Search code examples
javaraspberry-pilistenerinfinite-looppolling

How to avoid to use polling with raspberry?


I am doing a project with Raspberry in Java and I use the Pi4j library. I don't wont use polling, so for example I use this code :

public class ListenGpioExample {

  public static void main(String args[]) throws InterruptedException {
    System.out.println("<--Pi4J--> GPIO Listen Example ... started.");

    // create gpio controller
    final GpioController gpio = GpioFactory.getInstance();

    // provision gpio pin #02 as an input pin with its internal pull down resistor enabled
    final GpioPinDigitalInput myButton = gpio.provisionDigitalInputPin(RaspiPin.GPIO_02, PinPullResistance.PULL_DOWN);

    // create and register gpio pin listener
    myButton.addListener(new GpioPinListenerDigital() {
        @Override
        public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
            // display pin state on console
            System.out.println(" --> GPIO PIN STATE CHANGE: " + event.getPin() + " = " + event.getState());
        }

    });

    System.out.println(" ... complete the GPIO #02 circuit and see the listener feedback here in the console.");

    // keep program running until user aborts (CTRL-C)
    for (;;) {
        Thread.sleep(500);
    }

    // stop all GPIO activity/threads by shutting down the GPIO controller
    // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks)
    // gpio.shutdown();   <--- implement this method call if you wish to terminate the Pi4J GPIO controller        
}}

My question is : the fact that there is the infinite loop is still a form of polling ?

Because I don't understand if the infinite loop is necessary or not.


Solution

  • No, this is not polling. This example uses an event listener, which will fire up once an state change occurs in the GPIO Pin

    As you can read on the Pi4J library page:

    The listener implementation is based on GPIO hardware interrupts not state polling.

    The for(;;) is intended for keeping the program alive until the users stops it (as you can read in the comment)