Tag Archives: timer1

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); […]

Timers in Compare Mode – Part I

Hi Friends, In last tutorials we discussed about the basics of TIMERs of AVR. In this tutorial we will go a step further and use the timer in compare mode . In our first tutorial on timer we set the clock of the timer using a prescaler and then let the timer run and whenever it overflowed it informed us. This way we computed time. But this has its limitations we cannot compute time very accurately. To make it more accurate we can use the compare mode of the timer. In compare mode we load a register called Output Compare Register with a value of our choice and the timer will compare the current value of timer with that of Output Compare Register continuously and when they match the following things can be configured to happen. A related Output Compare Pin can be made to go high,low or toggle automatically. This mode is ideal for generating square waves of different frequency. It can be used to generate PWM signals used to implement a DAC digital to analog converter which can be used to control the speed of DC motors. Simply generate an interrupt and call our handler. On a compare match we can configure the timer to reset it self to 0. This is called CTC – Clear Timer on […]