Posted by on Jun 24, 2011 in Atmel AVR, Microcontrollers | 278 comments # AVR Timers – TIMER0 Hello friends! Welcome back to the second part of the AVR Timers Series. In the previous post, we have discussed the basic concepts of AVR Timers. Let me summarize it:

• We have seen how timers are made up of registers, whose value automatically increases/decreases. Thus, the terms timer/counter are used interchangeably.
• In AVR, there are three types of timers – TIMER0, TIMER1 and TIMER2. Of these, TIMER1 is a 16-bit timer whereas others are 8-bit timers.
• We have seen how prescalers are used to trade duration with resolution.
• We have also discussed how to choose an appropriate value of a prescaler.
• And then, to finish off, we learnt about interrupts.

So, I will move towards its implementation directly. I have assumed that you have understood the concepts discussed above.

In this tutorial, we will learn to use TIMER0. Since timer is a peripheral, it can be activated by setting some bits in some registers. Instead of discussing all the registers at once, we will be discussing them as and when necessary. For those who are new to the term ‘register’, they can read about it from this page. To have an idea about AVR Peripherals, view this page (you need to scroll down a bit).

# Problem Statement

Let’s define a problem statement for us. The simplest one being the LED flasher. Let’s say, we need to flash an LED every 6 ms and we are have a CPU clock frequency of 32 kHz.

Well, I know that an LED flashing at every 6 ms will be always visible as on by our eye, but I could not find any simpler example which does not include prescalers. Take this as a demonstration.

# Methodology

Now, as per the following formula, with a clock frequency of 32 kHz and 8-bit counter, the maximum delay possible is of 8 ms. This is quite low (for us, but not for the MCU). Hence for a delay of 6 ms, we need a timer count of 191. This can easily be achieved with an 8-bit counter (MAX = 255). Thus, what we need to do is quite simple. We need to keep a track of the counter value. As soon as it reaches 191, we toggle the LED value and reset the counter. For this, we need the help of the following registers.

### TCNT0 Register

The Timer/Counter Register – TCNT0 is as follows:

This is where the uint 8-bit counter of the timer resides. The value of the counter is stored here and increases/decreases automatically. Data can be both read/written from this register.

Now we know where the counter value lies. But this register won’t be activated unless we activate the timer! Thus we need to set the timer up. How? Read on…

### TCCR0 Register

The Timer/Counter Control Register – TCCR0 is as follows:

Right now, we will concentrate on the highlighted bits. The other bits will be discussed as and when necessary. By selecting these three Clock Select Bits, CS02:00, we set the timer up by choosing proper prescaler. The possible combinations are shown below.

For this problem statement, we choose No Prescaling. Ignore the bits highlighted in grey. We will be using it later in this tutorial. Thus, we initialize the counter as:

`TCCR0 |= (1 << CS00);`

Please note that if you do not initialize this register, all the bits will remain as zero and the timer/counter will remain stopped.

Thus now we are ready to write a code for this. To learn about I/O port operations in AVR, view this. To know about bit manipulations, view this.

### Code

```#include <avr/io.h>

void timer0_init()
{
// set up timer with no prescaling
TCCR0 |= (1 << CS00);

// initialize counter
TCNT0 = 0;
}

int main(void)
{
// connect led to pin PC0
DDRC |= (1 << 0);

// initialize timer
timer0_init();

// loop forever
while(1)
{
// check if the timer count reaches 191
if (TCNT0 >= 191)
{
PORTC ^= (1 << 0);    // toggles the led
TCNT0 = 0;            // reset counter
}
}
}```

I guess the code is pretty simple and straightforward. It doesn’t need any explanation. Or maybe one thing needs explanation. In the if statement, I have used

`if (TCNT0 >= 191)`

`if (TCNT0 == 191)`

This is because sometimes due to missed compares or unexpected increment, this condition may never be true. Thus to remain on the safer side, we use ‘>=’ instead of ‘==’.

# Problem Statement Redefined

Now let’s change the above problem statement to the following. We need to flash an LED every 8 ms and we have an XTAL of 16 MHz. Well, 8 ms is still low, but it’s good enough for the following illustration.

### Methodology – Using Prescalers

Now since the CPU clock frequency is 16 MHz, the maximum time delay that it can measure is 16 μs! But 8 ms (which is quite a small duration for us) is way much larger. So what do we do? Yes, you guessed right (I hope so ;))! We use a prescaler in order to trade duration with resolution. Now the following table summarizes the results of using different prescalers 8, 64, 256 and 1024. See previous tutorial for details.

From the values of the counter, we can easily rule out the top three prescalers as they are above the maximum limit of an 8-bit counter (which is 255). Thus we use a prescaler of 1024. Now refer to the descriptions of clock select bits as shown in the TCCR0 register. Have a look at the selection highlighted in grey. This implements a prescaler of 1024. The rest remains the same. Moving to the coding part, we simply change the initialize function and the compare value. The rest remains the same.

### Code

