Interrupts
How an Arduino reacts at once without checking: attachInterrupt() on pins 2 and 3, the rules for an interrupt function, volatile, counting presses and timing.

When you are waiting for a friend, you can look out of the window every minute to see whether they’ve arrived, or get on with your own things until the doorbell rings. An Arduino can work either way. The first is called polling: on every pass of the loop, the program reads the pin. The second is an interrupt: when something changes on the pin, the chip itself stops what it is doing, runs a short function, and goes back to where it left off.
Most programs at the workshop poll, and that is fine. This page explains when polling isn’t enough, how to write an interrupt, and the mistakes interrupts lead to.
Polling or an interrupt

In both programs one pass of the loop takes 4 ms, for example because it refreshes a display.
- At the top the program polls: it reads pin D2 with
digitalRead(2)once on every pass. The short pulse happens between two readings, and the program doesn’t see it. It sees the long one, but 3 ms late. - At the bottom the pin starts an interrupt. As soon as a pulse appears, the chip stops the loop, runs the interrupt function (ISR, interrupt service routine) and goes back to the loop. The drawing shows the ISR wider than it really is: it takes only a few microseconds.
Polling is enough as long as each pass of the loop is short compared with what you are measuring. You need an interrupt when an event is shorter than a pass of the loop, or when the exact time it happened matters.
An interrupt on the Arduino Uno
On an Arduino Uno only pins 2 and 3 have an interrupt on a pin change (see Pinouts). You switch the interrupt on in setup():
attachInterrupt(digitalPinToInterrupt(2), changed, CHANGE);
digitalPinToInterrupt(2)turns the pin number into the interrupt number.changedis the name of the function the chip calls when the interrupt happens.- The last part says which change starts the interrupt:
RISING(from LOW to HIGH),FALLING(from HIGH to LOW),CHANGE(any change) orLOW(all the time while the pin is LOW).
The Uno’s other pins can start an interrupt only through a library for pin change interrupts, which is more complicated. On other microcontrollers, such as the ESP32, almost every pin has an interrupt.
The rules for an interrupt function
An interrupt function runs in the middle of any other part of the program, and everything else stands still meanwhile. So it has to follow a few rules:
- It must be short. Let it only remember what happened (increase a counter, note a time), and let
loop()do everything else. - No
delay()and noSerial. While an interrupt runs, the other interrupts wait.delay()then doesn’t work properly, andSerial.print()can lock up the whole program. millis()doesn’t count on while the interrupt function runs. It may read it, and for short timesmicros()is better (see millis() instead of delay()).- Shared variables are
volatile. Mark a variable that the interrupt function changes andloop()reads withvolatile. Then the compiler reads it from memory every time, instead of keeping an old value. - Copy a variable larger than a byte with interrupts switched off.
The last rule needs explaining. The chip on an Arduino Uno is 8-bit: it can’t read a two-byte number, such as an unsigned int, in one go, but byte by byte.

