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:



  1. Pauses the current task.

  2. Saves its state (registers, program counter).

  3. Jumps to an Interrupt Service Routine (ISR) to handle the event.

  4. 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:

BoardInterrupt Pins
Uno, Nano2, 3 (INT0, INT1)
Mega25602, 3, 18, 19, 20, 21
ESP32Almost any GPIO (configurable)
Arduino DueAll 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:

cpp
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).

cpp
void buttonPressed() {
  digitalWrite(LED_PIN, !digitalRead(LED_PIN)); // Toggle LED
}

(3) Detach Interrupt (Optional)

cpp
detachInterrupt(digitalPinToInterrupt(pin));

Example: Button Press Interrupt

cpp
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:

cpp
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).

评论

此博客中的热门博文

How To Connect Stm32 To PC?

What are the common HDL languages used in FPGA design?

How do you set up ADC (Analog-to-Digital Converter) in STM32?