Getting started with Pi4J for Raspberry Pi
This guide will help you get started with using Pi4J library to write Java/Kotlin code for Raspberry Pi
If you have some experience with Raspberry Pi, you know that Python is the most commonly used programming language for Raspberry Pi programming. However, when it comes to complex robotic projects, the need for a language with strong Object Oriented Programming support becomes more apparent. The weird syntax and the lack of types in python always makes me dislike it. That’s why I wanted to use Java or Kotlin for programming the Pi.
Pi4J is a Java library which provides an object oriented programming interface for Raspberry Pi. This library gives you the freedom to use Java or Kotlin for programming the Raspberry Pi.
Let’s see how you can get started with Pi4J:
Preparing your Raspberry Pi
Before getting started with programming, You’ll need to prepare your Raspberry Pi
- For this, you’ll need a Raspberry Pi that’s running Raspberry Pi OS.
- Then you need to change the Raspberry Pi configuration to enable I²C, Hardware Serial, One Wire and a few other things. For this you can use the
raspi-configterminal utility, or you can just use the following commands
sudo raspi-config nonint do_i2c 0
sudo raspi-config nonint do_ssh 0
sudo raspi-config nonint do_serial_hw 0
sudo raspi-config nonint do_serial_cons 1
sudo raspi-config nonint do_onewire 0
sudo systemctl disable hciuart
echo "dtoverlay=disable-bt" | sudo tee -a /boot/firmware/config.txt- Next you need to install Java and some other essential tools.
sudo apt install -y i2c-tools java-common libxi6 libxrender1 libxtst6- Use the following command to install Java 21 on your Raspberry Pi
wget https://cdn.azul.com/zulu/bin/zulu21.38.21-ca-jdk21.0.5-linux_arm64.deb
sudo dpkg -i zulu21.38.21-ca-jdk21.0.5-linux_arm64.debNow you are ready to get started with programming your Raspberry Pi
Writing your program
Writing your Java code can be done on a separate computer or inside the Raspberry Pi OS. I recommend you to use a separate computer for programming, as compiling a large Java/Kotlin code base will require a lot of resources, that a Raspberry Pi may not be able to provide.
For writing your program, I recommend you to use IntelliJ IDEA. Using that will simplify a lot of things.
First Open IDEA and create a new project. You can select either Java or Kotlin as your preferred language. I’m going to use Kotlin here as I prefer using Kotlin over Java. Make sure to use Maven as the build system.

Now it’s time to add the necessary plugins and dependencies to our project. Open pom.xml and add these lines under the plugins section. Make sure to replace the version numbers with the latest available versions.
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<version>3.14.0version>
<configuration>
<showDeprecation>trueshowDeprecation>
<showWarnings>trueshowWarnings>
<verbose>falseverbose>
configuration>
plugin>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-jar-pluginartifactId>
<version>3.4.2version>
<configuration>
<archive>
<manifest>
<mainClass>top.suhasdissa.MainKtmainClass>
manifest>
archive>
configuration>
plugin>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-shade-pluginartifactId>
<version>3.6.0version>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
transformers>
configuration>
<executions>
<execution>
<phase>packagephase>
<goals>
<goal>shadegoal>
goals>
execution>
executions>
plugin>
plugins>Then add these lines under the dependencies section. Make sure to replace the version numbers with the latest available versions.
<dependencies>
<dependency>
<groupId>com.pi4jgroupId>
<artifactId>pi4j-ktxartifactId>
<version>2.4.0version>
dependency>
<dependency>
<groupId>com.pi4jgroupId>
<artifactId>pi4j-plugin-raspberrypiartifactId>
<version>2.6.1version>
dependency>
<dependency>
<groupId>com.pi4jgroupId>
<artifactId>pi4j-plugin-pigpioartifactId>
<version>2.6.1version>
dependency>
<dependency>
<groupId>com.pi4jgroupId>
<artifactId>pi4j-ktxartifactId>
<version>2.4.0version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-simpleartifactId>
<version>2.0.13version>
dependency>
dependencies>Here’s an example pom.xml file
"1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>top.suhasdissagroupId>
<artifactId>MyFirstProjectartifactId>
<version>1.0version>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<kotlin.code.style>officialkotlin.code.style>
<kotlin.compiler.jvmTarget>1.8kotlin.compiler.jvmTarget>
properties>
<repositories>
<repository>
<id>mavenCentralid>
<url>https://repo1.maven.org/maven2/url>
repository>
repositories>
<build>
<sourceDirectory>src/main/kotlinsourceDirectory>
<testSourceDirectory>src/test/kotlintestSourceDirectory>
<finalName>robotfinalName>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlingroupId>
<artifactId>kotlin-maven-pluginartifactId>
<version>2.0.21version>
<executions>
<execution>
<id>compileid>
<phase>compilephase>
<goals>
<goal>compilegoal>
goals>
execution>
<execution>
<id>test-compileid>
<phase>test-compilephase>
<goals>
<goal>test-compilegoal>
goals>
execution>
executions>
plugin>
<plugin>
<artifactId>maven-surefire-pluginartifactId>
<version>2.22.2version>
plugin>
<plugin>
<artifactId>maven-failsafe-pluginartifactId>
<version>2.22.2version>
plugin>
<plugin>
<groupId>org.codehaus.mojogroupId>
<artifactId>exec-maven-pluginartifactId>
<version>1.6.0version>
<configuration>
<mainClass>MainKtmainClass>
configuration>
plugin>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<version>3.14.0version>
<configuration>
<showDeprecation>trueshowDeprecation>
<showWarnings>trueshowWarnings>
<verbose>falseverbose>
configuration>
plugin>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-jar-pluginartifactId>
<version>3.4.2version>
<configuration>
<archive>
<manifest>
<mainClass>top.suhasdissa.MainKtmainClass>
manifest>
archive>
configuration>
plugin>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-shade-pluginartifactId>
<version>3.6.0version>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
transformers>
configuration>
<executions>
<execution>
<phase>packagephase>
<goals>
<goal>shadegoal>
goals>
execution>
executions>
plugin>
plugins>
build>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlingroupId>
<artifactId>kotlin-test-junit5artifactId>
<version>2.0.21version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.junit.jupitergroupId>
<artifactId>junit-jupiterartifactId>
<version>5.10.0version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.jetbrains.kotlingroupId>
<artifactId>kotlin-stdlibartifactId>
<version>2.0.21version>
dependency>
<dependency>
<groupId>com.pi4jgroupId>
<artifactId>pi4j-coreartifactId>
<version>2.6.1version>
dependency>
<dependency>
<groupId>com.pi4jgroupId>
<artifactId>pi4j-ktxartifactId>
<version>2.4.0version>
dependency>
<dependency>
<groupId>com.pi4jgroupId>
<artifactId>pi4j-plugin-raspberrypiartifactId>
<version>2.6.1version>
dependency>
<dependency>
<groupId>com.pi4jgroupId>
<artifactId>pi4j-plugin-pigpioartifactId>
<version>2.6.1version>
dependency>
<dependency>
<groupId>com.pi4jgroupId>
<artifactId>pi4j-ktxartifactId>
<version>2.4.0version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-simpleartifactId>
<version>2.0.13version>
dependency>
dependencies>
project>Now let’s write a simple program to blink an LED
Let’s start by connecting an LED to our Raspberry Pi. Connect the LED cathode to GND pin and anode to pin 22.

