Sunday, 11 June 2017

Generating a delay of 1s using timer in atmega8

Hello Friends,

In this tutorial, we will learn how to generate a delay of 1second using timer0 in atmega8.

We are writing the code in Avr studio 4.

Timer 0 is a 8-bit timer means we can feed any value from 0 (0x00) to 255 (0xff)

Timing Diagram
In this example, we are using prescaler of value8. Prescaler divides the base frequency (provided by crystal or internal rc oscillator).

Machine Cycle = 1/Fosc      (Fosc is 8 MHz)

M.C = 1/8 us or 0.125 us

Delay = (256-x) * 0.125 * Pre scaler  (Pre scaler = 8)

Delay = (256-x) * 0.125 *8 = (256 - x) us

Let us suppose we required a delay of 250 us

Here, x=6 which should be fed to timer counter register 

TCCR0 register
TCCR0=0x02;   // for prescaler 8

when the timer overflows i.e. passes 0xff, a flag (TOV0) is generated in TIFR register.
We have to detect this flag.
Let's start writing the code:  

#define F_CPU 8000000UL


void main()
int count=0;
DDRD=0xff;    // set o/p mode
TCNT0=6;   // initialize the timer 
TCCR0=0x02;  // 8 prescalar if no prescalar accuracy is much more
if(TIFR & 0x01)      // we will enter here after every 4us
TIFR=0x01;  // clear the flag

if(count>=4000)   // (4000 count = 1s)

Check the video:

No comments:

Post a Comment