How to Use Arduino Interrupt with attachInterrupt()
How to Use Arduino Interrupt with attachInterrupt()
What is an Interrupt
Normally, Arduino runs code inside void loop() continuously from top to bottom, then repeats. But what if something urgent happens that needs immediate attention, like a button press or motion detected by a sensor? This is where interrupt comes in handy.
Think of it like watching TV when someone rings the doorbell. You pause, answer the door, then go back to watching your show. That brief interruption is exactly what Arduino interrupt does.
Interrupt Pins by Board
Different Arduino boards have different numbers of external interrupts:
| Board | int.0 | int.1 | int.2 | int.3 | int.4 | int.5 |
|---|---|---|---|---|---|---|
| UNO, Ethernet | 2 | 3 | - | - | - | - |
| Mega2560 | 2 | 3 | 21 | 20 | 19 | 18 |
| Leonardo | 3 | 2 | 0 | 1 | - | 7 |
This guide focuses on Arduino UNO R3 with its two available interrupt pins.
Arduino Interrupt Code Example
This example monitors pin 3 (interrupt 1) and toggles the LED on pin 13 whenever a rising signal is detected:
const int ledPin = 13;
volatile int ledState = LOW;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
// attachInterrupt(interrupt, function, mode)
// interrupt: 1 = pin 3 on UNO
// function: name of ISR to execute
// mode: RISING, FALLING, or CHANGE
attachInterrupt(1, blink, RISING);
}
void loop() {
digitalWrite(ledPin, ledState);
// other tasks continue here
Serial.println("Running...");
delay(500);
}
void blink() {
Serial.println("Interrupt triggered!");
ledState = !ledState;
}
Important: Variables used inside an Interrupt Service Routine (ISR) must be declared volatile to prevent the compiler from optimizing them away.
Interrupt Trigger Modes
| Mode | Description |
|---|---|
| RISING | Triggers when signal goes from LOW to HIGH |
| FALLING | Triggers when signal goes from HIGH to LOW |
| CHANGE | Triggers on any signal transition |
Best Practices for Arduino Interrupts
- Keep ISR functions short and fast - other code waits while ISR runs
- Avoid using
delay()andSerial.println()inside ISR functions - Use
volatilefor all variables shared between ISR and main code - For complex communication (like I2C) inside ISR, use flags to handle in loop()
Reference Video
อยากทำโปรเจคแบบนี้?
รับทำโปรเจค Arduino / IoT จบงานไว ส่งงานครบ พร้อมสอน
If you need Arduino project service or urgent IoT development, see full service details on the home page
จ้างทำโปรเจคเลย