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.

2
  • 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. Commented Apr 13, 2022 at 14:53
  • As others have said, you definitely need volatile. Q: Have you also confirmed that your event handler is actually called when an interrupt occurs? Commented Apr 13, 2022 at 15:06

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi @Tom V, this works, I rally appreciate 10/10. I need more experience with types of data.
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;
}

2 Comments

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.