Suppose your Arduino project reads a sensor, updates a display, and responds to a push button. Most of the time, the button works as expected. Every so often, though, a quick press seems to do nothing, most likely because the program was busy elsewhere when the button changed state.
One solution is to check the input more frequently. However, when an event is brief or unpredictable, interrupts offer another approach. Instead of waiting for the next input check, the microcontroller can run a short routine as soon as the event occurs.
In this Arduino interrupt tutorial, we will use attachInterrupt() to detect a button press and then cover the rules for writing an interrupt service routine (ISR). From there, we will build a pulse counter, where interrupts show a clearer advantage over polling, and finish by configuring pin change interrupts on the ATmega328P.
What Is an Arduino Interrupt?
An interrupt is an event that asks the CPU to temporarily suspend its usual execution flow. When that event occurs, the microcontroller runs a special function called an interrupt service routine (ISR). Once the ISR finishes, the program normally resumes where it left off.
To see where interrupts fit, start with the structure of a typical Arduino sketch, which uses setup() for initialization and loop() for repeated work:
void setup() {
// Run once
}
void loop() {
// Repeated program tasks
}
Interrupts do not replace loop(). Instead, they give the sketch a second way to react to events while the main program continues its work. For example, an ISR might set a flag, leaving loop() to perform the slower work afterward.
A phone call during the workday offers a useful analogy: you briefly stop, answer the call, and then return to your original task. Unlike most phone calls, however, an ISR should be very short, because a long ISR delays normal execution and may block other events.
Which Arduino Pins Support External Interrupts?
The board determines which pins can serve as external interrupts. For common Uno-class and classic Arduino boards, the standard attachInterrupt() interface supports these pins:
| Board | Interrupt pins for attachInterrupt() |
|---|---|
| Arduino Uno R3 (ATmega328P) | D2, D3 |
| Classic Arduino Nano (ATmega328P) | D2, D3 |
| Arduino Uno R4 Minima / WiFi | D2, D3 |
| Arduino Mega 2560 | D2, D3, D18, D19, D20, D21 |
| Arduino Leonardo / Micro | D0, D1, D2, D3, D7 |
Other boards, including the Due and SAMD-based models, use different pins. A shared pin assignment does not mean shared hardware, either: the Uno R4 lists the same D2 and D3 as the Uno R3 but runs on a different microcontroller. For that reason, check the official documentation for your exact board and core rather than assuming every Uno-branded board shares the same interrupt hardware.
On the classic Uno R3, D2 maps to the external interrupt input INT0, while D3 maps to INT1. The first example uses D2 as the input and the built-in LED on D13 as the output.

How to Use attachInterrupt()
To link an interrupt input to a function in your sketch, Arduino provides attachInterrupt(). Its recommended syntax looks like this:
attachInterrupt(digitalPinToInterrupt(pin), isrFunction, mode);
The first argument identifies the interrupt tied to an Arduino digital pin. Next comes the name of the ISR callback, written without parentheses. Finally, the third argument selects the trigger condition. Putting these together for a button on D2 gives the following call:
attachInterrupt(digitalPinToInterrupt(2), buttonISR, FALLING);
With this line in place, the Arduino runs buttonISR() whenever D2 changes from HIGH to LOW. Note the use of digitalPinToInterrupt(2) rather than a hard-coded interrupt number; because the pin-to-interrupt mapping can differ between boards, the helper keeps the sketch portable.
Arduino Interrupt Trigger Modes
The mode argument accepts four standard values:
- LOW — Trigger while the input remains LOW.
- CHANGE — Trigger when the input changes state in either direction.
- RISING — Trigger when the input changes from LOW to HIGH.
- FALLING — Trigger when the input changes from HIGH to LOW.
Some Arduino boards also support a HIGH mode. In practice, the wiring determines which mode fits best. For instance, if a push button connects D2 to GND with INPUT_PULLUP enabled, pressing the button produces a FALLING edge. CHANGE, by contrast, reacts to both the press and the release, and possibly to extra transitions caused by contact bounce.
Example 1: Button Interrupt to Toggle an LED
This example builds up in two stages. First, a minimal sketch shows what the ISR does by reporting each falling edge on D2. We'll then expand it into a debounced application in which each accepted press toggles the built-in LED. In both versions, the ISR only sets a flag and leaves the rest of the work to loop().
Hardware and Wiring
For this build, you'll need an Arduino Uno R3 or classic Nano, a push button, two jumper wires, and a USB cable. Connect one side of the button to D2 and the other side to GND. When the button is open, the internal pull-up resistor holds D2 HIGH; pressing the button then connects the pin to ground and pulls it LOW.

