Sub topic 12
Debouncing with Interrupts and Its Pitfalls
Prerequisites and the interrupt model
This chapter assumes that you understand setup(), loop(), digitalRead(), pinMode(), INPUT_PULLUP, millis(), and timestamp-based software debouncing. It also assumes that a pushbutton connects an Arduino Uno pin to GND.
An interrupt is a hardware-triggered call to a special function. Instead of waiting for loop() to notice a pin change, the microcontroller pauses normal code briefly and runs an interrupt service routine (ISR). When the ISR returns, loop() continues.
For a button connected to pin 2, a falling edge occurs when the pin changes from HIGH to LOW. With INPUT_PULLUP, this usually means that the button was pressed.
Interrupts are useful when an event must be noticed quickly or when loop() has other work to do. They do not remove contact bounce. A bouncing button can still trigger several interrupts in a few milliseconds.
| Input method | Main strength | Main risk |
|---|---|---|
| Polling in `loop()` | Simple and easy to debug | A long task can delay detection |
| Interrupt | Notices an edge without waiting for `loop()` | The ISR must be short and carefully synchronized |
| Interrupt plus debounce | Fast event notification with bounce filtering | More rules about shared data and supported pins |
A short ISR that sets a flag
The safest common pattern is to let the ISR record an event and let loop() perform the real work. The ISR below checks the elapsed time since the last accepted edge. If the edge is too soon, it treats it as bounce.
volatile tells the compiler that a variable can change outside the current flow of code. Without it, the compiler might reuse an old value instead of reading the value written by the ISR.
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 haveInterruptTime = false;
volatile bool pressed = false;
unsigned long previousBlink = 0;
bool blinkState = LOW;
bool ledState = LOW;
void onPress() {
unsigned long now = millis();
if (!haveInterruptTime ||
now - lastInterruptTime >= DEBOUNCE_MS) {
lastInterruptTime = now;
haveInterruptTime = true;
pressed = true;
}
}
bool takePressEvent() {
noInterrupts();
bool event = pressed;
pressed = false;
interrupts();
return event;
}
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 (takePressEvent()) {
ledState = !ledState;
digitalWrite(LED_PIN, ledState);
}
}The built-in LED keeps blinking because loop() never waits with delay(). A valid button press sets pressed. The takePressEvent() function briefly disables interrupts while it reads and clears the flag. This prevents a new event from arriving between those two operations.
Interrupt pitfalls
An ISR should finish quickly. Do not call delay(), perform long calculations, or print with Serial from an ISR. These operations can block other interrupts or make timekeeping inaccurate.
Only some pins support external interrupts. On an Uno, pin 2 and pin 3 are typical choices. digitalPinToInterrupt() makes the code clearer and allows the board core to select the correct interrupt number.
The millis() counter continues to provide an elapsed-time value, but timer interrupts can be delayed while an ISR runs. This is another reason to keep the ISR short.
Shared values need care. A bool is usually read and written atomically on an Uno, but an unsigned long takes several byte operations. If loop() reads a multi-byte value while the ISR changes it, the value can be inconsistent. Use a short critical section, as takePressEvent() does, or copy the value with interrupts disabled.
An interrupt reports an edge, not necessarily a complete press. The example handles the falling edge only. If your project needs release detection, long presses, or repeated presses, add a state machine in loop() rather than expanding the ISR.
Exercise
Why does the example set a flag in the interrupt routine instead of toggling the LED there?
Show answer
The ISR should remain short. The flag lets loop() perform output changes and other application logic safely after the interrupt returns.