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
- Every raw change restamps
lastChange. - Only a reading stable past
SETTLE_MSbecomes the steady state. - The print fires on the clean falling edge alone.
Keywords and builtins used here
HIGHINPUT_PULLUPLOWSerialbeginconstdigitalReadifintlongloopmillispinModeprintlnsetupunsignedvoid
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.
Step 3 of 3 in Timing, step 12 of 27 in Language basics.