Filter switch bounce with clean state transitions.
Open in compiler →/*
Roboda verified Arduino sample 0519
Feature: Button Debounce
Generated for online build, classroom practice, and hardware upload testing.
*/
const byte buttonPin = 2;
const byte ledPin = 13;
bool stableState = HIGH;
bool lastReading = HIGH;
unsigned long lastChange = 0;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}
void loop() {
bool reading = digitalRead(buttonPin);
if (reading != lastReading) {
lastChange = millis();
lastReading = reading;
}
if (millis() - lastChange > 40) {
stableState = reading;
}
digitalWrite(ledPin, stableState == LOW ? HIGH : LOW);
}
How it works
Practice this Arduino feature with a verified Roboda sketch.
- Read the constants at the top of the sketch.
- Wire the pins exactly as listed in the pin map.
- Upload or compile once before changing values.
- Change one value at a time and watch Serial Monitor or the output device.
Connections
| Pin | Connect to | Note |
|---|---|---|
| D2 | Button to GND | Pressed reads LOW. |
| D13 | Built-in LED | Shows the debounced button state. |