Please help me understand this code

I've done some tests to see how the code from post #1 performs.
I used a Function Generator to provide pulses to pins 2 and 5 of an Arduino Uno R3.

Here is a 100us pulse, once per second on pin 2 (yellow trace), and a 100kHz signal going to pin5 (blue trace).
The code wrongly counts 3 pulses, instead of 10.
This error is due to the printing of "Ready ... " in the ISR.

Remove that printing of "Ready ... ", and the code will count correctly up to at least 200kHz:

But at frequencies above approximately 300kHz, we get extra pulses being counted.
I believe that this is due to the time taken for the ISR to stop the counting when the signal on pin 2 goes low.

At a frequency of 2MHz we count between 22 and 24 pulses instead of 20 in a time of 10µs:

At 2 MHz, we still count an extra 2 - 4 pulses if the sampling time is increased to 100µs:

The counter will in fact work with frequencies up to 8MHz:

1 Like