I'm trying to detect independently short and long presses of a button with debounce and not using a library. Long press is detected while button held, not on release. I've simulated the following code in Wokwi and sometimes get a short indication after a long indication. Is there a simpler or more efficient way of doing this?
void setup() {
Serial.begin(9600);
pinMode(2, INPUT_PULLUP); // button to gnd
}
void loop() {
// button hold with debounce
static unsigned long holdTime;
static bool press, hold;
if ( digitalRead(2) == LOW && press == false) {
// one time on button press - on bounce first low
holdTime = millis();
press = true;
}
// only after bounce period check for button release
if (millis() - holdTime > 300) {
if (digitalRead(2) == HIGH && press == true && hold == false) {
holdTime = millis();
press = false;
Serial.println("Short");
}
}
// if button remains held for period
if (millis() - holdTime > 1000) {
if (digitalRead(2) == LOW && press == true && hold == false) {
press = false;
hold = true;
holdTime = millis();
Serial.println("Long");
}
// inhibit retrigger
if (digitalRead(2) == HIGH && hold == true && millis() - holdTime > 1000) {
press = false;
hold = false;
}
}
}
Is your middle name Stefan.
I share knowledge so that the TO becomes curious to learn new things.
That's the purpose of this forum.
And if you don't like it, just ignore my well-intentioned programme examples!