What is an interrupt and how to use it in Arduino?
What is an Interrupt?
An interrupt is a signal that temporarily stops the normal execution of a program to handle a specific event. When an interrupt occurs, the microcontroller:
Pauses the current task.
Saves its state (registers, program counter).
Jumps to an Interrupt Service Routine (ISR) to handle the event.
Resumes the original task once the ISR completes.
Interrupts are useful for:
Real-time responses (e.g., button presses, sensor triggers).
Efficiency (no need for constant polling).
Power saving (sleep modes wake on interrupt).
Using Interrupts in Arduino
Arduino supports hardware interrupts (triggered by external signals) and software interrupts (timers, etc.).
1. Hardware Interrupts
Most Arduino boards have pins dedicated to interrupts:
Board | Interrupt Pins |
---|---|
Uno, Nano | 2, 3 (INT0, INT1) |
Mega2560 | 2, 3, 18, 19, 20, 21 |
ESP32 | Almost any GPIO (configurable) |
Arduino Due | All pins (but limited IRQ numbers) |
2. Steps to Use Interrupts in Arduino
(1) Attach an Interrupt
Use attachInterrupt()
to link a pin to an ISR:
attachInterrupt(digitalPinToInterrupt(pin), ISR, mode);
pin
→ The interrupt-capable pin (e.g.,2
on Uno).ISR
→ The function to call when the interrupt triggers.mode
→ When the interrupt should fire:RISING
(low → high)FALLING
(high → low)CHANGE
(any voltage change)LOW
(stays low)
(2) Write the ISR
Keep it short and fast (no delay()
, Serial.print()
can cause issues).
void buttonPressed() { digitalWrite(LED_PIN, !digitalRead(LED_PIN)); // Toggle LED }
(3) Detach Interrupt (Optional)
detachInterrupt(digitalPinToInterrupt(pin));
Example: Button Press Interrupt
const int BUTTON_PIN = 2; // Interrupt-capable pin (Uno/Nano: 2 or 3) const int LED_PIN = 13; void setup() { pinMode(LED_PIN, OUTPUT); pinMode(BUTTON_PIN, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), toggleLED, FALLING); } void loop() { // Main code keeps running (interrupts work in the background) delay(1000); // Not blocked by button press } void toggleLED() { digitalWrite(LED_PIN, !digitalRead(LED_PIN)); }
FALLING mode detects when the button is pressed (signal goes HIGH → LOW due to
INPUT_PULLUP
).
Important Notes
✔ Minimize ISR runtime (avoid delays, complex math).
✔ Use volatile variables if sharing data between ISR and main code:
volatile bool buttonPressed = false;
✔ Debounce buttons (hardware: capacitor + resistor; software: delay checks).
✔ Not all pins support interrupts (check your board’s datasheet).
Alternatives
Polling: Continuously check a pin state in
loop()
(simpler but less efficient).Timer Interrupts: Trigger actions at fixed intervals (e.g.,
TimerOne
library).
评论
发表评论