cmicrocontrolleratmelmplab-x

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


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.


Solution

  • 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.