Home Tutorials Basic Java GPIO example on your Raspberry PI

Basic Java GPIO example on your Raspberry PI

by shedboy71

The first step is to verify if you have java installed , to do this open a command prompt and type the following

java -version

This should return something like the following, if not you’ve probably got an older version of Raspbian or equivalent that didn’t contain Java. We’ll get to that in a later tip/tutorial.

java version

java version

Now we will install pi4j, still on the command line type in the following

[codesyntax lang=”bash”]

curl -s get.pi4j.com | sudo bash

[/codesyntax]

This goes through a whole sequence of actions such as downloading and installing the package, after a period of time this will complete and your ready to go.

Now typically the easiest way to test a GPIO library is to connect an LED and suitable resistor to one of the GPIO pins and flash the led on and off, the ‘Hello World’ type of example

Here is the schematic, as you can see we connect a resistor to pin 11, which is also known as GPIO 17 but in the land of pi4j this is called GPIO 0. Confused yet

pi and led

pi and led

 
Code :

This is mostly based on one of the examples

 

[codesyntax lang=”java”]

import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.RaspiPin;
import com.pi4j.io.gpio.GpioController;


public class ledflash{

public static void main(String[] args) throws InterruptedException {

System.out.println("GPIO Control Example");

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

// gpio pin #00 as an output pin and turn on
final GpioPinDigitalOutput pin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_00, "MyLED", PinState.HIGH);

// set shutdown state for this pin
pin.setShutdownOptions(true, PinState.LOW);

System.out.println("LED ON");
Thread.sleep(2000);

// turn off gpio pin #01
pin.low();
System.out.println("LED OFF");
Thread.sleep(2000);

pin.high();
System.out.println("LED ON");
Thread.sleep(2000);

pin.low();
System.out.println("LED OFF");
Thread.sleep(2000);

// stop all GPIO activity/threads by shutting down the GPIO controller
gpio.shutdown();
}
}

[/codesyntax]

 

Save your code above as ledflash.java in the examples folder – /opt/pi4j/examples

Compile
Next, use the following command to compile this example program:
[codesyntax lang=”bash”]

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

[/codesyntax]

Execute
The following command will run this example program:

[codesyntax lang=”bash”]
sudo java -classpath .:classes:/opt/pi4j/lib/’*’ ledflash

[/codesyntax]

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More