PIC16F1939 - Problem with Timer0 interrupt.

Thread Starter

hunterage2000

Joined May 2, 2010
487
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:
#include <pic16f1939.h>
#include <xc.h>
#define _XTAL_FREQ 500000 //1ms delay
void interrupt delay(void);
void main()
{
    ANSELA=0;
    TRISA=0;
    PORTA=0;
    OPTION_REG = 0b10001000; //WPU's disabled    No Prescaler
    INTCONbits.GIE = 1;
    INTCONbits.PEIE = 1;
    while(1)
    {
    ;      
    }
}

void interrupt delay()
{
    
    TMR0 = 0x00;
    INTCONbits.TMR0IF = 0;
    INTCONbits.TMR0IE = 1;
    while(!INTCONbits.TMR0IF)
    {
    PORTAbits.RA0 = !PORTAbits.RA0;
    INTCONbits.TMR0IE = 0;
   
    }
}
 

NorthGuy

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

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

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

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

C:
LATAbits.RA0 = !LATAbits.RA0
INTCONbits.TMR0IF = 0;
 

Thread Starter

hunterage2000

Joined May 2, 2010
487
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.
 
Top