typestar

Debounce in Arduino

A press counts once the contacts stop bouncing.

// A press only counts once the contacts stop bouncing.
const int BUTTON_PIN = 2;
const unsigned long SETTLE_MS = 25;
int steadyState = HIGH;
int lastReading = HIGH;
unsigned long lastChange = 0;
void setup() {
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop() {
  int reading = digitalRead(BUTTON_PIN);
  if (reading != lastReading) lastChange = millis();
  if (millis() - lastChange > SETTLE_MS && reading != steadyState) {
    steadyState = reading;
    if (steadyState == LOW) Serial.println("Pressed");
  }
  lastReading = reading;
}

How it works

  1. Every raw change restamps lastChange.
  2. Only a reading stable past SETTLE_MS becomes the steady state.
  3. The print fires on the clean falling edge alone.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
540
Tokens
119
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 119 seconds.

Type this snippet

Step 3 of 3 in Timing, step 12 of 27 in Language basics.

← Previous Next →

Debounce in other languages