Arduino External Interrupts Tutorial: React to Inputs Instantly with attachInterrupt()
The loop() function can only react to an input after the current pass has finished, so short signals such as encoder pulses or fast triggers are easy to miss. External interrupts solve this by running a dedicated function the moment a pin changes state. This tutorial explains how interrupts differ from polling, which pins support them on common boards, how attachInterrupt() and its trigger modes work, and how to write a safe interrupt service routine. It ends with a debounced button and LED example for the Arduino UNO.
The post is part of the Arduino Core Tutorials series. Readers who are new to pin handling can start with the digitalWrite() and digitalRead() tutorial and the Arduino UNO pinout guide. The delayMicroseconds() tutorial covers a timing function that still works inside an ISR, and the Arduino FreeRTOS tutorials build on the same ideas for multitasking.
Table of contents
- Arduino External Interrupts Tutorial: React to Inputs Instantly with attachInterrupt()
- How Arduino External Interrupts Work
- Arduino External Interrupt Pins
- Arduino attachInterrupt() Syntax
- Arduino Interrupt Trigger Modes
- Arduino detachInterrupt()
- Arduino Interrupt Button Wiring
- Arduino Interrupt Button Debounce Code
- Arduino ISR Rules
- Arduino Pin Change Interrupts
- Arduino Interrupt Troubleshooting
- Conclusion
How Arduino External Interrupts Work
An interrupt is a hardware signal that pauses the main program, runs a special function called an interrupt service routine (ISR), and then returns to the exact point where the program stopped. On a 16 MHz board such as the Arduino UNO, the whole sequence usually takes only a few microseconds.
Polling and Interrupts Compared
With polling, loop() must read the pin again and again. A short pulse that arrives while loop() is busy is missed, and the processor spends time checking a pin that has not changed. An interrupt avoids both problems because the hardware watches the pin and calls the ISR as soon as the selected condition occurs.
Interrupts are the better choice when the signal is shorter than one pass through loop(), when pulses from an encoder or sensor must be counted, or when the program must respond while the main loop is busy. Polling is enough when the input changes slowly, for example a button that is held for 100 ms or more, and when the extra work of managing an ISR flag is not justified.
Arduino External Interrupt Pins
External interrupts are triggered by voltage changes on pins that are wired to the interrupt logic of the microcontroller. Many boards support them on only a few pins, so the pin must be chosen before the circuit is built.
Interrupt Pinout Table
The table lists the digital pins that can be used with attachInterrupt() on common boards. The values follow the Arduino attachInterrupt() reference, and other boards can differ.
| Board | Interrupt pins | Notes |
|---|---|---|
| UNO R3, classic Nano, Pro Mini (ATmega328P) | 2, 3 | INT0 is pin 2 and INT1 is pin 3 |
| UNO R4 Minima and UNO R4 WiFi | 2, 3 | Same pins as the UNO R3 |
| Mega 2560 | 2, 3, 18, 19, 20, 21 | Pins 20 and 21 are also the I2C pins and carry external pull-ups |
| Leonardo and Micro | 0, 1, 2, 3, 7 | Five external interrupts |
| Zero | All digital pins except 4 | Pin 4 cannot be used |
| Due | All digital pins | Also supports the HIGH trigger mode |
| UNO WiFi Rev2 and Nano Every | All digital pins | Interrupt number equals the pin number |
Check Interrupt Support with digitalPinToInterrupt()
The function digitalPinToInterrupt() returns the interrupt number for a pin, or the value NOT_AN_INTERRUPT (-1) when the pin has no external interrupt. The sketch below prints the result for four pins, and the expected output on an UNO is 0, 1, -1 and -1.
// Prints the interrupt number of a pin. A value of -1 means the pin has no external interrupt.
void checkPin(uint8_t pin) {
Serial.print("Pin ");
Serial.print(pin);
Serial.print(": ");
Serial.println(digitalPinToInterrupt(pin));
}
void setup() {
Serial.begin(9600);
while (!Serial) { } // Waits for the USB serial port on boards such as the Leonardo
delay(2000);
checkPin(2); // 0 on the UNO
checkPin(3); // 1 on the UNO
checkPin(4); // -1 on the UNO (not valid)
checkPin(5); // -1 on the UNO (not valid)
}
void loop() {}The interrupt number is not always the same as the pin number. On the Mega 2560, for example, pin 21 is interrupt 2, while the Due, Zero and MKR boards use the pin number itself. For this reason, attachInterrupt() should always receive digitalPinToInterrupt(pin) and never a fixed interrupt number.
Arduino attachInterrupt() Syntax
The function attachInterrupt() links an interrupt pin to an ISR and selects the signal condition that starts it. The recommended form uses digitalPinToInterrupt() so that the same sketch works on different boards.
attachInterrupt(digitalPinToInterrupt(pin), ISR_function, mode);attachInterrupt() Parameters
- pin is the number of an interrupt-capable pin.
- ISR_function is the function that runs when the interrupt fires. It must take no parameters and return void.
- mode is the signal condition that triggers the interrupt, as listed in the next section.
Configure the Interrupt Pin as INPUT or INPUT_PULLUP
The pin must be configured as an input before the interrupt is attached. The two common choices are listed below.
- INPUT reads an external signal and expects the circuit to provide its own pull-up or pull-down resistor.
- INPUT_PULLUP enables the internal pull-up resistor, which keeps the pin HIGH until something pulls it to GND.
pinMode(2, INPUT_PULLUP); // Pin 2 as an input with the internal pull-up enabledINPUT_PULLUP is convenient for push buttons because no external resistor is needed. The internal resistor of the ATmega328P is roughly 20 kΩ to 50 kΩ, which is weak enough for a button to pull the pin to GND without trouble. The pull-up only sets the default level and does not protect the pin from higher voltages, so any external signal must stay between 0 V and the supply voltage of the board.
Calling pinMode() before attachInterrupt() is good practice, because enabling the pull-up after the interrupt is attached can create a level change that the interrupt then reports.
Arduino Interrupt Trigger Modes
The mode argument decides which signal change calls the ISR. The classic AVR boards such as the UNO, Nano and Mega support the first four modes, and the Due, Zero and MKR1000 also support HIGH.
| Mode | Triggers when | Typical use |
|---|---|---|
| RISING | The pin goes from LOW to HIGH | Start of a pulse, button release |
| FALLING | The pin goes from HIGH to LOW | Button press with INPUT_PULLUP |
| CHANGE | The pin changes in either direction | Rotary encoders, pulse width measurement |
| LOW | The pin is LOW | Level-triggered input, rarely needed |
| HIGH | The pin is HIGH (Due, Zero and MKR1000 only) | Level-triggered input, rarely needed |
FALLING is the usual choice for a button wired between the pin and GND with INPUT_PULLUP, because the pin rests at HIGH and drops to LOW when the button is pressed. CHANGE reports both edges of every pulse, which doubles the number of events from a rotary encoder compared with a single edge.
The LOW mode behaves differently from the edge modes because the interrupt keeps firing for as long as the pin stays LOW, not only at the moment of the transition. An ISR that returns while the pin is still LOW is called again immediately, which can leave very little time for the main program. For this reason, an edge mode is the safer default.
Arduino detachInterrupt()
The function detachInterrupt() stops the pin from calling its ISR. It is useful during a critical section of the program or when a noisy input causes false triggers.
detachInterrupt(digitalPinToInterrupt(2)); // Disable the interrupt on pin 2The pinMode() setting is not changed by this call, so a pin that was set to INPUT_PULLUP keeps its pull-up resistor. The interrupt can be enabled again at any time by calling attachInterrupt() with the same arguments.
The functions noInterrupts() and interrupts() work differently, because they pause and resume every interrupt on the board and not only the one on a single pin. They should be used only around short sections of code, since millis() depends on a timer interrupt and falls behind when interrupts stay disabled for too long.
Arduino Interrupt Button Wiring
The example in this tutorial uses a push button on pin 2 to toggle an LED on pin 13. Pin 2 is the INT0 interrupt pin of the UNO and Nano, and the button pulls it to GND when pressed.
Button and LED Connections
| Part | Connection |
|---|---|
| Push button | One leg to pin 2 and the other leg to GND |
| LED anode | Pin 13 through a 220 Ω resistor |
| LED cathode | GND |
The internal pull-up (INPUT_PULLUP) keeps pin 2 HIGH until the button is pressed, so no external resistor is needed for the button. With a typical red LED that has a forward voltage of about 2 V, the 220 Ω resistor limits the current to roughly 14 mA, which is below the 20 mA that is usually recommended for a single ATmega328P pin. The UNO and Nano already have an LED on pin 13, so the external LED is optional.
Arduino Interrupt Button Debounce Code
A mechanical button does not produce one clean transition. When the contacts close, they usually bounce for a few milliseconds, and in some worn switches for longer. Every bounce that crosses the trigger level fires another interrupt, so a single press can call the ISR many times.
Interrupt Debounce Sketch
The ISR only records the time of the latest edge and sets a flag. The loop() function waits until no new edge has arrived for DEBOUNCE_MS, checks that the button is still pressed, and then toggles the LED one time. Measuring the quiet period from the latest edge also ignores the bounce that happens when the button is released.
// A push button on pin 2 toggles the LED on pin 13 using an external interrupt
const uint8_t BUTTON_PIN = 2; // INT0 on the UNO and Nano
const uint8_t LED_PIN = 13; // Built-in LED on the UNO and Nano
const unsigned long DEBOUNCE_MS = 50; // Quiet time required after the latest edge
volatile bool edgeSeen = false; // Set in the ISR, cleared in loop()
volatile unsigned long lastEdgeMs = 0; // Time of the latest edge, written in the ISR
bool ledState = false;
void handleButtonISR() {
lastEdgeMs = millis(); // millis() can be read in an ISR, but it does not advance there
edgeSeen = true;
}
void setup() {
Serial.begin(9600);
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP); // Button between pin 2 and GND
// Stop here if the chosen pin has no external interrupt on this board
if (digitalPinToInterrupt(BUTTON_PIN) == NOT_AN_INTERRUPT) {
Serial.println("Error: this pin does not support external interrupts.");
while (true) { }
}
attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), handleButtonISR, FALLING);
Serial.println("Ready. Press the button.");
}
void loop() {
bool pressReady = false;
// Check and clear the flag in one step so that no edge is lost in between
noInterrupts();
if (edgeSeen && (millis() - lastEdgeMs >= DEBOUNCE_MS)) {
edgeSeen = false;
pressReady = true;
}
interrupts();
// Toggle only if the button is still pressed after the quiet period
if (pressReady && digitalRead(BUTTON_PIN) == LOW) {
ledState = !ledState;
digitalWrite(LED_PIN, ledState);
}
}The variables shared with the ISR are declared volatile so that the compiler reads them from memory on every access. The unsigned long variable is four bytes wide, and the 8-bit AVR core needs several instructions to read it, so the read in loop() happens with interrupts disabled. The check at the start of setup() uses digitalPinToInterrupt() to stop the sketch with a clear message when a pin without interrupt support is selected on another board.
Hardware Debounce with a Capacitor
A small capacitor across the button contacts removes most of the bounce before it reaches the pin. A 100 nF capacitor connected between pin 2 and GND works with the internal pull-up, and together they form an RC filter with a time constant of roughly 2 ms to 5 ms. The software debounce above can stay in place, because the two methods work well together.
Interrupt Button Result
The animation below shows the sketch running in the TinkerCAD simulator. Each press toggles the LED once.

