Imagine you're reading a book and the doorbell rings. You don't finish the page first; you get up, answer it, and come back to carry on. That's exactly an interrupt: the microcontroller pauses what it's doing, runs a small function for the event, and returns to where it left off.
Why do we need it?
If you read a button or sensor with digitalRead inside the loop, and the loop has a long delay or slow work, you can miss the event. An interrupt guarantees a response immediately, whatever the program is doing.
Example: a sensor outputs a pulse 2 ms long, and the loop takes 100 ms because it's writing to a display. With digitalRead you'll see the pulse only about 2% of the time. With an interrupt you'll see it every time.
Uses: counting fast pulses (an encoder, a speed sensor, or a water meter), an emergency button, and waking the chip from sleep.
Usage
volatile unsigned long count = 0;
void onPulse() {
count++;
}
void setup() {
pinMode(2, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(2), onPulse, FALLING);
Serial.begin(9600);
}
void loop() {
noInterrupts();
unsigned long c = count;
interrupts();
Serial.println(c);
delay(1000);
}
Notice that the delay(1000) in the loop doesn't affect counting: every pulse is counted even while the program waits. To stop the interrupt, use detachInterrupt(digitalPinToInterrupt(2)).
The pins
- Arduino Uno and Nano: only two pins, 2 and 3.
- Arduino Mega: six pins (2, 3, 18, 19, 20, 21).
- ESP32: almost any GPIO pin.
If you need an interrupt on another pin on the Uno, there's a type called a pin change interrupt that works on any pin, but it only tells you "something changed in this group" and you work out which pin. Libraries such as PinChangeInterrupt make it easier.
When does it fire?
- RISING: the signal went from LOW to HIGH.
- FALLING: it went from HIGH to LOW. With a pull-up, that's the moment a button is pressed.
- CHANGE: any change.
- LOW: for as long as it's LOW. Rarely used.
Rules for the ISR (the interrupt function)
- Very short: increment a counter or set a flag, and leave the heavy work to the loop.
- No
delay(), and be careful withSerial.printinside it. - Variables shared with the loop must be
volatile, so the compiler doesn't assume their value is constant. - Larger variables (more than one byte on the Uno): read them with interrupts disabled (
noInterrupts()), as in the example, so you don't read half old and half new. - On an ESP32, add
IRAM_ATTRbefore the function:void IRAM_ATTR onPulse() {...}.
Why does volatile matter? A real bug
bool pressed = false; // without volatile
void onPress() { pressed = true; }
void loop() {
while (!pressed) { } // waiting for the button
Serial.println("pressed");
}
The compiler sees that nothing inside the while changes pressed, so it may read it once, keep it in a register, and loop forever even after the button is pressed. The volatile keyword tells it: "this variable can change from outside; read it from memory every time".
What happens to time inside the ISR?
While you're inside the ISR, other interrupts are disabled. So millis() doesn't advance, delay() would hang forever, and Serial can freeze if its buffer fills. Hence the rule: get in, record, get out. You can still read micros() inside the ISR to know exactly when the event happened.
Project: a water meter with a flow sensor
Flow sensors such as the YF-S201 contain a small turbine with a magnet and a Hall sensor, outputting a pulse with each turn. For this sensor, roughly: frequency (Hz) = 7.5 × flow (litres/minute).
volatile unsigned long pulses = 0;
void IRAM_ATTR onPulse() { pulses++; } // on the Uno, remove IRAM_ATTR
float liters = 0;
void setup() {
Serial.begin(115200);
pinMode(2, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(2), onPulse, FALLING);
}
void loop() {
noInterrupts();
unsigned long p = pulses; pulses = 0;
interrupts();
float lpm = p / 7.5; // pulses per second ÷ 7.5 = litres per minute
liters += lpm / 60.0;
Serial.print(lpm); Serial.print(" L/min ");
Serial.print(liters); Serial.println(" L");
delay(1000);
}
The 7.5 figure is approximate, so calibrate it: fill a 10-litre bucket, see what the code reports, and adjust the number. The same idea measures the speed of a motor or wheel: a magnet on the wheel and a Hall sensor, and pulses per second × 60 = revolutions per minute.
Another project: the rotary encoder
An encoder (such as the KY-040 module) is the knob that turns endlessly, like a car's volume knob. It outputs two signals, CLK and DT, offset from each other by a quarter step, and the signal that leads the other tells you the direction.
const int CLK = 2, DT = 4;
volatile long pos = 0;
void onClk() {
if (digitalRead(CLK) == digitalRead(DT)) pos--;
else pos++;
}
void setup() {
Serial.begin(115200);
pinMode(CLK, INPUT_PULLUP);
pinMode(DT, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(CLK), onClk, CHANGE);
}
void loop() {
noInterrupts();
long p = pos;
interrupts();
Serial.println(p);
delay(100);
}
If the direction comes out reversed, swap the ++ and the --. A cheap encoder bounces like a button, so if the reading jumps, add a 10 nF capacitor from each pin to ground. The module usually has pull-up resistors on it, so enabling the internal ones as well makes no difference.
Polling or interrupt?
| Polling (reading in the loop) | Interrupt | |
|---|---|---|
| Response | When the loop reaches that line | Immediate |
| Short pulses | Can be missed | Are caught |
| Ease | Easier | Needs rules |
| Suited to | Buttons, slow sensors | Counters, encoders, waking up |
The practical rule: start with polling using millis, and move to an interrupt when you find events slipping past.
Watch out: buttons
A mechanical button bounces as it closes, so the interrupt fires several times per press. The fix: debounce by time in code, or a capacitor and resistor. See buttons and debouncing.
A simple debounce inside the ISR:
volatile unsigned long lastUs = 0;
volatile int presses = 0;
void onPress() {
unsigned long now = micros();
if (now - lastUs > 30000) { // ignore anything within 30 ms
presses++;
lastUs = now;
}
}
And if you don't need an instant response to the button (most cases), ordinary debouncing in the loop is simpler and needs no interrupt at all.
Other interrupts
Besides pin interrupts, there are timer interrupts that fire at exact fixed intervals, and the Arduino timer calculator works out their settings. But for most everyday uses, millis() is enough and simpler. On the ESP32, a pin interrupt can wake the chip from sleep, which is the basis of battery projects. See the ESP32 deep sleep article.
Recurring problems
| Problem | Usual cause |
|---|---|
| The counter never increases | The pin isn't 2 or 3 on the Uno, or you forgot digitalPinToInterrupt |
| The counter increases by itself | A floating pin with no pull-up |
| One press counts several times | Bounce |
| The program hangs | delay or lots of Serial inside the ISR |
| The value in the loop is sometimes wrong | Missing volatile, or reading a large variable without noInterrupts |
| The ESP32 resets | Missing IRAM_ATTR |
FAQ
Can I have more than one interrupt in the same program? Yes, each pin has its own function. If two happen together, one waits for the other to finish, which is why the functions must be short.
Can I print from inside the ISR to test? For a quick test it usually works, but don't leave it in. It's better to set a flag and print from the loop.