TIMER to count for 1 second

Discussion in 'The Projects Forum' started by honeymustard909, Aug 29, 2011.

  1. honeymustard909

    honeymustard909 Thread Starter New Member

    Joined:
    Jul 27, 2011
    3
    0
    Hi there i was wondering if any of you could help me out here . Basically, i need a Timer to count down a time limit which is used to turn off my device after the specified time limit. My pic18f46k20 is running at 1MHz and it is a 16 bit counter . (65536x(1/250KHz) = approx 1 second. I was wondering if this is a correct approach . The period_counter is to increase the second after the timer finish counting from 0-65536 . However to get 1 second , i have to set the period counter to 4000 instead of just 1 . I thought that the timer takes approx 1 second to finish counting.


    INTCONbits.TMR0IF = 0; // clear roll-over interrupt flag
    T0CON = 0b00000001; // pre scale 1:4
    TMR0H = 0x00; // clear timer
    TMR0L = 0x00;
    T0CONbits.TMR0ON = 1;

    void timer (void)
    {
    if ( INTCONbits.TMR0IF == 1 )
    {
    TMR0H= 0x00;
    TMR0L= 0x00;
    period_counter++;
    }
    }
    if ( period_counter > 4000 ) // 1 second
    {

    LATDbits.LATD7 = 1;
    period_counter = 0;
    counter_second ++;
    }
     
    #1
  2. honeymustard909

    honeymustard909 Thread Starter New Member

    Joined:
    Jul 27, 2011
    3
    0
    Why does it takes 4500 to generate a second ?

    void main (void)
    {
    //Init the output ports
    TRISD = 0b01111111; // RD7 as output

    //Init oscillator frequency
    // OSCCON = 0b00110110; // to set the frequency to 16MHz
    // OSCTUNE = 0b01011111;

    // Init Timer
    INTCONbits.TMR0IF = 0; // clear roll-over interrupt flag
    // INTCONbits.TMR0IE = 1; //enable interrupt flag
    T0CON = 0b00001000; //counts 16 bits no prescaler use internal oscillator
    TMR0H = 0x80; // clear timer
    TMR0L = 0x00;
    T0CONbits.TMR0ON = 1; // start timer
    while (1)
    {
    timer();
    counting();
    seconds();
    // minutes();
    }
    }
    void timer(void)
    {
    if (INTCONbits.TMR0IF == 1)
    {
    TMR0L = 0xFF;
    TMR0H = 0xFF;
    period_counter++;
    }
    }
    void counting (void)
    {
    if ( period_counter > 4500 ) // 1 second (4000)
    {
    LATDbits.LATD7 = 1;
    period_counter = 0;
    counter_second ++;
    }
    }
    void seconds (void)
    {
    if (counter_second > 1)
    {
    LATDbits.LATD7 =0;
    counter_second =0;
    counter_minute =0;
    counter_hour =0;
    }
    }
     
    #2
Loading...