Pi4J - Connecting Java to the Raspberry Pi
Announcing the Pi4J project!
This project is intended to provide a bridge between the native hardware and Java for full access to the Raspberry Pi in with a Java-friendly object-oriented approach. Pi4J is an open source project developed by professional software engineers. In addition to the basic raw hardware access functionality, this project also attempts to provide a set of advanced features that make working with the Raspberry Pi an easy to implement and more convenient experience for Java developers.
Project Website
Source Repository
Basic Features
- Export & unexport GPIO pins
- Configure GPIO pin direction
- Configure GPIO pin edge detection
- Control/write/set GPIO pin states
- Read GPIO pin states
- Send & receive data via RS232 serial communication
Advanced Features
- Pulse GPIO pin states
- Listen for GPIO pin state changes (interrupt-based events; not polling)
- Automatically set GPIO states on program termination (GPIO shutdown)
- Triggers for automation based on pin state changes
- Access system information and network information from the Raspberry Pi
- Wrapper classes for direct access to WiringPi Library from Java
To get started using the Pi4J library, please see the Usage page and review each of the examples below to explore the functionality provided by the Pi4j library.
- Control GPIO
- Listen for GPIO Events
- Shutdown GPIO
- Trigger GPIO on Events
- Serial Communication
- System/Network Information
Simple Usage Example
Below is a simple example demonstrating controlling a single GPIO pin state.
(Please visit this page for a more in-depth view of this example: Control GPIO Example)
public static void main(String[] args) throws InterruptedException { System.out.println("<--Pi4J--> GPIO Control Example ... started."); // create gpio controller Gpio gpio = GpioFactory.createInstance(); // provision gpio pin #01 as an output pin and turn on GpioPin pin = gpio.provisionOuputPin(Pin.GPIO_01, "MyLED",
PinState.HIGH); System.out.println("--> GPIO state should be: ON"); Thread.sleep(5000); // turn off gpio pin #01 pin.low(); System.out.println("--> GPIO state should be: OFF");Thread.sleep(5000); // toggle the current state of gpio pin #01 (should turn on) pin.toggle(); System.out.println("--> GPIO state should be: ON"); Thread.sleep(5000); // toggle the current state of gpio pin #01 (should turn off) pin.toggle(); System.out.println("--> GPIO state should be: OFF"); Thread.sleep(5000); // turn on gpio pin #01 for 1 second and then off System.out.println("--> GPIO state should be: ON for only 1 second"); pin.pulse(1000); }
Stay tuned ... more articles to come on using the Pi4J library.