I have written code to make a digital clock using timer1 and tested with Proteus (an Arduino simulator). That program has been downloaded into an Atmega8 and interfaced to an LCD display. Seconds are being counted perfectly in 1 second duration. But when second, minutes and hours are incremented to greater than 60 I see problems. To limit those value, I have written these instruction:
if (second==60) { second=0; }
But when the seconds reach 59, the LCD shows the next second's value randomly. For example: 59,09,19,29,39,49,59.....99,10,11,12,13,14.
Part of code:
unsigned int second=0;
unsigned int minute=0;
void init_timer1(void);
int main(void)
{ init_timer1(); sei();
Init_LCD();
while(1) { goto_position_X_Y(1,0);
sprintf(lcd,"second=%d",second);
Send_A_String(lcd);
goto_position_X_Y(2,0); // second line first position
sprintf(lcd,"minute=%d",minute);
Send_A_String(lcd);
} }
void init_timer1(void)
{ TCCR1B |=(1<< CS12); // prescaler set 256;new freq=31250;
TCCR1B |=(1<< WGM12);
TCNT1 =0; OCR1A= 3107; // 16 bit max count value 65535,
TIMSK |=(1<< OCIE1A) ;
}
ISR(TIMER1_COMPA_vect)
{ second++;
if(second==60)
{ second=0; }
minute=minute+(second/60);
if(minute==60)
{ minute=0; } }