Stage 1: Detect the Falling Edge
The first sketch does nothing more than report each falling edge on D2 to the Serial Monitor:
const byte buttonPin = 2;
volatile bool edgeDetected = false;
void buttonISR() {
edgeDetected = true;
}
void setup() {
Serial.begin(115200);
pinMode(buttonPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(buttonPin),
buttonISR, FALLING);
}
void loop() {
bool pending;
noInterrupts();
pending = edgeDetected;
edgeDetected = false;
interrupts();
if (pending) {
Serial.println("Falling edge detected on D2");
}
}
Pressing the button connects D2 to ground, which produces the FALLING edge that invokes buttonISR(). The ISR itself contains a single statement, edgeDetected = true;, and makes no attempt at serial output or debouncing. Declaring the flag volatile tells the compiler that, from the main program's perspective, its value can change unexpectedly.
Inside loop(), the sketch briefly disables interrupts while it copies and clears the flag. That short critical section prevents a new interrupt from changing the flag between the two operations, and the Serial output then runs with interrupts enabled.
Open the Serial Monitor at 115200 baud and press the button a few times. Occasionally, a single press will print two or more lines, which brings us to contact bounce.
Why Button Debouncing Matters
Mechanical button contacts seldom make a perfectly clean transition. Instead, a single press can produce a burst of HIGH and LOW edges over a few milliseconds. Without filtering, that one physical press may invoke the ISR several times, especially in CHANGE mode.

