1

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • How do you know that it always stays i while loop? Is there some code that follows that while? This problem is probably because of that the interrupt doesn't occur. – Kozmotronik Apr 13 '22 at 14:53
  • As others have said, you definitely need [volatile](https://barrgroup.com/embedded-systems/how-to/c-volatile-keyword). Q: Have you also confirmed that your event handler is actually called when an interrupt occurs? – paulsm4 Apr 13 '22 at 15:06

2 Answers2

2

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.

Tom V
  • 4,827
  • 2
  • 5
  • 22
0

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;
}
netskink
  • 4,033
  • 2
  • 34
  • 46
  • Hi netskink, I use the interrupt as it meant to be, taken direct from the library I'm using. It was a data type error. – Jairo Macías Apr 13 '22 at 15:23
  • The error was that the volatile decorator was missing? That is a valid point but I was thinking the routine was not hit when the interrupt occurs. I'm also curious how the compiler handles the change to the routine and returns. Typically the final return in assemble differs between a normal ret vs reti due to stack usage. – netskink Apr 13 '22 at 17:22