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 ?
Hi,
My timer 2 over flows and generates interrupt at every 10ms, so to measure 1 second i need to count the timer 2 interrupt (1000/10) = 100 times. So this counting is done in my code as count down i.e. I initialize var_counter to 100 and count down it to 0 and at 0 I stop timer 2. Otherwise var_counter does not have any other special use.