Delay generation using Timer  
To generate precide time delays is just another use of timers in microcontrollers but in case if you are using WinAVR to compile your 'C' program. You do not need to use timers at all to generate time delays. As in WinAVR functions like _delay_ms(ms_delay) already are there to generate precise delay using machine cycle skip. This function uses nop; instruction to skip one machine cycle hence can generate precise time delays. It is known as software delay.

But still making delay function using timers is a good program to learn about timers.

Now consider the hello world led blinking circuit we made intially.



We are going to write a program to make LEd blink at every one second. But this time this 1 sec delay will be generated using hardware Timer1;

/***********************************************************************
Example program to demonstrate precise delay generation using Timer1.
ATmega8 running on 1MHz clock source
If we use a clock prescaler of 64
Effective clock at timer = 1MHz/64 = 15625 Hz.
So to generate delay of one sec value TCNT1 must be incremented to 15625 starting from zero.
***********************************************************************/


#include<avr/io.h>

int main(void)
{
DDRC = 0xFF; // PORTC as output
PORTC = 0xFF; Initially LED is Off
TCCR1B = (1<<CS10)|(1<<CS11); // Clock prescaler is set to divided by 64
while(1==1)
{
cbi(PORTC,5); // LED On
delay_1sec(); // 1 sec delay
sbi(PORTC,5); // LED Off
delay_1sec(); }
return 0;
}

void delay_1sec()
{
TCNT1=15625;
do
{
TCNT1=(TCNT1-1);
}while(TCNT1>0);
}

devesh@electroons.com
Best viewed at Firefox 1024x768 resolution