Menu
CoddyTech

Debounce a Button

Part of the Inputs section of Coddy's Arduino journey. Lesson 6 of 22.

This lesson's button is a real one, and the starter is your counter from the last lesson. Run it and press the button once: the count jumps by more than one.

Inside a button, two metal contacts touch. When they meet they bounce: for about a millisecond they hit, spring apart and hit again. Letting go does the same. loop() reads the pin many times in that millisecond and counts every bounce as a press.

The fix is called debouncing: when the reading changes, act on it once, then wait about 20 ms for the contacts to settle before reading again. A person never notices 20 ms.

if (reading != lastReading) {
  if (reading == LOW) {
    presses++;
    Serial.println(presses);
  }
  delay(20);
}
lastReading = reading;

Wait after every change, not only after a press: a release bounces too, and each bounce on the way up looks like a new press.

challenge icon

Challenge

Medium

Fix the counter so each press counts once:

  • when reading is different from lastReading, count it if it is a press (LOW), then wait 20 ms
  • keep saving lastReading at the end of loop()

Press Run, press the button a few times and watch the count, then Check.

Try it yourself

const int buttonPin = 2;

int presses = 0;
int lastReading = HIGH;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop() {
  int reading = digitalRead(buttonPin);
  if (reading == LOW && lastReading == HIGH) {
    presses++;
    Serial.println(presses);
  }
  lastReading = reading;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Inputs

Practice on your own: Arduino playground