PIC16F1939 - Problem with Timer0 interrupt.

Discussion in 'Embedded Systems and Microcontrollers' started by hunterage2000, Apr 30, 2016.

  1. hunterage2000

    Thread Starter Active Member

    May 2, 2010
    400
    0
    Hi, I am trying to toggle an led using the rollover of timer0 but nothings happening. I have added the code I have used.
    Code (Text):
    1. #include <pic16f1939.h>
    2. #include <xc.h>
    3. #define _XTAL_FREQ 500000 //1ms delay
    4. void interrupt delay(void);
    5. void main()
    6. {
    7.     ANSELA=0;
    8.     TRISA=0;
    9.     PORTA=0;
    10.     OPTION_REG = 0b10001000; //WPU's disabled    No Prescaler
    11.     INTCONbits.GIE = 1;
    12.     INTCONbits.PEIE = 1;
    13.     while(1)
    14.     {
    15.     ;      
    16.     }
    17. }
    18.  
    19. void interrupt delay()
    20. {
    21.    
    22.     TMR0 = 0x00;
    23.     INTCONbits.TMR0IF = 0;
    24.     INTCONbits.TMR0IE = 1;
    25.     while(!INTCONbits.TMR0IF)
    26.     {
    27.     PORTAbits.RA0 = !PORTAbits.RA0;
    28.     INTCONbits.TMR0IE = 0;
    29.    
    30.     }
    31. }      
     
  2. NorthGuy

    Active Member

    Jun 28, 2014
    604
    121
    Remove these things from interrupt and include them in the initialization, and add timer initialization/enabling:

    Code (C):
    1. TMR0 = 0x00; // reset timer
    2. // *** must add timer initialization here
    3. // *** must enable timer here
    4. INTCONbits.TMR0IE = 1; // enable timer interrupt
    Inside the interrupt you only need (note I changed PORTA to LATA):

    Code (C):
    1. if (INTCONbits.TMR0IF && INTCONbits.TMR0IE) {
    2.   LATAbits.LATA0 = !LATAbits.LATA0
    3.   INTCONbits.TMR0IF = 0;
    4. }
    If you never disable the timer, you do not need to check for TMR0IE:

    Code (C):
    1. if (INTCONbits.TMR0IF) {
    2.   LATAbits.LATA0 = !LATAbits.LATA0
    3.   INTCONbits.TMR0IF = 0;
    4. }
    If you only have timer interrupt and no other interrupts, no need to check for anything:

    Code (C):
    1. LATAbits.RA0 = !LATAbits.RA0
    2. INTCONbits.TMR0IF = 0;
     
  3. hunterage2000

    Thread Starter Active Member

    May 2, 2010
    400
    0
    This problem has been solved now. I looked in the xc8 user guide and I needed to use the ei() function to enable interrupts. Cheers.
     
  4. NorthGuy

    Active Member

    Jun 28, 2014
    604
    121
    Not really. Setting GIE directly works just as well.
     
Loading...