Why can't I use a global bool variable whose value depends on interrupt flags?

316 views Asked by At

I'm trying to wait for an interrupt to continue with the execution of the code, something like this:

bool flag = false;

void interrupt_handler (uintptr_t context)
{
    flag = true;
}

void main()
{
    CallbackRegister(event, interrupt_handler,0);
    while(!flag);
}

But it always stays in the while loop even when the interrupt occurs. Does anyone know why? I'm currently using MPLABX with a SAMD21J17 microcontroller.

2

There are 2 answers

1
Tom V On BEST ANSWER

You need to change:

bool flag = false;

to:

volatile bool flag = false;

The reason is that without volatile the compiler is allowed to assume that the flag never changes after it has been read once, but you want it to read the flag repeatedly.

2
netskink On

Hmm. I don't know that particular compiler but a quick check of the microchip compiler user guide says something which jumped out to me immediately.

You have a function named interrupt handler, but you don't have it identified with decorator. I suggest you look at this guide in section 5.8.1 "Writing an Interrupt Service Routine" where it says "Write each ISR prototype using the __interrupt() specifier".

So your routine would look like this at a minimum:

void __interrupt(high_priority) interrupt_handler (uintptr_t context) {
    flag = true;
}