I have an interrupt handler for my PIC 16 that should modify a global variable. The global variable is then read by main()
in an infinite loop.
For some reason, it seems that the global variable is being modified inside the interrupt handler, but that the modifications do not persist out of the interrupt handler. I am sure that:
- The interrupt handler is being called properly
- The handler modifies the global variable inside the handler
- The code in
main()
that reads the global variable is correct
Finally, I have been careful to declare the global variable as volatile
as recommended here.
What could explain that the global variable change in the interrupt handler does not persist to main()
?
[Note: My C code is compiled by XC8. Below is the full code of my reduced test case.]
#include <pic16f1824.h>
#include <xc.h>
volatile unsigned char buttonPress = 0b0;
void interrupt InterruptServiceRoutine(void) {
// Update the button press value
buttonPress = 0b1;
}
void main(void) {
// Make RA4 an output
TRISAbits.TRISA4 = 0b0;
// Turn off status LED
LATAbits.LATA4 = 0b0;
// Enable interrupts
INTCONbits.GIE = 0b1;
// Enable interrupt-on-change to wake from sleep
INTCONbits.IOCIE = 0b1;
// Make the RA2 pin a digital input
TRISAbits.TRISA2 = 0b1;
ANSELAbits.ANSA2 = 0b0;
// Interrupt on RA2 negedges
IOCANbits.IOCAN2 = 0b1;
while(1) {
if(buttonPress == 0b1) {
// Turn on LED <-- Never turns on
LATAbits.LATA4 = 0b1;
}
}
}
volatile
is not used. But since your sure you have, it may be an optimization with XC8 (that's the whole reason to use volatile, to prevent optimization.) You need to add your code or some example of it. \$\endgroup\$button_debounce()
\$\endgroup\$