Do I need interrupts() noInterrupts() in the loop section?
Yes, you do. Always.
The optimal workflow is
- In the ISR itself, just raise a flag or directly change some global
- In the
loop you first copy that flag/variable to a local variable, using interrupts/noInterrupts to prevent the ISR changing the value while you are using/copying it.
Assignment are not atomic in Arduino World. That means that the value you are copying can change while you are doing it, and you end with garbage in your variables. Or, worse, it can change between one statement and the next. Try to debug that.
This is how you do it. In this example, I'm using an interrupt to manage a button (with debouncing). I need to detect state (pressed/not pressed) and timing (how long you pressed it). I can't directly use
loop; I copy it first so it won't change while I'm using it.
volatile unsigned long lastFallingEdge = 0; // For debouncing.
volatile boolean bPressed = false;
lastFallingEdge = millis();
bPressed = true;
bPressed = false;
unsigned long falling = lastFallingEdge;
unsigned long len = millis() - falling;
// Do something.