1

For a bitbanging project I'm working on, I need to measure microseconds as accurately as possible. The function micros() won't work for me here because of the unpredictable times at which it might roll over. I have been using this project by Louis Frigon as an example:

https://web.archive.org/web/20140627135927/http://www.sigmaobjects.com/toyota/

In this document he sets his Atmega8's prescaler value:

// Timer 0 prescaler = 8 ( 1 count / us )
TCCR0 = _BV(CS01);

Do I understand that after these instructions, TCNT0 counts up by nearly precise microseconds? If so, what math could I use to set my prescaler for measuring microseconds? The 328P has a higher clock speed, does that mean I won't be able to do this?

Bo Thompson
  • 261
  • 1
  • 3
  • 13

1 Answers1

0

The 328P has a higher clock speed

The 328P will run at whatever speed you clock it, up to a maximum that depends on the supply voltage. Most 328P-based Arduinos are clocked at 16 MHz though.

what math could I use to set my prescaler for measuring microseconds?

You can't. You would have to set the prescaler to 16 if you want the timer to count microseconds. You can set it to 8 or to 64, but there is no intermediate setting in between.

Maybe you could leave the prescaler at 8 and count half-microseconds instead?


Edit: On the 328P, Timer 0 has two control registers, named TCCR0A and TCCR0B. To set it to normal counting mode at F_CPU/8, you have to:

TCCR0A = 0;
TCCR0B = _BV(CS01);

If you are programming in plain C, the first line is not needed (but it won't hurt either), as the initial value of TCCR0A is zero on reset. If you are using the Arduino core library (and you write setup() and loop() instead of main()), then you do need this first line, as the Arduino core configures Timer 0 for PWM at 977 Hz. But note that the Arduino core also uses Timer 0 for timekeeping (millis(), micros() and delay()). Thus you may want to use another timer.

You could switch to Timer 2 by replacing every “0” with a “2” on the register and bit names of the two lines above. Then you would also replace every occurrence of TCNT0 in the code with TCNT2.

Edgar Bonet
  • 45,094
  • 4
  • 42
  • 81