The Stage 2 sketch handles bounce by waiting 30 milliseconds after an edge and confirming the button state before acting. That said, don't automatically apply this button-oriented delay to sensors that produce legitimate fast pulses. In those applications, rejecting any event that arrives within 30 milliseconds of the last one could discard real data.
Stage 2: Debounced LED Toggle
The complete sketch keeps the same ISR and flag transfer but adds press validation and release detection on top:
const byte buttonPin = 2;
const byte ledPin = LED_BUILTIN;
volatile bool interruptFlag = false;
bool ledOn = false;
bool buttonHeld = false;
bool checkingPress = false;
unsigned long pressCheckStarted = 0;
unsigned long releaseStarted = 0;
const unsigned long debounceMs = 30;
void buttonISR() {
interruptFlag = true;
}
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(buttonPin),
buttonISR, FALLING);
}
void loop() {
bool pending;
noInterrupts();
pending = interruptFlag;
interruptFlag = false;
interrupts();
// Wait briefly, then confirm the input is LOW.
if (pending && !buttonHeld && !checkingPress) {
checkingPress = true;
pressCheckStarted = millis();
}
if (checkingPress &&
millis() - pressCheckStarted >= debounceMs) {
checkingPress = false;
if (digitalRead(buttonPin) == LOW) {
buttonHeld = true;
ledOn = !ledOn;
digitalWrite(ledPin, ledOn);
}
}
// Re-arm only after a stable HIGH release.
if (buttonHeld) {
if (digitalRead(buttonPin) == HIGH) {
if (releaseStarted == 0) releaseStarted = millis();
if (millis() - releaseStarted >= debounceMs) {
buttonHeld = false;
releaseStarted = 0;
}
} else {
releaseStarted = 0;
}
}
}
Understanding the Code
In setup(), INPUT_PULLUP gives D2 a defined idle state without an external resistor, so the pin reads HIGH when the button is released. The ISR and the flag transfer at the top of loop() work the same way they did in Stage 1.
Once it detects an edge, loop() waits 30 milliseconds and confirms that the button is still LOW. If so, the sketch toggles the LED once and then waits for a sustained HIGH level before accepting a new press.
As a result, the sketch deliberately ignores taps shorter than about 30 milliseconds. For a human-operated button, that trade-off is usually sensible, since a deliberate press lasts longer, but it does mean the sketch will not register every extremely brief contact.
Keep in mind that this approach is only one debounce strategy. Switches with unusually long bounce or noisy wiring may need a more rigorous state machine or hardware filtering.
Important Rules When Writing an ISR
Interrupts are convenient, but they also bring responsibilities. In general, a short, predictable ISR is easier to debug and less likely to interfere with the rest of your program. The following rules help keep it that way:
- Keep ISRs short — Set a flag or update a small counter, then return.
- Skip delay() — On classic AVR Arduinos, timing relies on interrupts that cannot run normally while another ISR executes.
- Leave out Serial.print() — Serial buffering and transmission may depend on interrupt activity, so a print call can stall an ISR.
- Declare ISR-shared variables volatile — The qualifier stops the compiler from assuming they change only in ordinary program flow.
- Protect multi-byte shared values — An 8-bit ATmega328P reads a 32-bit value across several instructions, so an interrupt can land partway through the read.
- Don't assume every event is queued — One-bit flags and hardware pending flags cannot store an unlimited number of occurrences.
Timing functions deserve special care. During a long AVR ISR, millis() does not advance normally, and delay() has no place there at all. micros() can help with very short ISR timing, although it too has limits if interrupts stay disabled for too long. As a general pattern, record the event immediately and leave timing, processing and Serial output to loop().
Disabling Interrupts vs. Detaching Them
All three examples call noInterrupts() and interrupts(), which can be confused with detachInterrupt(). Although the names sound similar, the functions serve different purposes:
- noInterrupts() / interrupts() — Disable and re-enable interrupts globally. Every interrupt source waits while they are off, so reserve them for short critical sections, such as copying a shared variable.
- detachInterrupt() — Remove the handler attached to one specific source, such as D2. Other interrupts, including the timer that drives millis(), keep running.
detachInterrupt(digitalPinToInterrupt(buttonPin)); // Stop responding to D2
attachInterrupt(digitalPinToInterrupt(buttonPin), // Resume later
buttonISR, FALLING);
Detaching suits situations where the sketch should ignore an input for a while, such as during calibration. On AVR boards, however, an edge that occurs while the handler is detached can leave a pending flag, so the ISR may run once immediately after you re-attach it.
Example 2: Counting Pulses with an Interrupt
While a push button works well for learning attachInterrupt(), a pulse counter better demonstrates the practical advantage. Imagine a Hall-effect sensor that generates one signal edge whenever a rotating shaft passes a magnet. If loop() pauses now and then to update a display or handle other work, polling may miss a narrow pulse entirely.
To build the circuit, connect a sensor with a suitable 5 V-compatible digital output to D2, and tie the sensor's ground to the Arduino's. The sketch below assumes an open-collector or open-drain output that relies on INPUT_PULLUP. Because Hall sensor modules differ, check your sensor's output stage and voltage before wiring.
const byte pulsePin = 2;
volatile unsigned long pulseCount = 0;
unsigned long previousCount = 0;
unsigned long previousSample = 0;
void countPulse() {
++pulseCount;
}
void setup() {
Serial.begin(115200);
pinMode(pulsePin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(pulsePin),
countPulse, FALLING);
previousSample = millis();
}
void loop() {
unsigned long now = millis();
if (now - previousSample >= 1000) {
unsigned long snapshot;
noInterrupts();
snapshot = pulseCount;
interrupts();
unsigned long pulses = snapshot - previousCount;
unsigned long elapsedMs = now - previousSample;
float frequencyHz = (pulses * 1000.0) / elapsedMs;
Serial.print("Pulse frequency: ");
Serial.print(frequencyHz, 1);
Serial.println(" Hz");
previousCount = snapshot;
previousSample = now;
}
}
Here, countPulse() increments a volatile counter on each falling edge. Meanwhile, loop() periodically takes an atomic snapshot of that counter and calculates pulses per second. Notice that the sketch disables interrupts only for the copy, not for the floating-point calculation or the Serial output.
The snapshot matters on the ATmega328P because an unsigned long is 32 bits wide, while the CPU processes only eight bits at a time. Without protection, an interrupt could modify the counter partway through the main program's read. As a bonus, the unsigned subtraction handles normal counter rollover, provided fewer than 2^32 pulses accumulate between samples.
Even so, hardware still sets limits. A sensor can produce noise and false transitions, each pulse must meet the input's timing requirements, and the CPU cannot service interrupts infinitely fast. At very high pulse rates, the microcontroller's hardware counter/timer features may be a better fit.
For a rotating shaft, the measured frequency converts directly to rotational speed:

