Try Embedded

Pushbutton toggle with debouncing

Each press of a button toggles an LED, with software debouncing so one press counts once.

Input · Beginner

In a real product: Smart switch (Smart home): Each debounced press toggles the light once.

Mechanical buttons don't switch cleanly: the contacts bounce for a millisecond or so, which the board can read as many presses. This project toggles an LED once per press by debouncing: it waits until the button has held still.

What you'll learn

  • Reading a button with the internal pull-up resistor
  • What contact bounce is and how to filter it with millis()
  • Acting on the change of a signal (a press), not its level

How it works

One side of the button goes to pin 2, the other to GND. INPUT_PULLUP holds pin 2 HIGH until the button connects it to GND, so LOW means pressed.

Every time the reading changes, the code notes the time. Only when the reading has stayed the same for 30 ms does it accept it as the new stable state. When the stable state goes from HIGH to LOW (a fresh press), the LED toggles.

The simulator bounces the contacts like a real button (10 to 30 flips in about a millisecond). Try setting the delay to 0 and see presses get counted twice.

Try this

  • Count the presses and print the count to the Serial Monitor.
  • Detect a long press (held over a second) and do something different.
  • Set the button's bounce to off and remove the debouncing to compare.

sketch.ino

// Each press of the button on pin 2 toggles the LED on pin 12. Debounced: a change counts after 30 ms of quiet.
const int BUTTON = 2;
const int LED = 12;
const unsigned long DEBOUNCE_MS = 30;

bool ledOn = false;
int lastReading = HIGH;
int stableState = HIGH;
unsigned long changedAt = 0;

void setup() {
  pinMode(BUTTON, INPUT_PULLUP);
  pinMode(LED, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int reading = digitalRead(BUTTON);
  if (reading != lastReading) {
    changedAt = millis();
    lastReading = reading;
  }
  if (millis() - changedAt > DEBOUNCE_MS && reading != stableState) {
    stableState = reading;
    if (stableState == LOW) {  // a new press
      ledOn = !ledOn;
      digitalWrite(LED, ledOn);
      Serial.println(ledOn ? "LED on" : "LED off");
    }
  }
}

Lessons behind it