Posted by on Jun 29, 2011 in Atmel AVR, Microcontrollers | 43 comments

# AVR Timers – TIMER2

Hello friends! Welcome to the tutorial on the TIMER2 of AVR ATMEGA16/32. I hope that you have already come across and read the following posts, in which the basic concepts and applications of AVR Timers are discussed.

In this post, we will discuss about TIMER2. Since TIMER2 is an 8-bit timer (like TIMER0), most of the registers are similar to that of TIMER0 registers. Apart from that, TIMER2 offers a special feature which other timers don’t – Asynchronous Operation. We will discuss about it later.

Since you are already aware of the concepts (I assume so, or else refer to my previous posts), we will proceed the way we did in TIMER1 tutorial. We will implement both prescalers and interrupts in the same problem statement.

# Problem Statement

We need to flash an LED every 50 ms. We have an XTAL of 16 MHz. This is the same problem statement that we discussed in TIMER0 (the last one). We will implement the same using TIMER2.

### Methodology – Using Prescaler and Interrupt

As discussed in the TIMER0 tutorial, we use a prescaler of 256. For this, the overflow time is 4.096 ms. Thus the timer should overflow 12 times (MAX = 255) and count up to 53 in the 13th iteration, and then reset the timer. The formula used is as follows:Now let’s have a look at the TIMER2 registers.

# TCCR2 Register

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

TCCR2 Register

Since we will be dealing with the CTC mode later, we are only concerned with Bits2:0 – CS22:20 – Clock Select Bits. Unlike other timers, TIMER2 offers us with a wide range of prescalers to choose from. In TIMER0/1 the prescalers available are 8, 64, 256 and 1024, whereas in TIMER2, we have 8, 32, 64, 128, 256 and 1024!

Clock Select Bit Description

Since we are choosing 256 as the prescaler, we choose the 7th option (110).

# TCNT2 Register

In the Timer/Counter Register – TCNT2, the value of he timer is stored. Since TIMER2 is an 8-bit timer, this register is 8 bits wide.

TCNT2 Register

# TIMSK Register

The Timer/Counter Interrupt Mask – TIMSK Register is as follows. It is a register common to all the timers.

TIMSK Register

Here we are concerned with the 6th bit – TOIE2 – Timer/Counter2 Overflow Interrupt Enable. We set this to ‘1’ in order to enable overflow interrupts.

# TIFR Register

The Timer/Counter Interrupt Flag Register – TIFR is as follows. It is a register common to all the timers.

TIFR Register

Here we are concerned with the 6th bit – TOV2 – Timer/Counter2 Overflow Flag. This bit is set (one) whenever the timer overflows. It is cleared automatically whenever the corresponding Interrupt Service Routine (ISR) is executed. Alternatively, we can clear it by writing ‘1’ to it.

# Code

To learn about I/O port operations in AVR, view this. To know about bit manipulations, view this. To learn how this code is structured, view the TIMER0 post. To learn how to use AVR Studio 5, view this.

```#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 timer2_init()
{
// set up timer with prescaler = 256
TCCR2 |= (1 << CS22)|(1 << CS21);

// initialize counter
TCNT2 = 0;

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

// enable global interrupts
sei();

// initialize overflow counter variable
tot_overflow = 0;
}

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

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

// initialize timer
timer2_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 (TCNT2 >= 53)
{
PORTC ^= (1 << 0);    // toggles the led
TCNT2 = 0;            // reset counter
tot_overflow = 0;     // reset overflow counter
}
}
}
}```

So friends, this is how to operate TIMER2 in general mode. Other modes of operation will be discussed in upcoming posts. In the next post, we will learn about the Clear Timer on Compare (CTC) Mode and learn how to apply it to different timers.

1. hello
I want to make a frequency meter by Timer2 and I used 32768Khz crystal in order to make it accruate.
my question is that how can I set chip clock on 4MHz in present of crystal 32768Khz?

• Hello Behnam,
Your AVR can run on a single clock frequency, either 32.768 kHz or 4 MHz. If your fuses are set correctly, if you simply hook up the crystal across the XTAL pins with two 22pF capacitors in parallel, that should be good!

PS. Is it 32768 Hz or 32768 kHz that you mentioned?!

2. I’m really happy with your web, every aspect of the AVR microcontrollers is explained here. Sometimes read and understand direct from the datasheet is a hard work, but with your post we only need 5 minutes to understand.

Muchas gracias por los post,
Un saludo desde Colombia,
Andres Galvez.

• Muchas Gracias Andres! :)

3. 1st i must say nice explaination on timers.
now my question is ,u mentioned about the register “TIFR”
,but u didnt write any code for this register.give me some more explaination on this register

• TIFR register is a register containing the interrupt flags for all the timers. These flags are cleared automatically whenever the corresponding ISR is executed. Since we have implemented the ISR here, we don’t need to worry about these flags. In case you choose not to implement the ISR, then you’ll need to monitor these flags.

Good question! :)

4. Thank you max….. this tutorial is really helpful. Am wrking on ultrasonic sensor for wch I had to count the echo pulse that is being received. Cud u pls help me measuring the distance? And m using atmega64 controller & timer2-8bit counter.

• Which sensor are you using?

5. How do I know which timer to use out of the three…I mean are they problem-specific or just based on user’s choice?

6. with respect and in regarding to the code there is one mathematic error where we used ,explanation is here:
in 13th iteration of timer overflow ,timer must count 52 not 53 Whereas it is used 53 because timer count from 0 to 255 and 0.848/0.016=53 so (0 count to 52=53),,,,,thats all :)

• Yeah you’re right. I need to verify it. Once I do, I’ll change it. Thank you. Good that you figured it out without blindly following the code! :)

7. Max, I think your tutorials are excellent. Thank you.
However, I have had problems getting Timer0 and Timer2 to work using the tutorial code as model. I’m using the Atmel 328PB Mini xplained board, breaking the outputs to a breadboard populated with led’s. I’ve corrected the register names in keeping with the 328PB registers. The problem lies with the nested if’s. Using Timer2 as example. I’ve had to eliminate the nested IF and instead OR the second condition with the first. I know that ruins the integrity of the code as designed but I wanted to see if the led would illuminate and it does, although it is steady. I added a 200ms delay to flash the led.
Timer1 – worked great.

• If you are combining two nested if conditions, then use AND operation, not OR. If the LED is not flashing, which means it is not going to the inner if. So you need to figure out which one is it? Is it the outer if that fails or the inner if.

8. seriously. your blogs are best i say
plz provide CTC mode ink too

9. Excellent tutorials! There is a broken link in AVR Timers – TIMER0

• Thanks Carlos. I updated the link.

1. Timer Pada Mikrokontroler AVR - […] TIMER2, 8-bit timer […]

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