Debouncing Button Input with Timers in Arduino
subratasarkar20
c_cpp
a year ago
1.8 kB
19
Indexable
const int buttonPin = 8;
unsigned long debounceDelay = 50; // debounce delay
unsigned long startTime = 0; // variable to store time
bool lastButtonState = HIGH; // variable to store the previous button state
bool currentButtonState = HIGH; // variable to store the current button state
// assign two timer to keep track of the time make keep them both in OFF state
bool timer1 = false;
bool timer2 = false;
void setup() {
pinMode(buttonPin, INPUT_PULLUP); //assign button pin to PULL UP resistor
Serial.begin(9600);
}
void loop() {
float buttonState = digitalRead(buttonPin); //read the button state
if (buttonState != lastButtonState) { // compare with last button state if it has changed
startTime = millis(); // store the time when the button state has been changed
timer1 = true; // turn ON timer 1
}
if (timer1 == true) { // if timer 1 is ON
if (millis() - startTime > debounceDelay) { // check if the debounce time has been passed
timer2 = true; // turn ON timer 2 after the debounce time
}
}
if (timer2 == true && buttonState != currentButtonState) { // check if time 2 is ON and button state is LOW
currentButtonState = buttonState; // update current button state
if (currentButtonState == LOW) { // check if the button state is still LOW
Serial.println("BUTTON PRESSED"); // take action accordingly
} else {
Serial.println("BUTTON NOT PRESSED"); // take action accordingly
}
}
lastButtonState = buttonState; // update the last button state
}
Editor is loading...
Leave a Comment