Main Content

Control AVR 8 bit Timer-Counter0 using AVR-GCC

Timers are very important part of embedded systems. They make your life much easier if used properly. Timers runs independently to main program flow, so they can do job independently without disturbing precious calculations done by CPU. You just set up the timer and let it run while your main program perform other tasks. Timers are really easy to set up. In this post an example is made for Atmega8 timers. Other AVR microcontroller models and even different brand ships have similar timers.

Atmega8 has two 8 bit timers/counters and one 16-bit timer counter with many abilities.

Standard 8-bit Timer/Counter0 features are:

- Single channel counter;
- Frequency generator;
- External Event counter;
- 10 – bit clock prescaler.

TCNT0 is 8 bit timer counter register which keeps the current count number. Timer counter can be clocked by an external clock through pin T0 or from internal via pre-scaller. Timer counter is incrementing (MAX value is 0xFF) and then restarts from BOTTOM=0x00. After timer Overflows, the flag TOV0 is written to 1 and if TOIE0 bit in SREG is set, then timer overflow interrupt is executed. TOV0 acts as a ninth bit of counter register that is only set but not cleared. When this bit is combined with timer overflow interrupt – then it is automatically cleared. If you need to start counter form different number rather than BOTTOM, then you can write any value to TCNT0 register at any time.

Prescaler may have values 1, 8, 64, 256, 1024. Like in picture you may see prescaling at 8 clock cycles.”

Link to article