Timers in AVR
Timers in AVR
AVR Timer
Normal mode
• In this mode, the contents of timer/counter increments with the clock. It counts until it reaches $FF
• When it rolls over from $FF to $00, it sets a flag bit TOV0
Steps to program in normal mode:
1. Load TCNT0 register with initial count value.
2. Load TCCR0 register indicating mode and prescaler option to be used.
3. Keep monitoring the timer overflow flag TOV0 to see if it is raised. Get out of the
loop when TOV0 becomes high.
4. Stop the timer by disconnecting the clock source with following instruction
LDI R16,0x00
OUT TCCR0,R16
5. Clear TOV0 flag for the next round by writing 1 to that bit of TIFR register.
6. Go back to step 1 and repeat the same.
Timer 0 Normal Mode Programming in AVR Microcontroller
1. Tclock=1/Ftimer (If we use prescaler than we need to divide base frequency with
that and finally inverse it to have Tclock)
2. Divide the desired time delay by Tclock. This says how many clocks we need.
3. Perform 256 - n, where n is the decimal value we got in step 2
4. Convert result of step 3 in to hex
5. Set TCNTO = Hex number of step 4
Example in C
#include <avr/io.h>
#define F_CPU 8000000UL
void TODelay(); // function declaration
int main(void)
{
DDRB |= (1<<3); // Make PB3 an o/p port
while(1)
{
PORTB = PORTB ^ (1<<3); // Toggle PB3
TODelay();
}
int main(void)
{
DDRB |= (1<<3); // Make PB3 an o/p port while(1)
{
PORTB| = (1<<3); // Set PB3
T0Delay(1);
PORTB&=~(1<<3);
T0Delay(9);
}
return 0;
}