Arduino ISR Rules
An ISR runs while other interrupts wait, so it follows stricter rules than a normal function. The rules below prevent most of the problems that appear in interrupt-driven sketches.
Keep the ISR Short
A long ISR delays the main program and every other pending interrupt. The best pattern is to set a flag or update a counter inside the ISR and to do the real work in loop(), as the debounce sketch above does.
Avoid delay() and Serial in an ISR
The timer interrupt that drives millis() cannot run while an ISR is executing. As a result, millis() does not advance inside an ISR, delay() never finishes, and micros() starts to give wrong values after one or two milliseconds. The function delayMicroseconds() uses no timer interrupt and still works.
The Serial library should also stay out of ISRs. Its transmit buffer is emptied by an interrupt, so Serial.print() can wait forever for free space once the 64-byte buffer on an AVR board is full. The Arduino reference also warns that serial data received while an ISR is running may be lost.
Declare Shared Variables as volatile
Without the volatile keyword, the compiler may keep a variable in a register and never read the value that the ISR wrote to memory. Every variable that is written in an ISR and read in loop(), or the other way round, needs the keyword.
volatile bool edgeSeen = false; // One byte, read and written in a single step on AVR
volatile unsigned long pulseCount = 0; // Four bytes, needs protection when read in loop()Read Multi-Byte Variables with Interrupts Disabled
An 8-bit AVR core reads a 16-bit or 32-bit variable in several steps. If the ISR changes the value between those steps, loop() receives a mix of old and new bytes. Disabling interrupts for the short time of the copy avoids this problem.
noInterrupts();
unsigned long count = pulseCount; // Consistent copy of all four bytes
interrupts();Pending Interrupts and Priority
On AVR boards only one ISR runs at a time. Other interrupts that occur in the meantime are not discarded, because the hardware keeps one pending request for each interrupt source and runs it after the current ISR returns. When several requests are pending, the one with the highest priority (the lowest vector number) runs first. Two events from the same source that arrive during a long ISR are therefore counted as one, which is another reason to keep the ISR short.
Arduino Pin Change Interrupts
The ATmega328P has only two external interrupt pins, but it can also raise a pin change interrupt on every I/O pin, including the analog pins A0 to A5. A pin change interrupt has no trigger modes and fires on any change of the pin, in either direction. The pins are split into three groups that share one ISR each.
| Group | UNO pins | Mask register | ISR vector |
|---|---|---|---|
| PORTB | D8 to D13 (PCINT0 to PCINT5) | PCMSK0 | PCINT0_vect |
| PORTC | A0 to A5 (PCINT8 to PCINT13) | PCMSK1 | PCINT1_vect |
| PORTD | D0 to D7 (PCINT16 to PCINT23) | PCMSK2 | PCINT2_vect |
The sketch below enables a pin change interrupt on A0. Because every pin of the group calls the same ISR, a sketch that uses more than one pin of a group must read the port inside the ISR to find out which pin changed.
// Pin change interrupt on A0 (PCINT8) for the ATmega328P (UNO, classic Nano, Pro Mini)
const uint8_t INPUT_PIN = A0;
volatile bool pinChanged = false;
ISR(PCINT1_vect) { // Shared by A0 to A5
pinChanged = true;
}
void setup() {
Serial.begin(9600);
pinMode(INPUT_PIN, INPUT_PULLUP);
PCICR |= (1 << PCIE1); // Enable pin change interrupts for the A0 to A5 group
PCMSK1 |= (1 << PCINT8); // Unmask A0 only
}
void loop() {
if (pinChanged) {
pinChanged = false;
Serial.println(digitalRead(INPUT_PIN) ? "A0 is HIGH" : "A0 is LOW");
}
}The registers in this example belong to the ATmega328P, so the code does not apply to the Mega, the Leonardo or ARM boards. Those boards use different pin groups and register names.
Arduino Interrupt Troubleshooting
The table lists the most common problems with external interrupts and the usual fix for each one.
| Problem | Likely cause | Fix |
|---|---|---|
| The interrupt never fires | The pin has no external interrupt, the pin is not set to an input with a pull-up, or the trigger mode does not match the signal | Confirm that digitalPinToInterrupt() does not return -1, call pinMode(pin, INPUT_PULLUP), and use FALLING for a button wired to GND |
| The LED toggles more than once per press | The debounce time is too short, or the button is noisy | Raise DEBOUNCE_MS from 50 to 100, and add a 100 nF capacitor across the button if needed |
| millis() freezes or drifts | The ISR is too long, or interrupts stay disabled for too long | Remove delay() and long loops from the ISR, because millis() depends on the Timer0 overflow interrupt |
| The program hangs or the serial text is corrupted | Serial.print() is called inside the ISR | Set a flag in the ISR and print from loop() |
| loop() never sees a value that the ISR changed | The shared variable is not declared volatile | Add the volatile keyword to every variable shared with the ISR |
| A counter shows a wrong value now and then | A multi-byte variable is read while the ISR updates it | Copy the variable between noInterrupts() and interrupts() |
| The ISR runs again and again | The LOW trigger mode is used and the pin stays LOW | Switch to FALLING or RISING |
Conclusion
External interrupts let the hardware watch a pin while the main program keeps running. The ISR only records the event, and loop() handles it afterward, which keeps the response fast and the program predictable. This tutorial covered the interrupt pins of common boards, the syntax and modes of attachInterrupt(), the rules for writing an ISR, and a debounced button example that can be reused for other inputs.
The IR sensor tutorial and the PIR motion sensor tutorial both connect the sensor output to pin 2, so their sketches can be changed to use attachInterrupt() when polling is too slow. The DS3231 RTC tutorial covers the alarm feature of that module. For signaling RTOS tasks from an ISR, continue with the FreeRTOS interrupts tutorial, which uses the same flag idea together with a semaphore.
Download Project Here
Download the CubeMX project files and HAL source code — all tested on real hardware.
If you find this useful, you can support us with a Donation as well.
Browse More Arduino Core Tutorials

Arun is an embedded systems engineer with 10+ years of experience in STM32, ESP32, and AVR microcontrollers. He created ControllersTech to share practical tutorials on embedded software, HAL drivers, RTOS, and hardware design — grounded in real industrial automation experience.
Recommended Tools
Essential dev tools
Categories
Browse by platform





