7
\$\begingroup\$

Is there a way of telling if sei()/interrupts() or cli()/noInterrupts() was last called?

I need this to be able to enable interrupts, execute some code and set interrupts disable interrupts if they where disabled.

Here is some sample code:

void function_requiring_interrupts(void) {
    bool interruptsEnabled = getInterrupsState(); // what function / variable here?

    interrupts();

    // Code requiring interrups are enabled

    if(!interruptsEnabled) {
        noInterrupts();
    }
}
\$\endgroup\$

1 Answer 1

9
\$\begingroup\$

One way of doing this is to save, and then later restore the SREG status register, thus saving and later restoring the interrupt status to whatever it was, thus:

  uint8_t oldSREG = SREG; // Save the status
  cli();

  // Do stuff, as little as possible.

  SREG = oldSREG;

Also, the rationale described in the question has inherent problems: If some other code already had interrupts disabled, and your code enables interrupts, data corruption or program failure could occur. Any "interrupt-disabled" block of code would be expecting all registers and memory / variables to remain untainted, while enabling interrupts can cause that to change.

Therefore the reverse logic, as in the code fragment above, is best practice: Explicitly disable interrupts for your own code as needed, but restore interrupts as soon as possible, then proceed with the rest of your processing.

\$\endgroup\$
2
  • \$\begingroup\$ Anindo is right about the warning. You should never enable interrupts in a library or other call that is not specifically designed to do that. Code that has interrupts disabled did so for a reason and enabling interrupts in your library routine could cause all sorts of havoc with the other code. \$\endgroup\$
    – james
    Apr 19, 2013 at 16:46
  • \$\begingroup\$ Would it matter if an interrupt were to occur after saving the status register, but before disabling interrupts? \$\endgroup\$
    – Shepmaster
    May 14, 2016 at 23:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.