Interrupts: Responding to Events Instantly
Interrupts allow your Arduino to respond to events immediately — even while the main loop is busy doing something else.
An interrupt causes the processor to pause what it's doing, run an Interrupt Service Routine (ISR), and then resume where it left off.
Attaching an Interrupt
const int buttonPin = 2;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
// Attach interrupt to pin 2 — trigger when pin falls from HIGH to LOW
attachInterrupt(digitalPinToInterrupt(buttonPin), buttonPressed, FALLING);
}
void loop() {
// Main loop runs normally
delay(1000);
}
// ISR — runs immediately when interrupt triggers
void buttonPressed() {
// This code runs IMMEDIATELY when button is pressed
// Even if main loop is doing something else!
}Interrupt Modes
| Mode | Triggers when |
|---|---|
LOW | Pin is LOW |
HIGH | Pin is HIGH |
CHANGE | Pin changes from HIGH to LOW or LOW to HIGH |
RISING | Pin goes from LOW to HIGH |
FALLING | Pin goes from HIGH to LOW |
ISR Rules
ISR functions have important restrictions:
- Must be void with no parameters
- Must be fast — don't use
delay()inside ISRs - Use
volatilefor variables shared between ISR and main loop
volatile bool buttonFlag = false;
void buttonPressed() {
buttonFlag = true; // Just set a flag, don't do complex work
}
void loop() {
if (buttonFlag) {
// Handle the button press in the main loop
buttonFlag = false;
}
}Debouncing with Interrupts
When using interrupts with buttons, debouncing becomes trickier because the interrupt fires on every bounce:
volatile unsigned long lastInterruptTime = 0;
volatile bool buttonPressed = false;
void buttonPressedISR() {
unsigned long interruptTime = millis();
// Ignore bounces within 200ms
if (interruptTime - lastInterruptTime > 200) {
buttonPressed = true;
lastInterruptTime = interruptTime;
}
}Key Takeaways
attachInterrupt()triggers an ISR when a pin changes state- ISRs must be fast — no delays or complex logic
- Use
volatilefor variables shared between ISR and main loop - DigitalPinToInterrupt() maps pin numbers to interrupt numbers
- Debounce mechanical switches even when using interrupts
Resources
- Arduino.cc - attachInterrupt: https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
- Video: Arduino Interrupts Tutorial - https://www.youtube.com/watch?v=Pgjjn3_Fyqo