javaraspberry-pievent-listenergpiopi4j

Pi4j Event Listener not triggered by GPIO status change


I have a simple Java program which should listen for changes of GPIO status.
I'm using a button to change the status of a GPIO and from terminal I can see it works: enter image description here


Despite this, the event listener is never triggered. Here is the code:

public class GpioHandler
{
    private static final GpioController gpioController = GpioFactory.getInstance();
    public static ButtonsHandler buttons;

    public GpioHandler()
    {
        buttons = new ButtonsHandler(gpioController, RaspiPin.GPIO_05);
        buttons.listener();
    }
}
public class ButtonsHandler
{
    private static HashMap<String, GpioPinDigitalOutput> buttons = new HashMap<String, GpioPinDigitalOutput>();

    public ButtonsHandler(GpioController gpioController, Pin... pins)
    {
        for(int c = 0; c < pins.length; c++)
        {
            Integer index = c + 1;
            buttons.put(index.toString(), gpioController.provisionDigitalOutputPin(pins[c]));
        }
    }

    public void listener()
    {
        for(HashMap.Entry<String, GpioPinDigitalOutput> pin : buttons.entrySet())
        {
            pin.getValue().addListener(new GpioPinListenerDigital() {
                @Override
                public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event)
                {
                    System.out.println(" --> GPIO PIN STATE CHANGE: " + pin.getKey() + " = " + event.getState());
                }
            });
        }
    }
}

I'm using a RaspberryPi 4 and the last version of Pi4j (1.2).
Any suggestion?


Solution

  • Okay, apparently it was just me being stupid.
    The mistake is that I was using the class GpioPinDigitalOutput instead of GpioPinDigitalInput. I changed it and also modified this line

    buttons.put(index.toString(), gpioController.provisionDigitalOutputPin(pins[c]));
    

    into

    buttons.put(index.toString(), gpioController.provisionDigitalInputPin(pins[c], PinPullResistance.PULL_DOWN));
    

    to prevent the value from floating.
    Now everything works just fine.