```#include <avr/io.h>

void timer0_init()
{
// set up timer with prescaler = 1024
TCCR0 |= (1 << CS02)|(1 << CS00);

// initialize counter
TCNT0 = 0;
}

int main(void)
{
// connect led to pin PC0
DDRC |= (1 << 0);

// initialize timer
timer0_init();

// loop forever
while(1)
{
// check if the timer count reaches 124
if (TCNT0 >= 124)
{
PORTC ^= (1 << 0);    // toggles the led
TCNT0 = 0;            // reset counter
}
}
}```

# Problem Statement Redefined Again!

Now let’s change the problem statement to something you can actually see! Let’s flash an LED every 50 ms (you can surely see the LED flashing this time ;)). We have an XTAL of 16 MHz.

### Methodology – Using Interrupts

So now, we have to flash the LED every 50 ms. With CPU frequency 16 MHz, even a maximum delay of 16.384 ms can be achieved using a 1024 prescaler. So what do we do now? Well, we use interrupts.

The concept here is that the hardware generates an interrupt every time the timer overflows. Since the required delay is greater than the maximum possible delay, obviously the timer will overflow. And whenever the timer overflows, an interrupt is fired. Now the question is how many times should the interrupt be fired?

For this, let’s do some calculation. Let’s choose a prescaler, say 256. Thus, as per the calculations, it should take 4.096 ms for the timer to overflow. Now as soon as the timer overflows, an interrupt is fired and an Interrupt Service Routine (ISR) is executed. Now,

50 ms ÷ 4.096 ms = 12.207

Thus, in simple terms, by the time the timer has overflown 12 times, 49.152 ms would have passed. After that, when the timer undergoes 13th iteration, it would achieve a delay of 50 ms. Thus, in the 13th iteration, we need a delay of 50 – 49.152 = 0.848 ms. At a frequency of 62.5 kHz (prescaler = 256), each tick takes 0.016 ms. Thus to achieve a delay of 0.848 ms, it would require 53 ticks. Thus, in the 13th iteration, we only allow the timer to count up to 53, and then reset it. All this can be achieved in the ISR as follows:

```// global variable to count the number of overflows
volatile uint8_t tot_overflow;

// TIMER0 overflow interrupt service routine
// called whenever TCNT0 overflows
ISR(TIMER0_OVF_vect)
{
// keep a track of number of overflows
tot_overflow++;
}

int main(void)
{
// connect led to pin PC0
DDRC |= (1 << 0);

// initialize timer
timer0_init();

// loop forever
while(1)
{
// check if no. of overflows = 12
if (tot_overflow >= 12)  // NOTE: '>=' is used
{
// check if the timer count reaches 53
if (TCNT0 >= 53)
{
PORTC ^= (1 << 0);    // toggles the led
TCNT0 = 0;            // reset counter
tot_overflow = 0;     // reset overflow counter
}
}
}
}```

Please note that the code is not yet ready. Not until you learn how to enable the interrupt feature. For this, you should be aware of the following registers.

### TIMSK Register

The Timer/Counter Interrupt Mask – TIMSK Register is as follows. It is a common register for all the three timers. For TIMER0, bits 1 and 0 are allotted. Right now, we are interested in the 0th bit TOIE0. Setting this bit to ‘1’ enables the TIMER0 overflow interrupt.

### TIFR Register

The Timer/Counter Interrupt Flag Register– TIFR is as follows. Even though we are not using it in our code, you should be aware of it.

This is also a register shared by all the timers. Even here, bits 1 and 0 are allotted for TIMER0. At present we are interested in the 0th bit TOV0 bit. This bit is set (one) whenever TIMER0 overflows. This bit is reset (zero) whenever the Interrupt Service Routine (ISR) is executed. If there is no ISR to execute, we can clear it manually by writing one to it.

In this example, since we are using ISR, we need not care about this bit (thus this register as a whole).

Enabling Global Interrupts

In the AVRs, there’s only one single bit which handles all the interrupts. Thus, to enable it, we need to enable the global interrupts. This is done by calling a function named sei(). Don’t worry much about it, we simply need to call it once, that’s all.

### Final Code

```#include <avr/io.h>
#include <avr/interrupt.h>

// global variable to count the number of overflows
volatile uint8_t tot_overflow;

// initialize timer, interrupt and variable
void timer0_init()
{
// set up timer with prescaler = 256
TCCR0 |= (1 << CS02);

// initialize counter
TCNT0 = 0;

// enable overflow interrupt
TIMSK |= (1 << TOIE0);

// enable global interrupts
sei();

// initialize overflow counter variable
tot_overflow = 0;
}

// TIMER0 overflow interrupt service routine
// called whenever TCNT0 overflows
ISR(TIMER0_OVF_vect)
{
// keep a track of number of overflows
tot_overflow++;
}

int main(void)
{
// connect led to pin PC0
DDRC |= (1 << 0);

// initialize timer
timer0_init();

// loop forever
while(1)
{
// check if no. of overflows = 12
if (tot_overflow >= 12)  // NOTE: '>=' is used
{
// check if the timer count reaches 53
if (TCNT0 >= 53)
{
PORTC ^= (1 << 0);    // toggles the led
TCNT0 = 0;            // reset counter
tot_overflow = 0;     // reset overflow counter
}
}
}
}```

