PiPHP / GPIO

A PHP library for accessing the GPIO pins on a Raspberry Pi.
MIT License
425 stars 43 forks source link

Debouncing interrupts #5

Open colinodell opened 8 years ago

colinodell commented 8 years ago

Do you think there's a need for the InterruptWatcher to have debouncing logic built-in? For example, when I run the code in the README example and toggle the connection between the GPIO pin and ground, I get the following result:

Pin 4 changed to: 1
Pin 4 changed to: 0
Pin 4 changed to: 1
Pin 4 changed to: 0
Pin 4 changed to: 1
Pin 4 changed to: 1
Pin 4 changed to: 0
Pin 4 changed to: 0
Pin 4 changed to: 1
Pin 4 changed to: 1
Pin 4 changed to: 0
Pin 4 changed to: 1
Pin 4 changed to: 0
Pin 4 changed to: 1
Pin 4 changed to: 0
Pin 4 changed to: 1
Pin 4 changed to: 0
Pin 4 changed to: 0
Pin 4 changed to: 0
Pin 4 changed to: 0
Pin 4 changed to: 0
Pin 4 changed to: 0
Pin 4 changed to: 0
Pin 4 changed to: 0
Pin 4 changed to: 0
Pin 4 changed to: 0
Pin 4 changed to: 0
Pin 4 changed to: 0
Pin 4 changed to: 1

Note how sometimes the interrupt callback is fired but the value doesn't appear to have changed. This happens because the value rapidly switches (or "bounces") due to noise or mechanical/physical imperfections with the button/connection.

A common approach to "debouncing" is timing the duration between the current interrupt and the previous one. If it's faster than, say, 100ms then the toggle probably wasn't intentional and should be ignored. Here's an example: https://raspberrypi.stackexchange.com/questions/8544/gpio-interrupt-debounce

As a developer I could implement this myself on top of your library, but it would be much easier if that functionality was baked in.

AndrewCarterUK commented 8 years ago

How about as an optional parameter when registering the interrupt?

$interruptWatcher->register($pin, $callback);
// or...
$interruptWatcher->register($pin, $callback, $delay);

If the parameter isn't set then no bouncing protection, otherwise it represents a time in milliseconds that must occur between invoking callbacks?

colinodell commented 8 years ago

Yeah that would be great!

allebb commented 6 years ago

I'm experiencing the same issue as @colinodell at the moment.

Having baked in support to prevent bouncing would be fantastic... at the moment on my RPi3 it rarely registers the button "release".

Any idea when this may be released?

AndrewCarterUK commented 6 years ago

Hi @allebb - I haven't got a setup for this at the moment and I'm quite busy with my paid work. I've not been doing PHP for a while and haven't got any of my electronics equipment set up in my new residence.

If anyone reading is capable with some available spare time I'd welcome a PR for this

fcrossen commented 3 years ago

@allebb / @colinodell https://github.com/PiPHP/GPIO/pull/25