Interruptions
Notes
- An interrupt is a signal from a physical device that causes the CPU to
- Save the current state of the computation
- Transfer control to an interrupt routine to handle the event.
- Return to the current state
- As such interrupts routines should be very short.
- The nano uses digital pins D2 and D3 for interrupts.
- On your board, the switch is wired to D2 as well as D4
- In my demo, the switches are wired to D3 through an OR gate
- To enable an interrupt
- Set the pin mode to be
INPUT_PULLUP-
pinMode(INTERRUPT_PIN, INPUT_PULLUP);
-
- Then attach the pin to a ISR via
attachInterrupt-
attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN),InputHandler, RISING); - There are several modes
- LOW - trigger when the value is low
- CHANGE - trigger when the value changes
- RISING - trigger when the pin goes from low to high
- FALLING - trigger when the pin goes from high to low.
-
- This assumes the function
InputHandleris present
- Set the pin mode to be
- In c++ the
volatilequalifier marks a variable as something that should not be cached.- We can not pass variables to/from an ISR
- So we communicate via global variables
- And we mark them as volatile to make sure the value is not cached.
- An ISR
- Should be very short
- Should not call delay, any Serial routines
- You should not use any other routines that depend on interrupts.
- Did the following
- Declare global
volatile bool BUTTON_HAPPENED{false}; -
void InputHandler(){ BUTTON_HAPPENED = true; digitalWrite(LED_BUILTIN, HIGH); } - And in my main routine
if(BUTTON_HAPPENED) { Serial.println("The button was pushed"); BUTTON_HAPPENED = false; digitalWrite(LED_BUILTIN, LOW); } else { Serial.println("The button was NOT pushed"); }
- Declare global
- There is more with interrupts, but this will do for now.