0
0
AutocadHow-ToBeginner · 3 min read

How to Use attachInterrupt in Arduino: Simple Guide

Use attachInterrupt(digitalPinToInterrupt(pin), ISR, mode) to run a function when an interrupt event happens on a pin. This lets your Arduino respond immediately to changes like button presses or sensor signals without waiting in the main program.
📐

Syntax

The attachInterrupt() function connects an interrupt to a specific pin and tells Arduino what to do when the interrupt triggers.

  • digitalPinToInterrupt(pin): Converts the pin number to the interrupt number.
  • ISR: The name of the function to run when the interrupt happens. This function must take no parameters and return nothing.
  • mode: Defines when the interrupt triggers. Options are LOW, CHANGE, RISING, or FALLING.
arduino
attachInterrupt(digitalPinToInterrupt(pin), ISR, mode);
💻

Example

This example turns on the built-in LED when a button connected to pin 2 is pressed using an interrupt.

arduino
const int buttonPin = 2;
const int ledPin = LED_BUILTIN;
volatile bool ledState = false;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(buttonPin), toggleLED, FALLING);
}

void loop() {
  if (ledState) {
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }
}

void toggleLED() {
  ledState = !ledState;
}
Output
When the button on pin 2 is pressed, the built-in LED toggles ON or OFF immediately.
⚠️

Common Pitfalls

  • Interrupt function must be short: Keep the ISR (interrupt service routine) fast and simple to avoid missing other interrupts.
  • No delay or Serial inside ISR: Avoid using delay() or Serial.print() inside the interrupt function because they can cause problems.
  • Use volatile variables: Variables shared between ISR and main code should be declared volatile to prevent optimization issues.
  • Pin compatibility: Not all pins support interrupts; check your Arduino model's documentation.
arduino
/* Wrong way: Using delay inside ISR (do NOT do this) */
void wrongISR() {
  // delay(100); // This will cause problems - commented out to avoid misuse
}

/* Right way: Keep ISR short and set a flag */
volatile bool flag = false;
void rightISR() {
  flag = true; // Just set a flag
}
📊

Quick Reference

Here is a quick summary of interrupt modes:

ModeDescription
LOWTrigger when the pin is low
CHANGETrigger when the pin changes value (rising or falling)
RISINGTrigger when the pin goes from low to high
FALLINGTrigger when the pin goes from high to low

Key Takeaways

Use attachInterrupt with digitalPinToInterrupt(pin), ISR function, and mode to handle pin events.
Keep interrupt functions short and avoid delay or Serial calls inside them.
Declare shared variables as volatile to ensure correct behavior.
Check your Arduino board for which pins support interrupts.
Use interrupt modes LOW, CHANGE, RISING, or FALLING to control when the ISR triggers.