Sub topic 12
Debouncing with interrupts and its pitfalls
This chapter assumes you can write a setup() and loop() sketch, wire a pushbutton to INPUT_PULLUP, and use millis() for non-blocking timing. It also assumes you have seen timestamp-based software debouncing. Here you will use a hardware interrupt to catch a button press, filter out bounce inside the interrupt routine, and learn where this approach fails.
Why use an interrupt for a button
A polling sketch reads the pin on every pass through loop(). If loop() is fast, polling works well. If loop() sometimes spends a long time on other work, such as writing to an SD card or updating a display, a short press can start and end between two reads. The sketch never sees it.
An interrupt changes who watches the pin. The microcontroller's hardware notices the pin change and pauses loop(). It then runs a small function called an interrupt service routine (ISR), and afterwards resumes loop() where it stopped. The press is captured even if loop() is busy.
An ISR is a function that the hardware calls when an event occurs. You register it with attachInterrupt().
A working example
The following sketch toggles an external LED on pin 8 when the button on pin 2 is pressed. It also blinks the built-in LED every 500 ms with no delay(). The button connects pin 2 to GND. It assumes a board where pin 2 supports external interrupts, such as an Uno.
const uint8_t BUTTON_PIN = 2;
const uint8_t LED_PIN = 8;
const unsigned long DEBOUNCE_MS = 50;
const unsigned long BLINK_MS = 500;
volatile unsigned long lastInterruptTime = 0;
volatile bool pressed = false;
unsigned long previousBlink = 0;
bool blinkState = LOW;
bool ledOn = false;
void onPress() {
unsigned long now = millis();
if (now - lastInterruptTime >= DEBOUNCE_MS) {
lastInterruptTime = now;
pressed = true;
}
}
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
pinMode(LED_BUILTIN, OUTPUT);
attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), onPress, FALLING);
}
void loop() {
unsigned long now = millis();
if (now - previousBlink >= BLINK_MS) {
previousBlink = now;
blinkState = !blinkState;
digitalWrite(LED_BUILTIN, blinkState);
}
if (pressed) {
pressed = false;
ledOn = !ledOn;
digitalWrite(LED_PIN, ledOn);
}
}How the code works
INPUT_PULLUPholds the pin HIGH when the button is open. Pressing the button pulls the pin to GND, so a press is a falling edge.attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), onPress, FALLING)callsonPress()on each HIGH-to-LOW transition. UsedigitalPinToInterrupt()rather than a raw interrupt number, because the mapping from pin to interrupt number differs between boards.onPress()compares the current time with the last accepted edge. Bounce edges arrive within a few milliseconds of the first edge, so they fail the 50 ms test and are dropped.- The ISR only sets a flag.
loop()does the real work (toggling the LED), outside interrupt context.
The rules for writing an ISR
An ISR runs with the normal flow of your program suspended. Keep these rules in mind.
- Keep it short. While the ISR runs, other interrupts of the same or lower priority wait. On AVR boards such as the Uno, interrupts are disabled by default inside an ISR.
- Do not call
delay(). It relies on timer interrupts that are blocked inside the ISR, so it will not work as expected. - Do not rely on
millis()advancing.millis()is safe to read in an ISR, but its value does not change while the ISR runs, because the timer interrupt that updates it is blocked on AVR boards. - Avoid
Serial.print(). Serial output can block when its buffer is full. This can freeze the sketch from inside an ISR. - Mark shared variables
volatile. This is explained next.
Why `volatile` matters
The compiler optimizes code under the assumption that a variable only changes when your code changes it. In loop(), nothing visibly modifies pressed, so the compiler may keep its value in a register and never re-read it from memory. The flag would then never appear to change.
The volatile keyword tells the compiler that the value can change at any time, so it must read it from memory on every access. Any variable written in an ISR and read in loop() (or the reverse) needs it.
Sharing multi-byte values safely
In the example above, loop() only reads the one-byte bool pressed, and a one-byte read cannot be torn. If you want loop() to read a volatile unsigned long that the ISR writes, copy it with interrupts briefly disabled.
volatile unsigned long lastInterruptTime = 0;
unsigned long readLastInterruptTime() {
noInterrupts();
unsigned long copy = lastInterruptTime;
interrupts();
return copy;
}
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println(readLastInterruptTime());
delay(1000);
}Keep the section between noInterrupts() and interrupts() as short as possible. Interrupts that fire during that window are held until interrupts() runs, and a long window can make you miss events.
There is one more subtlety in the first example. Between the test if (pressed) and the line pressed = false; a new press could set the flag, and you would lose it. For a human pressing a button this is extremely unlikely, since the window is a few microseconds. If you count every event, such as pulses from a sensor, use a counter that the ISR increments and that loop() reads and subtracts under noInterrupts().
Pitfalls of interrupt debouncing
The time filter ignores everything, including real events
The ISR in the example drops any edge within 50 ms of the previous accepted edge. This is a lockout. A genuine second press inside that window is lost. For a human button that is fine. For a fast encoder or a signal that legitimately changes quickly, it is wrong.
Falling-edge-only detection can miss the release
The example reacts only to the press. Contact bounce also occurs on release. Because the ISR is attached to FALLING, a release bounce can produce a stray falling edge. Consider this sequence:
- The button is pressed. The ISR accepts the first falling edge.
- The button is released and bounces. The pin goes HIGH, briefly LOW, then HIGH.
- That brief LOW is a falling edge.
If the release happens more than 50 ms after the press, which is typical for a human press, the stray falling edge from release bounce will pass the time filter and register as a second press. The lockout only protects against bounce close to the previous accepted edge.
You can fix this in several ways:
- Attach the interrupt to
CHANGE, record every edge's timestamp, and let the ISR update the lockout on both press and release edges. - Use a hardware filter, such as an RC network with a Schmitt trigger, so the pin never sees bounce.
- Have the ISR only wake the sketch, then confirm the state in
loop()with a stable-state check.
Noise and long wires cause false triggers
An interrupt reacts to any edge, including a spike picked up by a long wire. Polling with a stable-time check naturally ignores brief glitches. An interrupt does not, unless you add filtering in software or hardware.
Not every pin supports interrupts
On the Uno, only pins 2 and 3 support attachInterrupt(). Other boards allow more pins. Check your board's documentation before choosing a pin. Using digitalPinToInterrupt() on an unsupported pin gives an invalid value, and the interrupt silently never fires.
ISRs hide timing bugs
A polled sketch behaves the same way on every pass. An interrupt-driven sketch depends on when the interrupt lands relative to loop(). Bugs such as torn multi-byte reads appear rarely and are hard to reproduce. Prefer simple designs with a single flag and short, well-defined handoffs.
Choosing between approaches
| Approach | Strengths | Weaknesses | Good fit |
|---|---|---|---|
| Polling with timestamp debounce | Simple, no shared-state problems, ignores short glitches | A press can be missed if `loop()` stalls for long | Most hobby projects with a responsive `loop()` |
| Interrupt with time filter | Catches presses even when `loop()` is busy | Needs `volatile`, limited pins, release bounce can leak through | Sketches with long-running work, or wake-from-sleep |
| RC filter and Schmitt trigger | Removes bounce before the microcontroller sees it | Extra parts, fixed time constant | Noisy environments, or when software cannot be changed |
A common combination is to use the interrupt only to catch the event and to confirm it with a stable-time check in loop(). This gives you the guarantee that no press is missed and the noise tolerance of polling.
Testing your interrupt debounce
To check whether your debounce works, count events.
- Add a
volatile unsigned intcounter incremented in the ISR only when an edge is accepted. - Print the counter from
loop()on a slow schedule, usingmillis()and notdelay(). - Press the button 20 times with deliberate, separated presses.
- If the count is higher than 20, bounce or release bounce is leaking through. If it is lower, your lockout is swallowing real presses or presses were too close together.
Exercise
In the example sketch, the ISR is attached with FALLING and uses a 50 ms lockout. Describe one way a single press-and-release can still toggle the LED twice, and name one fix.
Show answer
When the button is released, contact bounce can pull the pin LOW briefly. That produces a falling edge. If the release happens more than 50 ms after the press, the lockout has expired, so the ISR accepts the stray edge as a new press. Fixes include attaching to CHANGE and updating the lockout timestamp on every edge, adding an RC filter with a Schmitt trigger, or confirming the pin state in loop() after a stable period.
Exercise
Why must the flag pressed be declared volatile, and why is volatile alone not enough to safely share a 4-byte unsigned long on an 8-bit AVR board?
Show answer
Without volatile, the compiler may keep pressed in a register inside loop() and never see the ISR's change. Volatile forces a real memory read on every access. It does not make multi-byte accesses atomic, so an interrupt can fire between the byte reads of an unsigned long and leave a mixed value. Wrap the copy in noInterrupts() and interrupts().