Normally your sketch checks things in turn: read a button, update a display, read a sensor, round and round in loop(). If something happens very briefly, such as a pulse from a flow meter or a rotary encoder, the sketch can miss it while it's busy elsewhere. An interrupt fixes that. The hardware watches the pin for you and, the instant it changes, pauses whatever the sketch is doing, runs a short function you've chosen, then carries on exactly where it left off.
Which pins can do it?
Only certain pins have external interrupt hardware. On an Arduino Uno R3, Nano and other ATmega328P boards it's pins 2 and 3. Other boards have more: the Mega 2560 adds 18, 19, 20 and 21, and on the ESP32, Raspberry Pi Pico and many other 32-bit boards almost every pin can be used. The Uno R4 is an exception: still only pins 2 and 3. The Arduino attachInterrupt reference has the table for each board. Always write digitalPinToInterrupt(pin) rather than an interrupt number, so the same code works across boards.
attachInterrupt
attachInterrupt(digitalPinToInterrupt(pin), myFunction, mode) takes three things:
- the pin,
- the function to run, called an interrupt service routine or ISR, which must take no arguments and return nothing,
- the mode: when to trigger.
| Mode | Triggers when the pin… | Typical use |
|---|---|---|
FALLING | goes from HIGH to LOW | A button or sensor pulling an INPUT_PULLUP pin to ground |
RISING | goes from LOW to HIGH | A sensor that outputs a positive pulse |
CHANGE | changes either way | Rotary encoders, measuring pulse widths |
LOW | is LOW (repeats for as long as it stays LOW) | Waking from sleep; rarely needed otherwise |
Some Arm boards, such as the Due and Zero, also accept HIGH.
Example: counting pulses
Flow meters, anemometers and many speed sensors give one pulse per turn or per unit of flow. This sketch counts them on pin 2 and reports the total every second:
const byte SENSOR_PIN = 2; // Uno R3 / Nano: interrupts on pins 2 and 3
volatile unsigned long pulseCount = 0; // shared with the ISR, so volatile
void countPulse() { // the ISR: short and fast
pulseCount++;
}
void setup() {
Serial.begin(9600);
pinMode(SENSOR_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(SENSOR_PIN), countPulse, FALLING);
}
void loop() {
static unsigned long lastReport = 0;
if (millis() - lastReport >= 1000) {
lastReport += 1000;
noInterrupts(); // take a clean copy of the 4-byte count
unsigned long count = pulseCount;
pulseCount = 0;
interrupts();
Serial.print("Pulses in the last second: ");
Serial.println(count);
}
}
Three things in it matter, and they are the rules of interrupts.
Rule 1: keep the ISR tiny
While an ISR runs, other interrupts wait. The Arduino reference warns that inside an ISR delay() won't work and millis() won't count up. Serial printing relies on interrupts too, so it can stall or lose characters. So an ISR should do the bare minimum, usually setting a flag or bumping a counter, and leave the real work to loop(). No Serial.print(), no delay(), no long calculations.
Rule 2: shared variables must be volatile
The compiler normally keeps a copy of a variable in a fast register and assumes it only changes when your code changes it. It has no idea an ISR might change it in the background, so loop() can keep using a stale copy for ever. Declaring the variable volatile tells the compiler to read it fresh from memory every time.
Rule 3: read multi-byte variables with interrupts paused
An Uno's processor handles 8 bits at a time, so reading a 4-byte unsigned long takes several steps. If the interrupt fires halfway through, you get half of the old value and half of the new one: a rare, baffling glitch. noInterrupts() pauses interrupts for the few microseconds it takes to copy the value; interrupts() turns them back on. A pulse that arrives during that gap isn't lost: the hardware sets a flag and the ISR runs as soon as interrupts are back on. (It can only remember one, so keep the pause short.) A single byte or bool is read in one step, so it doesn't need this.
Example: a button that's never missed
Mechanical buttons bounce: the contacts chatter for a few milliseconds and can fire the interrupt several times per press. This ISR ignores any edge within 50 ms of the last accepted one, then loop() does the work:
const byte BUTTON_PIN = 3;
const byte LED_PIN = 13;
volatile bool pressed = false;
volatile unsigned long lastPressTime = 0;
void onButton() {
unsigned long now = millis(); // reading millis() in an ISR is fine
if (now - lastPressTime > 50) { // ignore bounces within 50 ms
pressed = true;
lastPressTime = now;
}
}
void setup() {
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP); // button wired from pin 3 to GND
attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), onButton, FALLING);
}
void loop() {
if (pressed) {
pressed = false;
digitalWrite(LED_PIN, !digitalRead(LED_PIN)); // toggle the LED
}
// ...the rest of your program carries on here
}
For a plain button on a project that loops quickly, polling with millis() is usually simpler and works just as well; see millis() vs delay(). Interrupts earn their keep for fast or very short signals, and for waking a sleeping board. The INPUT_PULLUP wiring is explained in pull-up and pull-down resistors.
Common mistakes
- Forgetting
volatile. The sketch seems to ignore the interrupt, often only once optimisation kicks in. - Using a pin without interrupt support, for example pin 4 on an Uno. It compiles, but nothing happens.
- A floating input. Without a pull-up or pull-down, electrical noise fires the interrupt at random.
- Printing from the ISR. It may hang or lose characters. Set a flag and print from
loop().
Going deeper
Interrupt latency
On a 16 MHz ATmega328P the processor finishes its current instruction, saves its place and jumps to the ISR in a few microseconds, and attachInterrupt()'s wrapper adds a little more. That's fast enough for pulses tens of kilohertz apart, but very fast signals will swamp it. For higher rates, use a hardware timer or counter input, which counts without running any code per pulse.
Pin change interrupts
The ATmega328P can also interrupt on a change of any pin through its three pin change interrupt groups. They fire on any change in a group of pins, so the ISR has to work out which pin changed and in which direction. Libraries such as EnableInterrupt or PinChangeInterrupt wrap this for you.
ESP32: IRAM_ATTR
On the ESP32, ISRs should be marked void IRAM_ATTR countPulse() so the code sits in internal RAM. Without it, an interrupt that arrives while flash is busy (for example during a Wi-Fi or file write) can crash the board. For variables shared with an ISR on dual-core chips, use a critical section (portENTER_CRITICAL) rather than noInterrupts().
Hardware debouncing
An RC filter (for example 10 kΩ and 100 nF, a 1 ms time constant) across a button smooths the bounce before it reaches the pin. A Schmitt-trigger buffer such as a 74HC14 after the filter gives clean edges. This removes the need for timing code in the ISR at all.
detachInterrupt and sleep
detachInterrupt(digitalPinToInterrupt(pin)) turns an interrupt off. On AVR boards in power-down sleep, only the LOW level (and pin change) interrupts can wake the chip on pins 2 and 3; the datasheet's sleep mode table lists which wake sources work in each mode.
Sources
The main references behind this guide. Numbers we worked out ourselves, such as the code outputs, come from running the code.
- Arduino language reference: attachInterrupt() (pins per board, modes, ISR rules)
- Arduino language reference: volatile
- Arduino language reference: noInterrupts()
- Microchip ATmega328P datasheet (external and pin change interrupts, sleep modes)
- Espressif: ESP-IDF interrupt allocation (IRAM-safe interrupt handlers)