i hope to get some help with my code.
I am trying to distinguish between a single press and a quick double press of the button with debouncing.
I am making some silly mistake in my code and i can't find out the problem. If I double press the button, both 'single' and 'double' gets printed on the serial monitor.
Thanks in advance for some help.
const int buttonPin = 5;
unsigned long lastPressTime;
int buttonState = 0;
int singlePress = 0;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
lastPressTime = millis();
Serial.begin(9600);
}
void loop() {
if (!digitalRead(buttonPin) == HIGH && buttonState == 0) {
unsigned long currentPressTime = millis();
//two presses within 500ms
if (currentPressTime - lastPressTime < 500) {
singlePress = 0;
//Do double press action
Serial.println("double");
} else {
singlePress = 1;
}
//update the last pressed time
lastPressTime = currentPressTime;
buttonState = 1;
} else if (!digitalRead(buttonPin) == LOW) {
buttonState = 0;
}
//check if 500ms have passed with no second button press
if (singlePress == 1 && lastPressTime - millis() > 500) {
singlePress = 0;
//DO single press stuff
Serial.println("single");
}
}
both 'single' and 'double' gets printed on the serial monitor.... you are almost there ... add code to pick one, then print