This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Timer 2 as 5 sec timer

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 ?