Using a timer, could schedule any task at a specific time without making other task awaiting. In this example we use timer to create a one millisecond tick every time the TOV0 triggered.
I use this timer tick to schedule the time for an LED turn on and off.
Schematic Diagram. CPU clocks at 16 MHz. PB0 toggle an LED. |
Let do some calculation:
- The CPU clock period is T (CPU) = 1/(16000000 MHz) = 62.5 nano seconds.
- I set the prescaler to 1:256 (TCCR0=0x04). So the timer 0 input period T = 256 x 62.5 nano seconds = 16 micro seconds.
- To get one millisecond: (0.000001 second)/(0.000016 second) = 62.5 counts
- So, when TOV0 is set we assign TCNT0 = (256-62) = 194 counts or -62 counts.
Source code:
#include <avr/io.h>
//A variable to hold one milli second
unsigned int milliSecond=0;
unsigned int oneMilliDelay(void){
//Check if TIFR is set
if(TIFR&0x01){
//Preload TCNT0 to make 1 mS
TCNT0=-62;
//Clear flag
TIFR=0x01;
milliSecond+=1;
} return milliSecond;
}
int main(void)
{
//Set PortC to Output
DDRB=0xFF;
//Clear PortC
PORTB=0x00;
//Set 1:256 prescaler
TCCR0=0x04;
//Clear overflow flag
TIFR=0x01;
while (1)
{
if(oneMilliDelay()<1000) PORTB=0x01;
else PORTB=0x00;
if(oneMilliDelay()>2000) milliSecond=0;
/*Do other tasks*/
}
}
Back to main tutorial page ATMega32 tutorials in C with Atmel Studio 7.
No comments:
Post a Comment