So friends, we are done with the basics of TIMER0. What remains to be discussed in it are CTC Mode and PWM Mode. We will be discussing them in upcoming posts. In the next post, we will discuss how to apply the same concepts to use TIMER1, and then to TIMER2.

Till then, enjoy flashing LEDs at different intervals! ;)

And please comment below to encourage me to keep on updating interesting stuffs! :) Also you can grab the RSS Feeds or subscribe to my blog to stay updated!

Thank You!

1. Sir,
I want to create a 38khz square wave readable for a tsop. how can i do that?

2. its amazing explanation thank you very very very much ……

3. Excellent tutorial, Timers have always been a weak area of mine, and I have got by using various libraries to complete the task, but now my intended application needs more precise timing and interrupts away from the main program, so I am having to learn.

I’m programming an ATMega328p. with an LED on PD6. I had errors compiling, so I referenced that datasheet and noticed that the CS00…CS02 bits where at TCCR0B so I changed the line to TCCR0B |= (1 << CS02) | (0 << CS01) | (1 << CS00); for a clkI/1024 prescale and TCNT0 to 255. This gave me around about a 30ms pulse on the led that I could actually visualise. So now I understand about setting up a basic clock. I intend to spend a bit more time, until I can confidently setup a clock to any frequency I need, before moving on.

4. Hi..I want to toggle 3 led’s with three diffrent timer interrupts….How Can I do that???
I want to toggle leds with diffrent ON OFF time..

5. Thank U.. Excellent Post!!

6. Thanks for such a nice Blog . . . . It’s immense pleasure to read your Blog. It clears any genuine doubt . .

7. Your blog including your previous post discussing the timers and interrupt are amazing. Keep doing this as you are assisting many people around the world including myself.

I understand completely what you are teaching, though my problem is that i am trying to program in Ada. Making it hard to find resources online. However, knowing theses steps is beneficial for any language. So…

Thanks a mill

Best regards

Jord

8. Hi, im a total noob, your articles are great and very well explained, I have avery dumb doub maybe haha; in all the tutorials of arduino coding that I seen, always structure the program with “void setup()[]” and “void loop()” so, why you use “main” and other functions instead “void setup and loop”?

thanks :)

9. Really helpful and makes things much easier.

Got a question:
why when I write the last program without giving “volatile” to the var “uint8_t tot_overflow”, the program doesn’t work?

10. I tried this code, but it does not work. Can you help me about it?

#define F_CPU 16000000UL
#include
#include

volatile unit8_t count;

void main()
{
// here we shall use prescaler to divide the clock frequency
// of 16MHz to 15625Hz

TCCR0=TCCR0|00000101;

// Now we shall enable the OVERFLOW INTERRUPT ENABLE

TIMSK=TIMSK|00000001;

// Now the following command initialises internal counter from ‘0’

TCNT0=0;

// Starting variable count

count=0;

// setting PORTD as output port

DDRD=0b11111111;

// Now this command enables global interrupts

sei(); // The “cli();” clears global interrupts

while(1)
{

// Following command is the ISR (Interrupt Service Routine) for
// TIMER0 overflow interrupt
// The MUC calls this, each time TIMER0 overflows
ISR(TIMER0_OVF_vect)
{
count++; // incrementing variable by ‘1’

// Applying condition for the ‘count’ variable

if(count==61)
{
PORTD=~PORTD;
count=0;
}

}

}

11. Thank you very much
Realy Best tutoria
l

12. Super !

13. hey dude,
in first code there is no use of tifr resistor so isnt it wrong?
the code is not running as it should run.

14. That definitely will help me at my exam next week!

15. What wold be the changes if I want to use Atmega128 ??????

• Thanks for writing this. Your articles are so great and easy to understand.😁

16. I wrote this code sir but got no output on serial monitor!!!!

void setup() {
Serial.begin(9600);
pinMode(13,OUTPUT);
TCCR1A = 0;
TCCR1B|=((1<<WGM12)|(1<<CS12));
TCNT1=0;
TIMSK1|=(1<<OCIE1A)|(1<<OCIE1B);

OCR1A=31249;
OCR1B=15624;

}
ISR (TIMER1_COMPA_vect)
{
Serial.println(millis());
}
ISR (TIMER1_COMPB_vect)
{
Serial.println(millis());
}

void loop() {
// put your main code here, to run repeatedly:

}

• I suspect that you are stomping on a timer used by the Serial class in arduino. The avr core uses the timers for a variety of uses including maintaining the serial Rx/Tx buffers. This tutorial was written for use with Atmel Studio and raw avr-gcc code.

17. Thanks a lot,
it helped me understanding in a better way.

This site uses Akismet to reduce spam. Learn how your comment data is processed.