Software Code

Now we make the program code that shows thereal  time on the LCD display. We use the external crystal as the source for the asynchronous clock. The asyncronous clock is the time base for the real time clock. It will overflow TIMER2 128 times each second. The overflow will generate a interrupt that makes the program jump the the Interrupt Service Routine (ISR). In the ISR a counter counts to 128, when it reaches 128 it will increase the seconds counter. The seconds will be converted into minutes and hours.

// program name: timer2 asynchronous timer
// date: 2015.08.25
// target device: atmega8/atmega328p
// target: 1s interval for RTC
// author:
// compiler: AVR_GCC
// timer2 overflow interrupt service routine
#include <avr/io.h>
#include <util/delay.h>
#include <util/lcd.h>
#include <avr/interrupt.h>
unsigned char time_count; int second=0; int minute=19; int hour=11;

/// Timer 0 overflow interrupt service routine
TCNT2 = 0;//set timer second++;// increase second } int main void)
LCDini(); TIMSK=0;//disable timer2 interrupts ASSR=0b00001000;//set timer2 to asynchronous mode TCNT2=0;
TCCR2=0b0000101;// set prescaler to 1/128 while (ASSR&((1<<TCN2UB)|(1<<TCR2UB)));//wait for registers update TIFR=0b01000000;//clear interrupt flags TIMSK=0b01000000;// enable Timer2 overflow interrupt sei();// enable global interrupts LCDgoto(0,0);
LCDtxt(" TIMER2 Clock ");
charmystr[4]="";// save enough space for result itoa(second,mystr,10);// convert to ascii LCDgoto(0,1);
LCDtxt(mystr);// display in on LCD while(1) { }