javaraspberry-pigpiopi4j

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) {
}

Solution

  • 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) {
    
        }