In this article we are going to continue with another tutorial of introduction to Raspberry PI. In this case we are going to prepare a project for Raspberry PI Zero W using a Java library called pi4j.
We know that we can control the GPIO of the Raspberry PI with C and Python. Precisely pi4j was born from the native bookshop wiringPi, which is a popular library written in C.
Installation of PI4J
To install this library we will open an ssh against the Raspberry PI and in the console we will introduce:
curl -s get.pi4j.com | sudo bash
This command will download and execute a script that will install the pi4j library in the / opt / pi4j directory
To verify that the installation is correct, we will try one of the examples, a simple assembly with an LED and a resistance, for this we place ourselves in the directory / opt / pi4j / examples and execute ./build ControlGpioExample.java so that it compiles one of the examples that come by default.
To execute it we will introduce ./run ControlGpioExample and we will see how the LED illuminates going through different states. First turn on for 5 seconds, then off for 5 seconds, then on for 5 more seconds, then off for 5 seconds and then on for 1 second, and finally the program is finished.
For this example you have to have an LED, a resistor, a breadboard, the cables and a Raspberry PI. The pin 1 is used, which translated into the visual format of the pins is pin number 6 (counting from the top left). Also use the ground pin, which corresponds to pin number 3 (counting from the top left).
You can see the assembly in the following photo:
Since the cables have a black connector, it seems that the cables are connected to the lower pins, but it is only an optical effect. They are really connected in the pins of the top row.
To create an example in java, we create the Test.java file and import the classes:
Then in the main method we create an instance of the gpio driver.
final GpioController gpio = GpioFactory.getInstance();
Then before using a pin we have to provision it and specify if it is input or output.
GpioPinDigitalOutput myLed = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_04, "Mi LED", PinState.LOW);
In this way we provision the pin 4, we give it a label, and we initialize it to the LOW state.
At the end of the main method, we can release the resources of the gpio interface with:
In these links you can buy the best books about Raspberry projects.