Sub topic 9
Debouncing in software with timestamps
This chapter assumes you can write a basic sketch with setup() and loop(), wire a pushbutton to a pin with INPUT_PULLUP, and read it with digitalRead(). It also assumes you know the millis() interval pattern, unsigned subtraction, and how to detect a state change. Here you combine those pieces into a timestamp-based debounce that reports exactly one event per press and never blocks the sketch.
The problem to solve
A mechanical button does not close cleanly. For a few milliseconds after the contacts touch, the pin flips between HIGH and LOW several times. A sketch that polls the pin on every pass through loop() can see those flips as separate presses. If your code toggles an LED on each falling edge, one physical press can toggle it two, three, or five times, and the final LED state looks random.
A debounce routine has one job. It takes the noisy raw reading and produces a clean state that changes only once per real press or release.
The delay() approach is tempting: wait 50 ms after the first change and read again. It works for a single button, but it freezes the whole sketch for that time. Timestamps solve the same problem without stopping anything.
The idea: wait for the signal to settle
The rule is simple:
> Accept a new button state only after the raw reading has stayed unchanged for a minimum time.
Every time the raw reading differs from the previous raw reading, you record the current time. While the signal is still bouncing, that timestamp keeps moving forward, so the "unchanged" timer keeps restarting. Once the reading holds steady for the debounce interval, you treat it as the real state.
This needs three pieces of memory:
lastReading: the raw value from the previous pass ofloop().lastChangeTime: themillis()value when the raw reading last changed.stableState: the debounced value your program trusts.
The full sketch
The button connects pin 2 to GND. With INPUT_PULLUP, the pin reads HIGH when the button is released and LOW when it is pressed. Each press toggles the built-in LED.
const uint8_t BUTTON_PIN = 2;
const unsigned long DEBOUNCE_MS = 30;
int lastReading = HIGH;
int stableState = HIGH;
unsigned long lastChangeTime = 0;
bool ledState = LOW;
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
int reading = digitalRead(BUTTON_PIN);
if (reading != lastReading) {
lastChangeTime = millis();
lastReading = reading;
}
if ((millis() - lastChangeTime >= DEBOUNCE_MS) && (reading != stableState)) {
stableState = reading;
if (stableState == LOW) { // pressed: the pin is pulled to GND
ledState = !ledState;
digitalWrite(LED_BUILTIN, ledState);
}
}
}How it works, step by step
Step 1: detect any raw change
if (reading != lastReading) {
lastChangeTime = millis();
lastReading = reading;
}This block runs on every flicker. It does not decide anything about the button. It only restarts the settling clock and remembers what the pin just did.
Step 2: check whether the signal has settled
if ((millis() - lastChangeTime >= DEBOUNCE_MS) && (reading != stableState)) {Two conditions must both be true:
- At least
DEBOUNCE_MSmilliseconds have passed since the last raw change. - The settled raw reading differs from what the program already believes.
The second condition is what makes the event fire once. After stableState is updated, reading equals stableState on every later pass, so the block does not run again until the pin truly changes.
Step 3: accept the new state and act on the edge
stableState = reading;
if (stableState == LOW) {
ledState = !ledState;
digitalWrite(LED_BUILTIN, ledState);
}Only the transition to LOW (a press) toggles the LED. The release also updates stableState, but it triggers no action. This is state-change detection applied to the debounced signal instead of the raw one.
A trace of one bouncy press
The table shows a press at about t = 100 ms with DEBOUNCE_MS = 30. The pin bounces, then settles LOW.
| Time (ms) | Raw reading | Raw changed? | lastChangeTime | Settled? | Action |
|---|---|---|---|---|---|
| 90 | HIGH | No | 0 | Yes, but equals stableState | None |
| 100 | LOW | Yes | 100 | No | None |
| 102 | HIGH | Yes | 102 | No | None |
| 105 | LOW | Yes | 105 | No | None |
| 120 | LOW | No | 105 | No (15 ms) | None |
| 135 | LOW | No | 105 | Yes (30 ms) and differs | stableState = LOW, toggle LED |
| 200 | LOW | No | 105 | Yes, but equals stableState | None |
The bounces at 100, 102, and 105 each reset the clock. The LED toggles once at 135, not three times.
Choosing the debounce interval
The right value depends on the switch. Small tactile buttons usually settle within 1 to 10 ms, and worn or cheap switches can take 20 ms or more. A value between 20 and 50 ms works for most hobby projects.
- Too short: bounces that outlast the interval slip through as extra presses.
- Too long: the button feels sluggish, and fast legitimate presses can be missed.
If you are unsure, print the time between raw changes with Serial while pressing the button many times, then pick an interval comfortably above the longest bounce you see.
Why unsigned subtraction matters here
millis() returns an unsigned long that wraps to 0 after about 49.7 days. The expression millis() - lastChangeTime stays correct across that wrap, as long as both operands are unsigned and the real elapsed time is under the counter range.
// Correct: unsigned subtraction gives the right elapsed time even after millis() wraps to 0.
if (millis() - startTime >= timeout) {
// timeout has elapsed
}
// Fragile: breaks when millis() rolls over, because the sum wraps and compares as a small number.
// if (millis() >= startTime + timeout) { ... }Keep lastChangeTime as unsigned long. If you store it in an int, it truncates after about 32 seconds on an 8-bit board and the debounce check fails in confusing ways.
Common errors
- Using
delay()for the debounce. It works for one button but blocks everything else, including a blinking LED or a second button. - Acting on the raw reading. If the action sits inside the first
ifblock, bounces still trigger it. - Forgetting to update
lastReading. The raw-change test then fires on every pass and the settling timer never completes. - Updating
stableStatewithout checkingreading != stableState. The action repeats on every pass while the button is held. - Reversed logic with
INPUT_PULLUP. A press is LOW. Testing for HIGH makes the LED toggle on release instead. - Storing time in a smaller type. Use
unsigned longfor all values that holdmillis()results. - Wiring to a pin without a pull-up. A floating input picks up noise and looks like endless bouncing. Use
INPUT_PULLUPor an external resistor.
Wrapping the logic for reuse
When a sketch has several buttons, repeating three global variables per button gets messy. A small struct keeps each button's state together. This version reports a press as a return value, so the caller does not need to know the debounce details.
struct Button {
uint8_t pin;
unsigned long debounceMs;
int lastReading;
int stableState;
unsigned long lastChangeTime;
};
Button button = {2, 30, HIGH, HIGH, 0};
bool ledState = LOW;
// Returns true exactly once per debounced press.
bool wasPressed(Button &b) {
int reading = digitalRead(b.pin);
bool pressedEvent = false;
if (reading != b.lastReading) {
b.lastChangeTime = millis();
b.lastReading = reading;
}
if ((millis() - b.lastChangeTime >= b.debounceMs) && (reading != b.stableState)) {
b.stableState = reading;
if (b.stableState == LOW) {
pressedEvent = true;
}
}
return pressedEvent;
}
void setup() {
pinMode(button.pin, INPUT_PULLUP);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
if (wasPressed(button)) {
ledState = !ledState;
digitalWrite(LED_BUILTIN, ledState);
}
}Call wasPressed() on every pass of loop(). It must run often so the timestamps are fresh, and it must be called once per pass, because each call consumes the event.
Edge cases
- A press shorter than the debounce time. A tap that releases before
DEBOUNCE_MShas elapsed is never accepted, because the signal does not stay stable long enough. This is usually desirable, since it filters out glitches. - Button held at power-up.
stableStatestarts as HIGH, so if the button is already down at boot, the first settled LOW reading registers as a press. Initialize fromdigitalRead()insetup()if you want to ignore that. - Slow
loop(). If other code makes a pass take longer than the debounce interval, you can miss the bounce entirely and accept a state late. Keep each pass short. - Release bounce. Contacts also bounce on release. This sketch handles it the same way, but it takes no action on release.
Check your understanding
Exercise
In the sketch, what two conditions must be true before stableState is updated, and what does each one prevent?
Show answer
First, millis() - lastChangeTime >= DEBOUNCE_MS must be true, which prevents accepting a reading while the pin is still bouncing. Second, reading != stableState must be true, which prevents the same state from being accepted again on every pass, so the action fires only once per press.
Exercise
A student changes unsigned long lastChangeTime to int lastChangeTime. The button works for the first half minute after power-up, then stops responding reliably. Why?
Show answer
On a board with 16-bit int, such as an Uno, the stored timestamp truncates once millis() exceeds 32767 (about 33 seconds). The subtraction millis() - lastChangeTime then produces wrong elapsed times, so the settled check is true or false at the wrong moments. Use unsigned long for all millis() timestamps.
Exercise
Modify the first sketch so the LED toggles when the button is released instead of when it is pressed. Which line changes?
Show answer
Change if (stableState == LOW) to if (stableState == HIGH). With INPUT_PULLUP, HIGH means released, so the toggle now happens when the debounced state returns to HIGH.