Hi all,
I've written this code to display time on an lcd. No problem, the code works but its losing seconds rapidly, about ten seconds in 3 minutes. obviously this needs to be reduced drastically!!
I'm using a mega32, with an 8mhz resonator and a 32.768Khz watch xtal on the TOSC pins. I'm using Timer0 interrupt at 2hz to update the display, and timer2 interrupt to get 1hz count out of the watch xtal in asynchronous mode. Both are using CTC mode.
Heres the code:
#include#include #include #include "lcd.h" #define bit_get(p,m) ((p) & (m)) #define bit_set(p,m) ((p) |= (m)) #define bit_clear(p,m) ((p) &= ~(m)) #define bit_flip(p,m) ((p) ^= (m)) #define bit_write(c,p,m) (c ? bit_set(p,m) : bit_clear(p,m)) #define BIT(x) (0x01 << (x)) #define LONGBIT(x) ((unsigned long)0x00000001 << (x)) volatile int sec = 0; volatile int min = 0; volatile int hrs = 0; volatile int tmpint = 0; volatile char tmpstr[3]; volatile char tempsec; volatile char tempmin; volatile char temphr; volatile int i=0; ///////////////////////////// // Timing routine ///////////////////////////// ISR(TIMER0_COMP_vect) // LCD Update Routine { //get 10xhrs if (sec < 10) { sprintf(tmpstr, "%d", sec); lcd_gotoxy(6,0); lcd_puts("0"); lcd_gotoxy(7,0); lcd_puts(tmpstr); } else { sprintf(tmpstr, "%d", sec); lcd_gotoxy(6,0); lcd_puts(tmpstr); } if (min < 10) { sprintf(tmpstr, "%d", min); lcd_gotoxy(3,0); lcd_puts("0"); lcd_gotoxy(4,0); lcd_puts(tmpstr); } else { sprintf(tmpstr, "%d", min); lcd_gotoxy(3,0); lcd_puts(tmpstr); } if (hrs < 10) { sprintf(tmpstr, "%d", hrs); lcd_gotoxy(0,0); lcd_puts("0"); lcd_gotoxy(1,0); lcd_puts(tmpstr); } else { sprintf(tmpstr, "%d", hrs); lcd_gotoxy(0,0); lcd_puts(tmpstr); } } ISR(TIMER2_COMP_vect) // Counting routine { PORTB ^= (1 << 0); // Toggle the LED sec++; if (sec==60) { min++; sec = 0; if (min==60) { hrs++; min = 0; if (hrs==24) { sec = 0; min = 0; hrs = 0; } } } } ISR(INT0_vect) { sec = 0; if (++hrs >= 24) { hrs = 0; } } ISR(INT1_vect) { sec = 0; if (++min >= 60) { min = 0; } } //////////////////////////// // MAIN //////////////////////////// void main() { init(); lcd_puts("Clock V2"); _delay_ms(1000); lcd_clrscr(); lcd_puts("00:00:00"); } ///////////////////////// // INIT function ///////////////////////// void init() { lcd_init(LCD_DISP_ON); lcd_clrscr(); DDRB |= (1 << 0); // Set LED as output MCUCR |=(1<<ISC11) | (1<<ISC01); // Set INT1 and INT0 to Falling Edge Triggered GICR |= (1<<INT0) | (1<<INT1); //turn on INT0 and INT1 TCCR0 |= (1<<WGM01) | (1<<CS02); // Set Timer 0 as ctc with 256 prescaler OCR0 = 15625; // set CTC to 32 for 1Hz operation TIMSK |= (1 << OCIE0); //Enable CTC interrupt TCCR2 |= (1<<WGM21) | (1<<CS22) | (1<<CS21) | (1<<CS20); // Set Timer2 as 1024 prescale, in CTC Mode OCR2 = 32; // set CTC to 32 for 1Hz operation ASSR |= (1<<AS2); // Set Asynchronous mode to use TOSC with 32.768khz watch xtal TIMSK |= (1 << OCIE2); // Enable CTC interrupt sei(); // enable global interrupts }
Any ideas?!? Thanks for your help!
Dave