Tag Archives: 16bit timer

Timers in Compare Mode – Part II

Hello and welcome back to the discussion on the TIMERs in compare mode. In the last article we discussed the basics and the theory about using the timer in compare mode. Now its time to write some practical code and run it in real world. The project we are making is a simple time base which is very useful for other project requiring accurate computation of time like a digital clock or a timer that automatically switches devices at time set by user. You can use it for any project after understanding the basics. We will have three global variable which will hold the millisecond, second and minutes of time elapsed. These variables are automatically updated by the compare match ISR. Look at the figure below to get an idea how this is implemented. Fig – Using AVR Timer to generate 1ms Time base.     Complete Code #include <avr/io.h> #include <avr/interrupt.h> #include "lcd.h" //Global variable for the clock system volatile unsigned int clock_millisecond=0; volatile unsigned char clock_second=0; volatile unsigned char clock_minute=0; main() { //Initialize the LCD Subsystem InitLCD(LS_BLINK); //Clear the display LCDClear(); //Set up the timer1 as described in the //tutorial TCCR1B=(1<<WGM12)|(1<<CS11)|(1<<CS10); OCR1A=250; //Enable the Output Compare A interrupt TIMSK|=(1<<OCIE1A); LCDWriteStringXY(0,0,"Time Base Demo"); LCDWriteStringXY(0,1," : (MM:SS)"); //Enable interrupts globally sei(); //Continuasly display the time while(1) { LCDWriteIntXY(0,1,clock_minute,2); LCDWriteIntXY(3,1,clock_second,2); _delay_loop_2(0); […]