Sub topic 10
Debouncing a Button with millis
This chapter shows how to filter contact bounce in software using millis(). It assumes you can wire a button to INPUT_PULLUP, know that a press reads LOW, and know why a mechanical contact can produce several transitions for one press. It also assumes you are comfortable with setup() and loop(), and with variables that keep their values between passes through loop().
The goal: accept a state only when it is stable
A bouncing contact flips between HIGH and LOW for a few milliseconds before it settles. A debounce routine answers one question: has the raw reading stayed the same long enough to trust it?
The usual rule is:
- Read the pin.
- If the reading differs from the previous raw reading, record the time of the change.
- If the reading has stayed unchanged for longer than a debounce interval, accept it as the new stable state.
Every bounce restarts the timer. Only a reading that survives the whole interval becomes the official state.
Why millis and not delay
A beginner fix is to call delay(50) after a change. It works for one button and one task, but delay() halts the whole sketch. Nothing else runs during the pause: other buttons are not read, serial data is not processed, and timed outputs stall.
millis() returns the number of milliseconds since the board started. It does not pause anything. You store a timestamp, and on each pass through loop() you compare the current time to it. The sketch keeps running at full speed, and the debounce check costs only a subtraction and a comparison.
The variables you need
The debounce code keeps three pieces of memory between passes through loop():
| Variable | Purpose |
|---|---|
| `lastReading` | The raw value from the previous pass. Used to notice a change. |
| `stableState` | The last value that survived the debounce interval. Your program acts on this one. |
| `lastChangeTime` | The `millis()` value when the raw reading last changed. |
Keeping the raw reading and the accepted state separate is the key idea. The raw value may jitter. The stable state only changes after the interval has passed.
The full sketch
This sketch toggles the built-in LED once per press. The button connects between pin 2 and GND, and the sketch uses INPUT_PULLUP.
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;
}
if ((millis() - lastChangeTime) >= debounceMs && reading != stableState) {
stableState = reading;
if (stableState == LOW) {
ledOn = !ledOn;
digitalWrite(ledPin, ledOn ? HIGH : LOW);
}
}
}Walking through one press
Suppose the button is released, so lastReading and stableState are both HIGH. You press it, and the contact bounces for about 3 ms.
- At t = 1000 ms the raw reading drops to
LOW. It differs fromlastReading, solastChangeTimebecomes 1000 andlastReadingbecomesLOW. - At t = 1001 ms the contact opens briefly and the reading is
HIGH. It differs again, solastChangeTimebecomes 1001. - The contact bounces a few more times. The last change is at about t = 1003 ms, after which the reading stays
LOW. - For the next 25 ms the first
ifdoes nothing, because the reading equalslastReading. The secondiffails becausemillis() - lastChangeTimeis under 25. - At t = 1028 ms the elapsed time reaches 25 and
reading(LOW) differs fromstableState(HIGH). The press is accepted:stableStatebecomesLOW, and the LED toggles. - On later passes
reading == stableState, so nothing happens until the next real change.
The LED toggles exactly once, even though the pin changed state several times.
Release is debounced too
Bounce occurs on release as well. The same logic handles it. When you let go, the reading goes HIGH, possibly with bounce, and after 25 quiet milliseconds stableState becomes HIGH. The inner if (stableState == LOW) skips the toggle, so only the press acts. Without debouncing the release, a bounce on release could register as a second press if you did not filter it.
Why subtraction is safe when millis rolls over
millis() returns an unsigned long, which is 32 bits on AVR boards such as the Uno. It wraps back to 0 after about 49.7 days. The expression millis() - lastChangeTime still gives the right elapsed time across the wrap, because unsigned subtraction wraps the same way.
Write the comparison as a subtraction. Avoid this form:
// Wrong across rollover: compares absolute times
if (millis() >= lastChangeTime + debounceMs) {
// ...
}Near the rollover point, lastChangeTime + debounceMs can overflow to a small number, and the test becomes true immediately. Also declare timestamps as unsigned long. Using int overflows after 32 seconds on AVR, because int is 16 bits there, and gives negative or truncated values.
Choosing the interval
The debounce interval trades filtering against responsiveness.
| Interval | Effect |
|---|---|
| Under 5 ms | May accept bounce from worn or cheap switches. |
| 10 to 25 ms | Works for most small tactile buttons. |
| 50 ms | Safe for poor switches, with a small but noticeable lag on fast tapping. |
| 100 ms or more | Rapid presses may be missed, and the button feels sluggish. |
Bounce time varies by switch type, age, and how hard you press. If you see double toggles, raise the interval. If fast presses are missed, lower it. You can measure the real bounce duration by recording the time between the first and last change in a press and printing the largest value over many presses.
Common errors
- Updating
lastChangeTimeon every pass. If you set it wheneverreading == stableStateor unconditionally, the timer never ages and no press is accepted. Set it only when the raw reading differs fromlastReading. - Forgetting to update
lastReading. Then every pass after a change looks like a new change, so the timer keeps restarting and the press is never accepted. - Comparing against
stableStatein the first check. The first check must compare against the previous raw reading. Comparing against the stable state restarts the timer on every pass while the button is held. - Using
intfor time. Useunsigned longformillis()values and for the interval. - Wrong starting values. With
INPUT_PULLUP, the idle level isHIGH, so initializelastReadingandstableStatetoHIGH. If you start them atLOW, the sketch sees a "press" at boot, and the LED may toggle by itself. - Blocking code elsewhere in
loop(). A longdelay()anywhere in the sketch makes the debounce timer check run rarely. Presses shorter than the delay may be missed entirely.
A reusable function
When you have more than one button, wrapping the logic keeps the code short. This version tracks one button per structure and reports a press when it is accepted.
struct Button {
uint8_t pin;
int lastReading;
int stableState;
unsigned long lastChangeTime;
};
const unsigned long debounceMs = 25;
Button buttons[] = {
{2, HIGH, HIGH, 0},
{3, HIGH, HIGH, 0}
};
const int buttonCount = sizeof(buttons) / sizeof(buttons[0]);
bool wasPressed(Button &b) {
int reading = digitalRead(b.pin);
if (reading != b.lastReading) {
b.lastChangeTime = millis();
b.lastReading = reading;
}
if ((millis() - b.lastChangeTime) >= debounceMs && reading != b.stableState) {
b.stableState = reading;
return b.stableState == LOW;
}
return false;
}
void setup() {
Serial.begin(9600);
for (int i = 0; i < buttonCount; i++) {
pinMode(buttons[i].pin, INPUT_PULLUP);
}
}
void loop() {
for (int i = 0; i < buttonCount; i++) {
if (wasPressed(buttons[i])) {
Serial.print("Button on pin ");
Serial.print(buttons[i].pin);
Serial.println(" pressed");
}
}
}wasPressed returns true for exactly one call per press: the call in which the stable state changes to LOW. This is the event-style behavior that the next chapter builds on, where you act on a press instead of a held level.
Limits of this approach
- Latency. The press is reported one debounce interval after the contact first closes. At 25 ms this is rarely noticeable, but it matters for fast reaction tests.
- Polling dependence. The pin must be read often. If
loop()takes longer than the interval, the filter still works but the effective resolution gets coarser. - Noise versus bounce. This filter handles mechanical bounce. Electrical noise on long wires or near motors may need shielding, shorter leads, or a hardware filter such as a small capacitor across the switch.
Exercise
In the debounce sketch, a student changes the first check to if (reading != stableState) { lastChangeTime = millis(); } and leaves the rest as is. Describe what happens when the button is pressed and held, and explain why.
Show answer
After the press, reading is LOW while stableState is still HIGH, so the first check is true on every pass and lastChangeTime is reset each time. The elapsed time millis() - lastChangeTime never reaches 25 ms, so stableState never changes and the LED never toggles. The first check must compare reading with lastReading, which is updated after a change, so the timer can age while the reading stays steady.
Exercise
Your sketch uses a 25 ms debounce and a button that bounces for up to 8 ms. A press closes the contact at t = 2000 ms, and the last bounce transition happens at t = 2008 ms. At what time does the sketch accept the press, and what is the shortest quiet period it requires?
Show answer
The timer restarts at the last change, t = 2008 ms, so the press is accepted once 25 ms have passed, at about t = 2033 ms. The sketch requires at least 25 ms of unchanged readings, which is the debounce interval.