const int LED_PIN = 8;
const int BTN_PIN = 12;
uint32_t DEBOUNCE_TIME = 20;
void setup() {
Serial.begin(9600);
pinMode(LED_PIN, OUTPUT);
pinMode(BTN_PIN, INPUT_PULLUP);
}
void loop() {
static uint32_t lastTime = 0;
static bool lastState = HIGH;
bool currentState = digitalRead(BTN_PIN);
uint32_t now = millis();
if (currentState != lastState && now - lastTime >= DEBOUNCE_TIME) {
if (!currentState) {
Serial.println("Button pressed!");
digitalWrite(LED_PIN, !digitalRead(LED_PIN));
} else {
Serial.println("Button released!");
}
lastTime = now;
lastState = currentState;
}
}
/*
// Arduino | bot
// Taming Bouncy Buttons: Understanding Debouncing
// Previous button state
bool lastButtonState = HIGH;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50; // 50ms
// In your loop():
bool reading = digitalRead(buttonPin);
if (reading != lastButtonState) {
lastDebounceTime = millis(); // Reset debounce timer
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// If current reading has been stable for longer than the delay
if (reading == LOW) { // Assuming button pulls LOW when pressed
// Button is considered pressed
// Your action here (e.g., toggle LED, count press)
// Make sure to only act on state change (e.g. if it *was* HIGH and *is now* LOW)
}
}
lastButtonState = reading;
*/