JChristensen / JC_Button

Arduino library to debounce button switches, detect presses, releases, and long presses
GNU General Public License v3.0
425 stars 102 forks source link

Not immune to noise :( #33

Closed guillaume-dorczynski closed 4 days ago

guillaume-dorczynski commented 1 year ago

Hello Jack

I've been using and recommending this library for years, but recently had a problem with buttons in a project using this library, and after investigating I found that the problem lies in your debounce code.

The problem is that button press/release changes are detected immediately, your code only prevents multiple changes during the debounce time. Therefore, it's not immune to noise!

To be clear, I always thought the button press/release was detected after the debounce time, not before, to wait for the button state to be stabilized.

Here is a Wokwi demo with the debounce time set to one second : https://wokwi.com/projects/353568497230783489

JChristensen commented 1 year ago

Greetings,

That's a good catch, thanks. When you discovered the issue, were you using a long debounce time, or was it a noisy environment? Were you able to address the problem, if so, how?

Jack

Xylopyrographer commented 1 year ago

Hello @JChristensen, @guillaume-dorczynski

Found the same issue due to a noisy switch and when using long(er) debounce times.

Jack, respecting your contributing policy, below are modified .h and .cpp files with changes to the read() function that fixes the issue. Probably not as elegant as your coding style though 😉.

All the best.

Edit: revise the .cpp file.

src.zip

JChristensen commented 4 days ago

Hello @guillaume-dorczynski, @Xylopyrographer:

It took longer than I would have liked to get back to this, but so it goes. I rewrote the read() function using a state machine construct; I usually find these easier to follow. I have tested the example sketches in the library, a couple of my own projects, and also a breadboard setup arranged to inject simulated noise. If y'all are still out there ;-) and are so inclined, additional testing is greatly appreciated. Thanks again for the input and for finding the issue!

Best regards ... jc