All courses

Arduino C++ · Lesson 27 of 40

Debounce buttons and detect events

Responsive Timing and State Machines

A press is an event; a pin level is a state

Uno internal pull-up5VD2 inputButton to GNDReleased → HIGHPressed → LOW
INPUT_PULLUP sets the idle level. The external button pulls the pin to ground when closed; debounce is still needed.

Wire a normally open pushbutton between D2 and GND, using INPUT_PULLUP. The idle reading is HIGH and the pressed reading is LOW. On four-leg tactile switches, pairs of legs are already joined internally; identify the switched pair with a continuity check while unpowered.

Contacts can bounce, producing several rapid transitions from one press. First wait for a stable level, then detect the transition into LOW. Incrementing a counter on every loop while LOW counts a long hold many times.

Toggle once per stable press

Arduino C++
const byte buttonPin = 2;
const unsigned long debounceMs = 30;
bool lastRaw = HIGH;
bool stable = HIGH;
bool ledOn = false;
unsigned long changedAt = 0;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  const unsigned long now = millis();
  const bool raw = digitalRead(buttonPin);
  if (raw != lastRaw) {
    changedAt = now;
    lastRaw = raw;
  }
  if (now - changedAt >= debounceMs && raw != stable) {
    stable = raw;
    if (stable == LOW) {
      ledOn = !ledOn;
      digitalWrite(LED_BUILTIN, ledOn);
    }
  }
}

Every raw transition restarts the stability timer. Only a new stable value becomes an event. There is no delay, so other short tasks can run in the same loop. The 30 ms interval is an example, not a universal switch specification.

Acceptance checks: A tap toggles once. A two-second hold also toggles once. Release does not toggle. Ten deliberate presses produce ten toggles. If it never changes, check the button orientation; if idle reads LOW, inspect wiring to ground.

Extension: Record the time of the debounced press and subtract it at release to distinguish a short click from a long hold. Decide whether a long hold should suppress the short-click action.

Official references for further study

A useful reminder

Clean Code: Use descriptive constants instead of magic numbers

Instead of calling digitalWrite(13, HIGH) directly in your code, define descriptive constants like const int LED_PIN = 13; at the top of your file. This makes your code self-documenting and extremely easy to update if you change your wiring.