More like:
// Measures the HIGH width, LOW width, frequency, and duty-cycle of a pulse train
// on Arduino NANO Pin 8 (ICP1 pin).
// Note: Since this uses Timer1, Pin 9 and Pin 10 can't be used for
// analogWrite().
void setup()
{
Serial.begin(9600);
while (!Serial);
// For testing, uncomment one of these lines and connect
// Pin 3 or Pin 5 to Pin 8
// analogWrite(3, 64); // 512.00, 1528.00, 2040.00, 25.10%, 490.20 Hz
// analogWrite(5, 64); // 260.00, 764.00, 1024.00, 25.39%, 976.56 Hz
noInterrupts (); // protected code
// reset Timer 1
TCCR1A = 0;
TCCR1B = 0;
TCNT1 = 0;
TIMSK1 = 0;
TIFR1 |= _BV(ICF1); // clear Input Capture Flag so we don't get a bogus interrupt
TIFR1 |= _BV(TOV1); // clear Overflow Flag so we don't get a bogus interrupt
TCCR1B = _BV(CS10) | // start Timer 1, no prescaler
_BV(ICES1); // Input Capture Edge Select (1=Rising, 0=Falling)
TIMSK1 |= _BV(ICIE1); // Enable Timer 1 Input Capture Interrupt
TIMSK1 |= _BV(TOIE1); // Enable Timer 1 Overflow Interrupt
interrupts ();
}
volatile uint16_t Overflows = 0;
ISR(TIMER1_OVF_vect)
{
Overflows++;
}
ISR(TIMER1_CAPT_vect)
{
static uint32_t previousRisingEdgeTime = 0;
uint32_t thisRisingEdgeTime;
uint16_t overflows = Overflows;
// If an overflow happened but has not been handled yet
// and the timer count was close to zero, count the
// overflow as part of this time.
if ((TIFR1 & _BV(TOV1)) && (ICR1 < 1024))
overflows++;
// Interrupted on Rising Edge
thisRisingEdgeTime = overflows; // Upper 16 bits
thisRisingEdgeTime = (thisRisingEdgeTime << 16) | ICR1;
uint32_t pulseDuration = thisRisingEdgeTime - previousRisingEdgeTime;
previousRisingEdgeTime = thisRisingEdgeTime;
// This is a good place to add 'pulseDuration' to the median filter.
// Make sure the median filter is marked 'volatile'.
}
void loop()
{
static uint32_t previousMedian;
uint32_t thisMedian;
noInterrupts();
// This would be where you get 'thisMedian'
// from the median filter.
interrupts();
// If a sample has been measured
if (thisMedian != previousMedian)
{
// Display the pulse length in microseconds
Serial.print("Pulse time (microseconds): ");
Serial.println(thisMedian / 16.0, 2);
previousMedian = thisMedian;
}
}