Button Debounce Handling in Arduino

 avatar
subratasarkar20
c_cpp
14 days ago
1.6 kB
3
Indexable
Never
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

bool buttonState;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);  // set button pin as input with internal pull-up resistor
  Serial.begin(9600);
}

void loop() {
  bool reading = digitalRead(buttonPin);  // read the current state of the button

  switch (buttonState) {
    case HIGH: 

      if (reading != lastButtonState) {  // check if the button state has changed (from HIGH to LOW or LOW to HIGH)
        lastDebounceTime = millis();     // reset the debounce timer
        Serial.println("HELLO");
      }
      break;

    case LOW:
      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
          }
        }
      }
      break;
  }

  lastButtonState = reading;  // save the current state as the last state, for the next loop
}
Leave a Comment