Here, f is the measured frequency in hertz, and P is the number of pulses per revolution. For example, with one magnet producing one pulse per revolution, a reading of 10 Hz corresponds to 600 RPM.
Arduino Interrupts vs. Polling
Interrupts are not always the right tool. Polling simply means checking an input inside loop(), and for a slowly changing signal, a debounced human button or a program with a short non-blocking loop, it can be simpler than an interrupt. A basic polling check looks like this:
if (digitalRead(2) == LOW) {
// Handle a pressed button
}
An interrupt earns its place when events arrive asynchronously or when pulses might be short relative to the loop's workload. Even then, it does not guarantee zero latency or perfect capture. Hardware and the CPU still have timing limits, and repeated events may arrive faster than software can service them. In short, the two approaches compare as follows:
- Polling: Simple for slow signals; no ISR or shared-data coordination; can miss brief pulses while loop() is busy.
- Interrupts: Respond independently of loop() polling frequency; appropriate for many pulse and encoder tasks; require attention to timing and ISR-shared state.
Pin Change Interrupts on the ATmega328P
So far, we've used D2 to detect external events. However, the Uno R3 has only two dedicated external interrupt inputs. What if both are already occupied and another sensor needs an interrupt? Fortunately, the ATmega328P offers another mechanism called pin change interrupts (PCINT), which let many additional digital and analog-labeled GPIO pins on an Uno R3 or classic Nano generate interrupts.
Unlike INT0 and INT1, though, PCINT inputs share a small number of interrupt vectors. Because every enabled pin in a group calls the same handler, that handler must inspect the port state to determine which pin changed. On the Uno, the pins fall into three groups:
- PCINT0–7: D8–D13, handled by PCINT0_vect.
- PCINT8–14: A0–A5, handled by PCINT1_vect.
- PCINT16–23: D0–D7, handled by PCINT2_vect.
These ranges follow the ATmega328P's internal numbering, and the list covers only the ordinary GPIO available on the Uno rather than every package pin. Any gaps in the numbering belong to pins reserved for the reset and oscillator functions.

The Registers: PCICR, PCIFR and PCMSK
Three registers control pin change interrupts. PCICR enables an interrupt group, PCMSK0, PCMSK1 and PCMSK2 select which pins within each group can trigger it, and PCIFR holds the pending group flags. To enable A0 (PCINT8), for example, set bit PCINT8 in PCMSK1, clear any pending flag, and then enable the group with PCIE1:
PCMSK1 |= (1 << PCINT8); // Select A0 / PCINT8
PCIFR = (1 << PCIF1); // Clear pending PCINT1 flag
PCICR |= (1 << PCIE1); // Enable the PCINT1 group
Notice that the |= operators set only the bits each step needs, leaving the rest of PCMSK1 and PCICR untouched. PCIFR is the exception: writing a 1 to a flag bit clears it, so a plain assignment clears PCIF1 without affecting the other flags.
Example 3: Using A0 as a Pin Change Interrupt
For this example, connect a momentary button between A0 and GND. Unlike attachInterrupt() with FALLING, basic PCINT hardware reacts to a change in either direction. The ISR therefore tracks A0's previous state and detects HIGH-to-LOW transitions in software.

