Fork me on GitHub

GPIO State Listener Example using Pi4J.

The following example demonstrates how to setup a listener for GPIO pin state changes on the Raspberry Pi. This listener implementation is far more efficient than constantly polling and querying for the the GPIO pin state. The listener implementation is based on GPIO hardware interrupts not state polling.

Source Code

The source code for this example is included in the github repository:
https://github.com/Pi4J/pi4j-v1/tree/master/pi4j-example/src/main/java/ListenGpioExample.java

  1.  
  2. /*
  3. * #%L
  4. * **********************************************************************
  5. * ORGANIZATION : Pi4J
  6. * PROJECT : Pi4J :: Java Examples
  7. * FILENAME : ListenGpioExample.java
  8. *
  9. * This file is part of the Pi4J project. More information about
  10. * this project can be found here: https://pi4j.com/
  11. * **********************************************************************
  12. * %%
  13. * Copyright (C) 2012 - 2021 Pi4J
  14. * %%
  15. * Licensed under the Apache License, Version 2.0 (the "License");
  16. * you may not use this file except in compliance with the License.
  17. * You may obtain a copy of the License at
  18. *
  19. * http://www.apache.org/licenses/LICENSE-2.0
  20. *
  21. * Unless required by applicable law or agreed to in writing, software
  22. * distributed under the License is distributed on an "AS IS" BASIS,
  23. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24. * See the License for the specific language governing permissions and
  25. * limitations under the License.
  26. * #L%
  27. */
  28.  
  29. import com.pi4j.io.gpio.*;
  30. import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent;
  31. import com.pi4j.io.gpio.event.GpioPinListenerDigital;
  32.  
  33. /**
  34. * This example code demonstrates how to setup a listener
  35. * for GPIO pin state changes on the Raspberry Pi.
  36. *
  37. * @author Robert Savage
  38. */
  39. public class ListenGpioExample {
  40.  
  41. public static void main(String args[]) throws InterruptedException {
  42. System.out.println("<--Pi4J--> GPIO Listen Example ... started.");
  43.  
  44. // create gpio controller
  45. final GpioController gpio = GpioFactory.getInstance();
  46.  
  47. // provision gpio pin #02 as an input pin with its internal pull down resistor enabled
  48. final GpioPinDigitalInput myButton = gpio.provisionDigitalInputPin(RaspiPin.GPIO_02, PinPullResistance.PULL_DOWN);
  49.  
  50. // set shutdown state for this input pin
  51. myButton.setShutdownOptions(true);
  52.  
  53. // create and register gpio pin listener
  54. myButton.addListener(new GpioPinListenerDigital() {
  55. @Override
  56. public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
  57. // display pin state on console
  58. System.out.println(" --> GPIO PIN STATE CHANGE: " + event.getPin() + " = " + event.getState());
  59. }
  60.  
  61. });
  62.  
  63. System.out.println(" ... complete the GPIO #02 circuit and see the listener feedback here in the console.");
  64.  
  65. // keep program running until user aborts (CTRL-C)
  66. while(true) {
  67. Thread.sleep(500);
  68. }
  69.  
  70. // stop all GPIO activity/threads by shutting down the GPIO controller
  71. // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks)
  72. // gpio.shutdown(); <--- implement this method call if you wish to terminate the Pi4J GPIO controller
  73. }
  74. }
  75.  

JavaDoc

The following JavaDoc links are the primary interfaces used to listen for GPIO state changes:

Wiring Diagram

The following circuit can be used in conjunction with this sample code.

(click here for hi-resolution image)

Navigate

If you have not already downloaded and installed the Pi4J library on the RaspberryPi, then view this page for instructions on where to download and how to install Pi4J:
Download & Install Pi4J

First, locate the ListenGpioExample.java source file in the samples folder of the Pi4J installation on the RaspberryPi.
You can use the following command on the Pi's console or SSH terminal to navigate to this path:
cd /opt/pi4j/examples

Compile

Next, use the following command to compile this example program:

javac -classpath .:classes:/opt/pi4j/lib/'*' -d . ListenGpioExample.java

Execute

The following command will run this example program:

sudo java -classpath .:classes:/opt/pi4j/lib/'*' ListenGpioExample

Output

You should see the following message on the console each time the momentary button is pressed:

--> GPIO PIN STATE CHANGE: 4 = HIGH

and this message on the console each time the momentary button is released:

--> GPIO PIN STATE CHANGE: 4 = LOW