Prasanna Anbazhagan
Prasanna Anbazhagan

Reputation: 1735

GPIO pin listener in PI using java cause a burst of action event

In this program I can able to read the GPIO pin. But pressing the hardware button(GPIO pin connected with button) for a single event cause a burst of state change and result in burst of action events.. So how can I eliminate the GPIO state change that happens concurrently for certain time period to eliminate this burst.

final GpioController gpio = GpioFactory.getInstance();
GpioPinDigitalInput myButton = null;
try {
    myButton = gpio.provisionDigitalInputPin(RaspiPin.GPIO_02,PinPullResistance.PULL_DOWN);
} catch(GpioPinExistsException e) {
}

try {
    myButton.addListener(new GpioPinListenerDigital() {
        @Override
        public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
            if(event.getState().toString().equalsIgnoreCase("HIGH") || event.getState().toString().equalsIgnoreCase("LOW")) {
                System.out.println("Pressed");
            }
        }
    });
} catch(NullPointerException e2) {
}

Upvotes: 4

Views: 1596

Answers (2)

yglodt
yglodt

Reputation: 14551

I just became aware that it's possible to set a debounce-duration on the GPIO:

myButton.setDebounce(1000); // 1000 ms

I will try this out and report my findings.

The full example with explanations is here:

https://github.com/Pi4J/pi4j/blob/master/pi4j-example/src/main/java/DebounceGpioExample.java

Edit

The debounce(1000) call itself seems to work. I get state changes no more often than the value in ms.

However my initial problem that as soon as I open the contact I get state changes from LOW to HIGH and vice-versa (bursts) all the time is not solved. They just occur only every 1000ms now.

Upvotes: 0

shazin
shazin

Reputation: 21903

Seems like the API is working as it is supposed to working, For example when you press a button current will start to flow to the read pin in return the pin will be keep on get an HIGH event until you release the button. What you must do is have a state and control the press and release.

try {
    myButton.addListener(new GpioPinListenerDigital() {

        private boolean pressed = false;
        private boolean released = false;

        @Override
        public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
                String state = event.getState().toString();
                if (state.equalsIgnoreCase("HIGH")) {
                       pressed = true;
                       released = !pressed;
                } else {
                       released = true;
                       pressed = !released;
                }

                // Do what you want with it.
            }
        });
    } catch(NullPointerException e2) {

    }

Upvotes: 1

Related Questions