Greetings everybody,
I am working on a project of making a timer which runs for 5 seconds and stops. I have selected timer 2 for this. I start the timer on key press and it runs for 5 seconds.
Below is the code for initializing the timer 2
void _init_timer(void) { T2CON = 0x80; /* 10000000 */ /*-------------------------------------- Overflow at every 10 ms. --------------------------------------*/ RCAP2H = 216; RCAP2L = 239; TL2 = RCAP2L; TH2 = RCAP2H; //SET HIGH PRIORITY FOR TIMER 2 INTERRUPT PT2 = 1; IPH |= 0x32; /*-------------------------------------- --------------------------------------*/ ET2 = 1; /* Enable Timer 2 Interrupts */ TR2 = 1; /* Start Timer 2 Running */ }
The timer 2 overflows at every 10ms so for 5 seconds it should over flow 500 times. I have set at variable var_counter to value 500 and as soon as timer 2 interrupt is raised i decrement the value of var_counter as below
void timer2_interrupt(void) interrupt 5 { TF2 = 0; var_counter --; if(var_counter == 0) { _disable_timer(); } }
The problem is that sometimes it runs exactly for 5 seconds and sometimes it stops withing the range of 5.1 to 5.3 seconds which means 100ms to 300ms more. How can i offset this error ?
Greetings Erik,
Well i use 89S8253 with 12Mhz external crystal. Yesterday i did some tweaking with my code and i got accuracy that i need. I have used timer 2 in 16bit auto reload mode. I have initialized timer 2 as below
RCAP2H = 216; RCAP2L = 239; TL2 = RCAP2L; TH2 = RCAP2H;
along with initialization of timer 2 i have also set the priority of timer interrupt with below code
PT2 = 1; IPH |= 0x32;