Sub topic 10
Debouncing a Button with `millis`
What debouncing solves
This chapter assumes you know the Arduino setup() and loop() functions, pinMode(), digitalRead(), digitalWrite(), and basic resistor and breadboard wiring.
A real push button does not change from open to closed perfectly. Its metal contacts can touch and separate several times in a few milliseconds. This behavior is called contact bounce. The Arduino is fast enough to observe these rapid changes.
Without debouncing, one physical press can look like several presses:
If your program toggles an LED whenever it detects a press, contact bounce may toggle the LED several times. The final state can seem random.
Debouncing is the process of accepting a new button state only after the reading has stayed unchanged for a short period. A delay of 20 to 50 milliseconds is common.
The `millis()` approach
millis() returns the number of milliseconds since the Arduino started running the current sketch. Unlike delay(), it lets loop() continue running while time passes.
The debounce algorithm is:
- Read the pin.
- If the raw reading changed, record the current time.
- Wait until the raw reading has remained unchanged for the debounce interval.
- Accept it as the new stable state.
Use an internal pull-up in this example. Connect one button terminal to pin 2 and the other terminal to GND. The pin reads HIGH when released and LOW when pressed.
| Variable | Purpose |
|---|---|
| `lastReading` | Most recent raw pin reading |
| `stableState` | Last reading accepted as valid |
| `lastChangeTime` | Time when the raw reading last changed |
| `debounceMs` | Required stable time |
const int buttonPin = 2;
const int ledPin = LED_BUILTIN;
const unsigned long debounceMs = 25;
int lastReading = HIGH;
int stableState = HIGH;
unsigned long lastChangeTime = 0;
bool ledOn = false;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}
void loop() {
int reading = digitalRead(buttonPin);
if (reading != lastReading) {
lastChangeTime = millis();
lastReading = reading;
}
unsigned long elapsed = millis() - lastChangeTime;
if (elapsed >= debounceMs && reading != stableState) {
stableState = reading;
if (stableState == LOW) {
ledOn = !ledOn;
digitalWrite(ledPin, ledOn ? HIGH : LOW);
}
}
}The expression millis() - lastChangeTime is intentional. Since both values are unsigned long, this subtraction continues to work when millis() eventually wraps around to zero.
The LED changes only when the stable state becomes LOW. That is the press event for an INPUT_PULLUP circuit. Holding the button does not repeatedly toggle the LED because the stable state does not change again.
Why not use `delay()`?
A simple version might read the button, call delay(25), and read it again. That can work for a small experiment, but delay() stops the entire loop() from doing other work. During the delay, the Arduino cannot update a display, check another input, or run timing-based tasks.
The millis() method keeps the sketch responsive. Each pass through loop() performs a quick check and then continues.
> callout note > Choose the shortest debounce interval that reliably removes false transitions. A value that is too short may allow bounce through. A value that is too long makes the button feel slow. >
Common errors
- Comparing a pressed input with
HIGHwhen usingINPUT_PULLUP. Pressed meansLOW. - Toggling the output whenever the button is held. Toggle only when the stable state changes to the pressed level.
- Resetting the timer only after accepting a state. Reset it whenever the raw reading changes.
- Using a blocking
delay()in a sketch that must perform other tasks. - Omitting the resistor or
INPUT_PULLUP, which leaves the input floating when the button is open.
Exercise
Why does the example toggle the LED only when stableState == LOW, instead of every time the loop reads LOW?
Show answer
With INPUT_PULLUP, LOW means pressed. Checking only when the stable state changes to LOW detects one press event. Repeated loop passes while the button is held do not toggle the LED again.