How Do I Debounce a Button?

Buttons bounce. One press can look like several quick presses. Debouncing filters that noise.

Simple software debounce

debounce.ino
cpp
const int buttonPin = 2;
int lastState = LOW;
unsigned long lastChange = 0;
const unsigned long debounceMs = 50;

void loop() {
  int reading = digitalRead(buttonPin);
  if (reading != lastState) {
    lastChange = millis();
  }
  if (millis() - lastChange > debounceMs) {
    // stable state, use reading
  }
  lastState = reading;
}

Hardware option

Add a 10k pull-up or pull-down and a small capacitor. That smooths the signal before it reaches the pin.

Bottom line

Use a short debounce delay and millis timing to ignore button chatter.

Related: Why should I avoid delay()? · How do I make a timer? · How do I do multiple things at once?