#include <avr/interrupt.h>
const byte buttonPin = A0;
volatile bool a0Falling = false;
bool previousA0High = true;
ISR(PCINT1_vect) {
bool currentA0High = (PINC & (1 << PINC0)) != 0;
if (previousA0High && !currentA0High) {
a0Falling = true;
}
previousA0High = currentA0High;
}
void setup() {
Serial.begin(115200);
pinMode(buttonPin, INPUT_PULLUP);
noInterrupts();
previousA0High = digitalRead(buttonPin);
PCMSK1 |= (1 << PCINT8);
PCIFR = (1 << PCIF1);
PCICR |= (1 << PCIE1);
interrupts();
}
void loop() {
bool pending;
noInterrupts();
pending = a0Falling;
a0Falling = false;
interrupts();
if (pending) {
Serial.println("A0 falling edge detected");
}
}
Inside PCINT1_vect, the ISR reads bit PINC0 to obtain A0's current state. It then compares that state with the previous one and, on a falling edge, sets a flag, leaving Serial output to the main program. Keep in mind that this single ISR serves the whole PCINT1 group, even though the example enables only A0.
Only a0Falling needs the volatile qualifier, because loop() reads it while the ISR can change it at any moment. previousA0High, by contrast, gets its starting value in setup() before the interrupt is enabled and from then on lives entirely inside the ISR, so the compiler's normal assumptions hold.
By design, the sketch is a raw edge detector rather than a complete button interface. A bouncing switch can still produce several edges, and a boolean flag tells the main loop only that one or more transitions occurred. For exactly one event per physical press, add the debounce strategy from Example 1.
Pin Change Interrupt Library
If you would rather not manage the registers yourself, a library can handle them for you. The original tutorial linked to the older PinChangeInt project, but NicoHood's PinChangeInterrupt library now offers a more convenient AVR alternative, with attachPCINT() and software-controlled edge selection. Because the library targets selected AVR processors, verify compatibility with your board before using it.
Library: NicoHood PinChangeInterrupt on GitHub
#include <PinChangeInterrupt.h>
const byte buttonPin = A0;
volatile bool buttonEvent = false;
void buttonISR() {
buttonEvent = true;
}
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
attachPCINT(digitalPinToPCINT(buttonPin),
buttonISR, FALLING);
}
void loop() {
bool pending;
noInterrupts();
pending = buttonEvent;
buttonEvent = false;
interrupts();
if (pending) {
// Debounce and handle the press here.
}
}
Like Example 3, this sketch is not a complete debounced button application; it shows only how to attach the interrupt and transfer an event flag safely. Its real advantage lies in the setup: the library handles the AVR-specific pin change configuration, so your application can use a familiar API.
Troubleshooting and FAQs
Why does my button trigger two or more interrupts?
Mechanical contact bounce is the most common cause. To fix it, use a debounce strategy, and if you only care about the press, choose FALLING rather than CHANGE.
Why isn’t attachInterrupt() responding?
Start by confirming that you are using one of the board's interrupt-capable pins and that the circuit shares a common ground. Next, make sure a pull-up or pull-down resistor gives the input a defined level. Finally, check the trigger edge; FALLING, for example, requires a HIGH-to-LOW transition.
Can I use delay() or Serial.print() inside an ISR?
Avoid both. On a classic AVR, delay() depends on timer behavior that cannot progress normally inside an ISR, while Serial output may rely on interrupt-driven buffers. Instead, set a flag in the ISR and handle these operations in loop().
Can I use any Arduino pin as an interrupt?
Not necessarily. On a classic Uno R3, attachInterrupt() supports only D2 and D3. Beyond those two, other GPIO pins can produce pin change interrupts through the ATmega328P hardware or a suitable AVR library. Boards built on different microcontrollers follow their own rules, so check the documentation for yours.
Does volatile make a shared counter atomic?
No. The volatile qualifier affects compiler optimization, not the number of machine instructions needed to access a variable. For shared multi-byte data on eight-bit AVR controllers, use an atomic snapshot or a short critical section.
Why do I still miss some fast pulses?
Several factors can cause missed pulses. A pulse may be shorter than the hardware can recognize, interrupt handling may be delayed, or the event rate may exceed the CPU's capacity. In addition, a boolean flag collapses multiple events into one indication, so for an accurate count, increment a counter in the ISR instead.
Conclusion
Arduino interrupts let projects react to external events without relying on continuous polling. On the Uno R3, attachInterrupt() on D2 or D3 offers the easiest starting point. Whichever pin you use, keep the ISR short, let loop() do the slower work, and protect any shared data.
When those two pins aren't enough, the ATmega328P's pin change interrupt hardware offers another option. Direct register access helps you understand the microcontroller, while a supported library keeps application code simpler.
Finally, for events driven by elapsed time rather than external edges, continue with the Arduino Timer Interrupt Tutorial.






