Testing if interrupts are on

There are several posts that discuss turning interrupts off and on and the need for non-interrupt code to disable interrupts at appropriate times.

Saving the SREG is suggested for a routine that might be called from either an ISR or a non-ISR context.

uint8_t SaveSREG = SREG; // save interrupt flag noInterrupts(); // disable interrupts // do the protected task SREG = SaveSREG; // restore the interrupt flag

I expected to find a more standard way to do this task so I could write a routine that could be used on multiple platforms. My code would look like this:

bool interruptsWereOn = areInterruptsOn(); noInterrupts(); // do the protected task if (interruptsWereOn) interrupts();

What I can not find is a standard way of testing if interrupts are on. I expected this to be part of the noInterrupts(), interrupts() suite of library routines. That people would implement for each platform.

Hopefully I am wrong and there is a standard way, but, if not can I suggest that we add one?

No, there isn’t, because the interrupt hardware on different processors is vastly different. On the ARM-based Arduinos, the interrupt controller is 100% different, and enormously more complex, with multiple, nested, prioritized interrupts.

Regards,
Ray L.

On the AVR-based Arduino you would check the Global Interrupt Enable bit (bit 7) of the Status Register (SREG).

There's a simple way to tell if interrupts are on: don't turn them off.

Your code should try to minimise the time that interrupts are off. This means that the noInterrupts() and interrupts() are just a few lines apart in the code. That's not too difficult to read and understand. Don't ever allow one function to turn interrupts off and rely on another one later turning them on. This code should always be local to a function and usually local to one {} block.

Think off it this way -nointerrupt() turns off all the interrupts. And interrupts() returns them to the state they there in before the call of nointerrupts(). Dit cli/sei calls

So no need to know which individual interrupt was on or off before you started playing around.

For the rest look at avr/interrupt (Google).

Mark