Sub topic 3
Debouncing in Software with Timestamps
This chapter assumes you can read setup() and loop(), use digitalRead(), and wire a pushbutton with pull-up input (INPUT_PULLUP). You should also understand millis() and unsigned integers.
Debouncing in software with timestamps
A mechanical button makes and breaks contact several times in a few milliseconds. The sketch sees each change as a separate press. A software debounce waits until the reading has stayed steady for a set time, then accepts it.
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: pin is pulled to GND
ledState = !ledState;
digitalWrite(LED_BUILTIN, ledState);
}
}
}Blinking and button handling together
Because loop() never blocks, the same sketch can blink an LED with a timer and check the button on every pass. Keep a separate previousBlink timestamp for each task.
Hardware debouncing: RC filters and Schmitt triggers
An RC filter (a resistor and capacitor) smooths the voltage so that short bounces do not cross the logic threshold. A Schmitt trigger is a logic input with two thresholds, which gives a clean edge once the signal crosses the upper or lower level. Hardware fixes cost parts and board space, so software debouncing is usually enough for a simple button.
Debouncing with interrupts and its pitfalls
An interrupt runs a function when a pin changes, so the sketch does not need to poll. Use attachInterrupt() with a short handler that sets a volatile flag. Avoid Serial calls and long work inside the handler. Bounces still trigger the interrupt, so you must still check a timestamp.
Extending the pattern: long press and repeat
Record the time when the button goes down. On release, compare the elapsed time with a threshold to tell a short press from a long press. For repeat, fire an action each time the held time passes another interval.
> Warning: this is a summary, not a complete design. Test each change on your own board.
Exercise
Why does the timestamp debounce restart its timer whenever the raw reading changes?
Show answer
A bounce produces rapid changes. Restarting the timer on each change means the reading must stay steady for the full DEBOUNCE_MS before the sketch accepts it.