Fantastic simplification of interrupts.
I've read many explanations but never really understood how to actually make them work.
I've read almost all of your tutorials because they are helpful and so well written.
Thanks,
Steve
Thank you for the kind words Steve
Thanks so much for this great tutorial.
Can you clear one thing for me.
In the full sketch code I expected this line
PCMSK = B00000001; //enable PCINT8
to be
PCMSK1 = B00000001; //enable PCINT8
What am I missing. There are 3 Pin Mask Registers, so I expected that you would have to name them explicitly.
Cheers
Mike
Hey Mike,
Thanks for pointing that out. You are correct, it should be PCMSK1. It seems I accidentally omitted the 1 at the end.
I could easily understand about interrupts
Great Tutorial.
Have one question.
How to set the CHANGE, LOW, HIGH, RISING, FALLING options when using the Pin Change Interrupt?
Thanks again for this interesting tutorial.
Hi,
Good question! Looking at the datasheet, there's no register for specifying the trigger type (CHANGE, LOW, HIGH, RISING, FALLING) when using Pin Change Interrupt, unlike in the external interrupts (which has EICRA). This is logical since it's called pin change interrupt so it must only trigger on CHANGE. But if you noticed, in the PinChangeInt library I presented, there seems to be an option to specify the trigger event:
Looking at the library, I saw this:
PCintPin* p = firstPin; while (p) { // Trigger interrupt if the bit is high and it's set to trigger on mode RISING or CHANGE // Trigger interrupt if the bit is low and it's set to trigger on mode FALLING or CHANGE if (p->mask & changedPins) { #ifndef NO_PIN_STATE PCintPort::pinState=PCintPort::curr & p->mask ? HIGH : LOW; #endif #ifndef NO_PIN_NUMBER PCintPort::arduinoPin=p->arduinoPin; #endif #ifdef PINMODE PCintPort::pinmode=p->mode; PCintPort::s_portRisingPins=portRisingPins; PCintPort::s_portFallingPins=portFallingPins; PCintPort::s_pmask=p->mask; PCintPort::s_changedPins=changedPins; #endif p->PCintFunc(); } p=p->next; }According to this, while there's nothing on the datasheet that says you can't specify the trigger event on pin change interrupt, it seems the library still allows you to do that depending on the initial state of your interrupt pin. So rising edge triggering is possible if the interrupt pin is initially low then made high or falling edge triggering is possible if the interrupt pin is initially high then made low.
I hoped this answered your question.