How to Use Interrupts in Arduino: Simple Guide with Examples
Use
attachInterrupt() in Arduino to run a function automatically when a specific pin changes state. Define an interrupt service routine (ISR) function and link it to a pin and trigger mode like RISING or FALLING. This lets your Arduino react immediately to events without waiting in the main loop.Syntax
The basic syntax to use an interrupt in Arduino is:
attachInterrupt(digitalPinToInterrupt(pin), ISR, mode);
Where:
pinis the Arduino pin number that supports interrupts.ISRis the name of the function to run when the interrupt triggers.modedefines when the interrupt triggers:LOW,CHANGE,RISING, orFALLING.
arduino
attachInterrupt(digitalPinToInterrupt(pin), ISR, mode);
Example
This example turns on an LED when a button connected to pin 2 is pressed using an interrupt. The LED is connected to pin 13.
arduino
const int buttonPin = 2; const int ledPin = 13; volatile bool ledState = false; void setup() { pinMode(ledPin, OUTPUT); pinMode(buttonPin, INPUT_PULLUP); 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 LED on pin 13 toggles ON or OFF immediately.
Common Pitfalls
Common mistakes when using interrupts in Arduino include:
- Using
delay()orSerial.print()inside the ISR, which can cause problems because ISRs should be very fast. - Not declaring variables shared between ISR and main code as
volatile, which can cause wrong values. - Forgetting to use
digitalPinToInterrupt()to get the correct interrupt number for the pin. - Using pins that do not support interrupts.
arduino
/* Wrong way: Using delay inside ISR */ void interruptFunc() { delay(100); // Avoid this } /* Right way: Keep ISR short and fast */ volatile bool flag = false; void interruptFunc() { flag = true; // Just set a flag }
Quick Reference
| Parameter | Description | Example Values |
|---|---|---|
| pin | Pin number that supports interrupts | 2, 3 (depends on board) |
| ISR | Function called when interrupt triggers | void myISR() |
| mode | When to trigger interrupt | LOW, CHANGE, RISING, FALLING |
Key Takeaways
Use attachInterrupt() with digitalPinToInterrupt(pin) to set up interrupts.
Keep interrupt service routines (ISR) short and avoid delay or Serial calls inside them.
Declare variables shared with ISR as volatile to ensure correct behavior.
Only use pins that support interrupts on your Arduino board.
Choose the correct trigger mode (RISING, FALLING, CHANGE, LOW) for your event.