Why does my button or switch bounce and how do I fix it?



Short Answer: Mechanical switches don't close cleanly — they "bounce" open/closed for 1–20 ms, causing multiple false triggers.

Detailed: When you press a switch, the metal contacts literally bounce like a dropped spring. A microcontroller reading the pin might see:

text
    Press:   HIGH ──┐┌─┐┌─┐┌──────────
                    ││ ││ │
    Actual:  LOW  ──┘└─┘└─┘└──────────
                    ↑ bounce (1-10ms)

Fixes (from easiest to most robust):

MethodHowGood for
Software debounceRead pin, wait 10ms, read againMost microcontrollers (Arduino, ESP32)
RC filter + Schmitt trigger10kฮฉ + 1ยตF to groundSimple, no code
Hardware debounce IC (MAX6816)Dedicated chipMultiple switches, professional
Schmitt trigger gate (74HC14)Clean edgesWhen software isn't an option

Arduino code example:

cpp
const int buttonPin = 2;
int lastState = LOW;
unsigned long lastDebounce = 0;

void loop() {
  int reading = digitalRead(buttonPin);
  if (reading != lastState) {
    lastDebounce = millis();
  }
  if ((millis() - lastDebounce) > 10) {
    // Button is stable — act on it
  }
  lastState = reading;
}

Rule of thumb: 10–50 ms debounce is enough for most buttons. Use 5 ms for tact switches, 20 ms for large toggle switches.

Comments