Button Debouncing in Arduino
const int buttonPin = 8; const int debounceInterval = 30; // debounce time in milliseconds unsigned long lastDebounceTime = 0; // variable to store the last time the button state changed bool currentButtonState = HIGH; // variable to store the current button state bool lastButtonState = HIGH; // variable to store the last button state void setup() { pinMode(buttonPin, INPUT_PULLUP); // set button pin as input with internal pull-up resistor Serial.begin(9600); } void loop() { float reading = digitalRead(buttonPin); // read the current state of the button if (reading != lastButtonState) { // check if the button state has changed (from HIGH to LOW or LOW to HIGH) lastDebounceTime = millis(); // reset the debounce timer } if ((millis() - lastDebounceTime) > debounceInterval) { // check if the debounce delay has been passed if (reading != currentButtonState) { // update the button state currentButtonState = reading; if (currentButtonState == LOW) { // check if the button is pressed (LOW state) Serial.println("BUTTON IS PRESSED"); // take action accordingly } else { Serial.println("BUTTON NOT PRESSED"); // take action accordingly } } } lastButtonState = reading; // save the current state as the last state, for the next loop }
Leave a Comment