#define LED_PIN 10
#define BUTTON_PIN 2
// Debounce parameters
const unsigned long DEBOUNCE_DELAY = 20; // 20 ms
uint8_t buttonState = LOW;
uint8_t lastButtonState = LOW;
unsigned long lastDebounceTime = 0;
void setup() {
pinMode(LED_PIN, OUTPUT); // LED output
pinMode(BUTTON_PIN, INPUT_PULLDOWN); // Button with internal pulldown
Serial.begin(115200); // Serial monitor
}
void loop() {
uint8_t reading = digitalRead(BUTTON_PIN);
// Check if button state changed
if (reading != lastButtonState) {
lastDebounceTime = millis(); // reset debounce timer
}
// Only update if stable for DEBOUNCE_DELAY
if ((millis() - lastDebounceTime) > DEBOUNCE_DELAY) {
if (reading != buttonState) {
buttonState = reading; // update stable button state
}
}
lastButtonState = reading;
digitalWrite(LED_PIN, buttonState); // Mirror button state to LED
Serial.println(buttonState); // Print 0 or 1
}