Counting High Frequency Pulses

Hi patrickfgarrett,

Here's some example code that uses the Arduino Uno's timer 1 clock input on D5, in order to count the number of pulses received. Meanwhile timer 2 is employed to generate a 500kHz test square wave on D11. Connecting D11 to D5 allows the timer 1 to be tested up to 500kHz. The code also includes an overflow counter to allow pulses to be counted over the 16-bits provided by timer 1:

// Set-up timer 1 to count pulses on digital pin D5, (with 500kHz test frequency on D11)
volatile uint32_t count;

void setup() { 
  Serial.begin(115200);                          // Initialise the serial port
  pinMode(11, OUTPUT);                           // Generate a 500kHz square wave test frequency on D11
  TCCR2A = _BV(COM2A0) | _BV(WGM21);             // Set timer 2 for CTC (Clear Timer on Compare Match) mode
  OCR2A = 15;                                    // Set the D11 output to toggle at 500kHz
  TCCR2B = _BV(CS20);                            // Enable timer clock without prescaler 
  TCCR1A = 0;                                    // Clear the TCCR1A register
  TCCR1B = _BV(CS12) | _BV(CS11) | _BV(CS10);    // Set T1 (D5) as the timer 1 clock source triggered on the rising edge 
  TIMSK1 = _BV(TOIE1);                           // Enable overflow interrupts on timer 1
}

void loop() {
  delay(10);                                    // Wait for 10ms (100Hz)
  noInterrupts();                               // Disable interrupts
  Serial.println(count << 16 | TCNT1);          // Print the number of pulses counted
  count = 0;                                    // Reset the overflow count to 0
  TCNT1 = 0;                                    // Reset timer 1 to 0
  interrupts();                                 // Enable interupts
}

ISR(TIMER1_OVF_vect) {                          // The timer 1 overflow interrupt service routine
  count++;                                      // Increment the overflow count
}

The code outputs the number of counted pulses every 10ms (or 100Hz) on the serial terminal. The output is as follows:

5004
5002
5002
5003
5004
5002
5002
5003
5004
5002
5003
5007
5006

This indicates that timer 1 is correctly counting the number of pulses at 500kHz with a small amount of jitter due to the delay() timing window and servicing the loop().