I got this working so that a short press toggles one LED on and off, and a long press toggles another LED on and off. However, when I short press once and then long press once, and both LEDs are on as expected, a long press sometimes toggles both LEDs off.
So, there is something wrong in my logic here. What mistake am I making?
Thanks! When I add serial printing, and I click as much as I can short and long for a minute, both LEDs are toggled without a single fault.
I don't understand why that single line of code seems to make a difference. I don't have an oscilloscope at hand, but other projects with that button and hardware debouncing work reliably.
long pressDuration = timeReleased - timePressed;
Serial.println(pressDuration); // The only thing I changed in loop()
You need a state machine.
Assume, you have 'debounced" the mechanical switches. They provide for a longer period if time an "uncertain" result.
You write a program as (hints):
wait X ms for short press: if it is still the same state of switch - at least a short button press happened
wait now Y ms (much longer): it this is also the same state of switch - it might have pressed longer
And short and long press are exclusive: if "long press" is realized, it cannot be a short press.
OK, here, the delay to distinguish between short and long is always the period for long (you cannot decide if it was short when not making sure it was not a long). Both will have a similar delay to realize (decide).
The "only problem": if you press the button twice, it was released after the short period - you get it as long pressed. It looks like a long press at the end.
I kept what I had and simply defined the minimum duration of what is a long press, and then tested for that. That provides a "dead band" of 200 milliseconds to differentiate between short and long presses. I might add another test for a "very long press", if I can find a use for that.