Monday, 29 December 2014

How to set a Simple Timer with Atmega

This program is to show how to write a simple timer in atmel to make your own delay function using the timer.

The basic registers which we will use:

 1.   TCNTx : load the timer values

                  Timer 0 and Timer 2  >>  TCNT0/TCNT2  >>   8 bit timers hence  can store 00 to FF.

                  Timer 1 >>  TCNT1L, TCNT1H  >>  0000 to FFFF.

2. TCCRX : Timer / Counter Control Register

                 This controls the way in which timer will function.
                 Here our aim is to make a simple delay function so we will focus in last three bits only and set the                      remaining bits to 0

                These are the clock select bits which decides the frequency that will be used to run the timer.

                Now suppose you select a prescaler of 64. If the crystal frequency is 16Mhz, then the frequency of timer will become 16/64 = 0.25 Mhz.

                hence the TCNTx register will increment 2,50,000 times in a second or say once every 4 micro seconds.

NOTE : if the last 3 bits are 000, that means there is no clock source and the timer wont run..
This way you can turn off the timer.
 ANd when TCNTx again becomes zero, TIFR register comes into picture:

3. TIFR : Timer Interrupt Flag register

The bits of this register are the flags whose values will change when the TCNTx register overflows.

The flags are by default  zero and when overflow occurs, they are set. This flag has to cleared and to clear the flag, we have to write "1" to it!! 

Note : Each timer has its own ISR(Interrupt Service Routine). When overflow occurs, interrupt occurs and the code inside ISR will be executed.

Our code here is very simple..
 >> Set the value in TCTN0 register
>> Set the prescaler in TCCR0.
>> Wait till the Overflow occurs.

Waiting is not timers are meant for..

But this makes clear the basic functions of various registers.

Run it in proteus, and you can see the LED blinking.

Get the codes from here:

No comments:

Post a Comment

Powered by Blogger.