Pi4J uses the BCM pin numbering scheme, which is different from the physical pin number. Use this diagram to get the BCM pin number for a given physical pin.

Let’s now write the code to blink an LED. Open the Main.kt and write the code like this
import com.pi4j.Pi4J
import com.pi4j.context.Context
import com.pi4j.io.gpio.digital.DigitalOutput
import com.pi4j.plugin.pigpio.provider.gpio.digital.PiGpioDigitalOutputProvider
fun main() {
// Create a context for Pi4J
val pi4j: Context = Pi4J.newAutoContext()
// Define pin 22 (BCM 25) as led pin and make it an output.
val led: DigitalOutput = pi4j.dout().create(25 /* PIN 22 */)
}Now we have defined our LED pin. It’s time to make our LED blink. Add these lines to make the LED blink.
I have crated a list of millisecond time duration values to blink the LED. It stays on for odd duration values and stays off for even duration values.
import com.pi4j.Pi4J
import com.pi4j.context.Context
import com.pi4j.io.gpio.digital.DigitalOutput
import com.pi4j.plugin.pigpio.provider.gpio.digital.PiGpioDigitalOutputProvider
fun main() {
val pi4j: Context = Pi4J.newAutoContext()
val led: DigitalOutput = pi4j.dout().create(25 /* PIN 22 */)
// Create a list of millisecond durations for the LED to be on and off
val pattern = arrayListOf(
0,
150,
150,
150,
150,
75,
75,
150,
150,
150,
150,
450
)
// iterate over the pattern list and turn the LED on and off
for (i in pattern.indices step 2) {
led.high()
Thread.sleep(pattern[i].toLong()) // ON time
if (i + 1 < pattern.size) {
led.low()
Thread.sleep(pattern[i + 1].toLong()) // OFF time
}
}
// turn off the LED after the pattern is done to ensure it is off
led.low()
}TIP: Try connecting a buzzer in place of the LED to hear this nice pattern.
Compiling the code
Now open the project’s folder in a terminal and run mvn clean package. This should create a .jar file inside the target directory.


For the mvn command to work, you need to have maven installed in your system. Follow this guide to learn how to install mvn on your system.
Running the code on a Raspberry Pi
Now it’s time to run the generated jar file on our Raspberry Pi. But before running it, we need to upload the file onto our Raspberry Pi. For this we’ll be using sftp
Turn on the Raspberry Pi and connect it to your local network. You can use WiFi or Ethernet for this. You have to know the local IP address of the Raspberry Pi. (You can use your router’s admin page or use nmap to find this)

Use the sftp command to upload the jar file to Raspberry Pi. For me, Raspberry Pi is using 192.168.124.248
sftp [email protected]
sftp> put /home/suhasdissa/Documents/IdeaProjects/MyFirstProject/target/robot.jar

Now the jar file is uploaded to the Raspberry Pi’s /home/rpi directory. Here, rpi is the username of the Raspberry Pi’s user account.
Now we can use ssh to log into our Pi and run the jar file
ssh [email protected]sudo java -jar robot.jar
Now you should see your LED blinking!
I hope this guide helped you to get an idea about Raspberry Pi and Pi4J.
I’ll meet you again with my next article.