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.

Using AVR Timers

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;

   //Initialize the LCD Subsystem
   //Clear the display

   //Set up the timer1 as described in the


   //Enable the Output Compare A interrupt

   LCDWriteStringXY(0,0,"Time Base Demo");
   LCDWriteStringXY(0,1,"  :   (MM:SS)");

   //Enable interrupts globally


   //Continuasly display the time


//The output compate interrupt handler
//We set up the timer in such a way that
//this ISR is called exactly at 1ms interval


The hardware is ATmega8-16PU running at 16MHz with a LCD Connected to it. I have used xBoard MINI to make the prototype. You can also use your own ATmega8 board. To make a board in your own see this. The output is displayed in a 16×2 character LCD module so please see the LCD interfacing tutorial for information about the connections and use. I recommend you to first setup and test the LCD interfacing because it will help you in many projects. If you have any problems setting it up please post a comment here or use the forum.eXtremeElectronics.co.in

xBoard MINI

Fig – xBoard MINI can be used to prototype many projects easily!



LCD interface with AVR MCU

Fig – The output of above program in 16×2 LCD module.



Goodbye for now. Meet you in next tutorials !!! And don’t forget to subscribe to my feed via email to receive latest tutorials direct in your mail box.



Avinash Gupta is solely focused on free and high quality tutorial to make learning embedded system fun !

More Posts - Website

Follow Me:
FacebookLinkedInGoogle Plus