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.

Timer counter prescaler is controlled by writing values to TCCR0 register(refer to datasheet for specific values).

Prescaler counter may be reset by setting bit0 (PSR10) to one in to SFIOR register. This clears prescaler counter value and this affects both 8 bit timers. PSR10 is cleared automatically after timer reset is complete.

As this timer is simplest of all timers of AVR working with it is very simple:

#include <avr\io.h>
#include <avr\iom8.h>
#include <avr\interrupt.h>
#define outp(a, b) b = a

uint8_t led;
/* signal handler for timer interrupt TOV0 */
ISR(TIMER0_OVF_vect) {
int main(void) {
/* use PortB for output (LED) */
    outp(0xFF, DDRB);      
/*enable timer overflow interrupt*/
    outp((1<<TOV0), TIMSK);
/*set timer counter initial value*/
/*start timer without presscaler*/
	outp((1<<CS00), TCCR0);
/* enable interrupts */
/*Initial led value*/
    led =  0x00;
    for (;;) {
/* loop forever timer interupts will
change the led value*/
    outp(led, PORTB);

You can find a good timer calculator here:

One Comment:

  1. This is imported post from
    Please let us know if you face any errors

Leave a Reply

Your email address will not be published. Required fields are marked *