The counter is 255: high byte 0, low byte 255. loop() reads the low byte, 255. Right then an interrupt comes and increases the counter to 256: high byte 1, low byte 0. loop() then reads the high byte, 1, and puts the two parts together as 1 · 256 + 255 = 511. That number was never in the counter. This happens rarely, but not never, and a mistake like this is hard to find, because the program shows a strange number now and then and corrects it straight away. That is why a larger variable is copied while no interrupt can get in:
noInterrupts(); // interrupts wait
unsigned int copy = count;
interrupts(); // interrupts work again
While interrupts are switched off, a change on the pin isn’t lost: it waits and runs straight after interrupts(). So switch interrupts off only briefly, just for the copy. There is more about bytes on the Variables and data types page.
Example: counting presses
The button is between pin 2 and GND, as in the lesson Buttons done right. loop() deliberately sleeps for 2 seconds at a time, and the presses are counted anyway, because the interrupt counts them.
// Counting button presses with an interrupt. The button is between pin 2 and GND.
// loop() deliberately sleeps for 2 seconds at a time, and the presses are counted anyway.
// Open the Serial Monitor (9600 baud).
const int BUTTON = 2; // on the Uno only pins 2 and 3 have an interrupt
volatile unsigned int count = 0; // changed by the interrupt function, so volatile
volatile unsigned long lastChange = 0;
// The interrupt function: short, no delay() and no Serial.
void changed() {
unsigned long now = micros();
// A press is a change to LOW after the pin has been still for at least 20 ms.
// Contact bounce gives changes closer than 20 ms, and those aren't counted.
if (digitalRead(BUTTON) == LOW && now - lastChange >= 20000) {
count++;
}
lastChange = now;
}
void setup() {
Serial.begin(9600);
pinMode(BUTTON, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(BUTTON), changed, CHANGE);
}
void loop() {
noInterrupts(); // count has two bytes: copy it while no interrupt can get in
unsigned int copy = count;
interrupts();
Serial.print("presses: ");
Serial.println(copy);
delay(2000); // deliberately slow: the interrupt counts while loop() waits
}
A button bounces when it is pressed and released: its contacts touch and part a few times (see Buttons and switches). The interrupt sees every bounce, so without a time check one press would count as three or four. That is why the function counts only a change to LOW that comes after the pin has been still for at least 20 ms.
Example: how long was the beam broken
The ball in a pinball machine passes through an infrared beam in a few milliseconds. If the sensor is wired to give a digital output, LOW while the beam is broken (in the pinball machine a comparator does this), the interrupt notes the exact time of both edges, and loop() prints the difference when it gets round to it:
// How long was the beam broken? A sensor with a digital output on pin 2,
// LOW while the beam is broken (for example a comparator's output, as in the pinball machine).
// Open the Serial Monitor (115200 baud).
const int SENSOR = 2;
volatile unsigned long start = 0; // when the beam was broken, in microseconds
volatile unsigned long duration = 0; // how long it was broken
volatile bool fresh = false; // whether there is a new measurement to print
void changed() {
unsigned long now = micros();
if (digitalRead(SENSOR) == LOW) {
start = now; // the beam has just been broken
} else {
duration = now - start; // the beam is free again
fresh = true;
}
}
void setup() {
Serial.begin(115200);
pinMode(SENSOR, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(SENSOR), changed, CHANGE);
}
void loop() {
if (fresh) {
noInterrupts(); // duration has four bytes
unsigned long t = duration;
fresh = false;
interrupts();
Serial.print("beam broken for ");
Serial.print(t);
Serial.println(" us");
}
}
From the duration and the ball’s diameter you can work out its speed. In the lesson Detecting the ball the receiver gives a voltage, so the program measures it with analogRead() and polling. That works while the loop is short. If the loop has more to do and the ball is fast, an interrupt is safer.
How fast is an interrupt?
On an Arduino Uno a few microseconds pass between the change on the pin and the start of the interrupt function. Polling is late by as long as one pass of the loop takes, and a pass that refreshes a display or sends messages can take several milliseconds, a thousand times longer. On the other hand, every interrupt stops the loop for a moment. If there are too many interrupts, for example from a pin that picks up noise or bounces, the loop hardly gets anything done.
Interrupts you already use
Even when you don’t write a single interrupt yourself, the Arduino uses them:
millis()anddelay()count with an interrupt from the Timer0 counter, about every millisecond.Serialreceives characters with an interrupt and stores them until the program reads them.- The Servo library uses Timer1, so on an Uno it switches off PWM on pins 9 and 10 (see Servo motor).
tone()uses Timer2, so it gets in the way of PWM on pins 3 and 11 (see Buzzer and speaker).
That is why an interrupt function must be short: while it runs, these interrupts wait too, so millis() falls behind and Serial can lose characters.
Interrupts on the ESP32
On the ESP32 almost every pin has an interrupt, and the interrupt function gets IRAM_ATTR in front of its name. That puts it in the fast internal memory, so it can run even while the flash memory is busy. The other rules are the same: a short function, volatile variables and copying with interrupts switched off. The program of the lab power supply reads its rotary encoder this way: every change on its two pins starts an interrupt, and loop() takes over the number of steps between noInterrupts() and interrupts(). There is more about the ESP32 on the ESP32 and ESP8266 page.
Debugging interrupts
Mistakes with interrupts are hard because you can’t see them: the interrupt function runs invisibly, at any moment, and you mustn’t use Serial in it. So first look for the symptom that matches what you see:
| What happens | The most common cause |
|---|---|
| The interrupt function never runs | The pin isn’t 2 or 3. The code says attachInterrupt(2, ...) instead of attachInterrupt(digitalPinToInterrupt(2), ...): the interrupt number for pin 2 is 0, and interrupt number 2 doesn’t exist on the Uno. The pin is connected to nothing and has no INPUT_PULLUP. |
| It counts too many | Contact bounce, interference on long wires, or a pin without a resistor to 5V or GND, which picks up noise. |
| Now and then it shows a strange value | The variable isn’t volatile, or loop() reads a variable larger than a byte without noInterrupts(). |
| The program gets stuck | Serial or delay() in the interrupt function, or an interrupts() forgotten after noInterrupts(). |
millis() falls behind, Serial loses characters | The interrupt function is too long or runs too often. |
When the cause isn’t obvious, these help you see what the interrupt function really does:
- First check the input without the interrupt. Read the pin with
digitalRead()inloop()and print it. If you still don’t see it change, the mistake is in the wiring, not in the interrupt (see Troubleshooting a circuit). - Count the runs. Let the interrupt function increase a counter, and let
loop()print it every second. That shows whether it runs at all, and how often. If the number grows even when nobody touches the button, the pin is picking up noise. - Switch a pin for the oscilloscope. At the start of the interrupt function set a spare pin HIGH, and at the end LOW. On an oscilloscope you then see each interrupt as a pulse: when it happened and how long it took.
digitalWrite()itself takes a few microseconds, so allow for that.
// Add to a program with an interrupt: a counter of runs and pin 13 for the oscilloscope.
// In setup() add pinMode(13, OUTPUT); and Serial.begin(9600);
volatile unsigned long interruptCount = 0;
void changed() {
digitalWrite(13, HIGH); // the start of the interrupt function
interruptCount++;
// ... whatever the interrupt function normally does
digitalWrite(13, LOW); // the end of the interrupt function
}
void loop() {
static unsigned long lastPrint = 0;
if (millis() - lastPrint >= 1000) {
lastPrint += 1000;
noInterrupts();
unsigned long n = interruptCount; // four bytes: copy it with interrupts off
interrupts();
Serial.print("interrupts: ");
Serial.println(n);
}
}
When something doesn’t work, don’t change several things at once. Change one, check it, and only then the next.
When not to use an interrupt
- Buttons that people press. A person holds a button for at least ten milliseconds or so, and the loop reads it many times in that time. Polling is simpler, and bounce is easier to deal with.
- Slow sensors, such as temperature or light.
- When you aren’t sure. Mistakes are harder to find in a program with interrupts: a part of the program can run at any moment, and the mistakes show up only now and then. Start with polling, and change to an interrupt only when you see that polling misses events.
Note
The diagrams, graphs and values on this page are calculated from simplified models or are typical examples. They are here to explain, and may differ from the actual specifications of the parts. Before you build anything, always check the datasheets of the parts you use.
What did we learn?
- Polling reads the pin on every pass of the loop, while an interrupt starts a function as soon as something changes on the pin.
- On an Arduino Uno pins 2 and 3 have an interrupt, which you switch on with
attachInterrupt(). - An interrupt function is short, without
delay()andSerial, and the variables it shares withloop()arevolatile. loop()copies a variable larger than a byte betweennoInterrupts()andinterrupts(), so that it doesn’t read it half changed.- You need an interrupt for short events and exact times. For buttons and slow sensors polling is simpler.
- To debug an interrupt, first check the input without it, then count the runs of the interrupt function or watch them on an oscilloscope.
Quick quiz
1. Why can a program that reads a pin every 4 ms miss a 1 ms pulse?
2. Which pins of an Arduino Uno have an interrupt you switch on with attachInterrupt()?
3. Why mustn't Serial.print() be in an interrupt function?
Serial sends characters with the help of an interrupt. When its buffer is full, Serial.print() waits for an interrupt that can’t come, and the program can get stuck.4. The counter is an unsigned int. Why does loop() copy it between noInterrupts() and interrupts()?
unsigned int on an Arduino Uno has two bytes, and the chip reads them one at a time. If an interrupt changes the counter between the readings of the two bytes, loop() puts together a number that never existed, for example 511 instead of 255 or 256.5. Does the button a player uses to start the game need an interrupt?