PI4J provides a friendly object-oriented I/O API and implementation libraries for Java programmers to access the full I/O capabilities of the Raspberry Pi platform. This project abstracts the low-level native integration and interrupt monitoring to enable Java programmers to focus on implementing their application business logic.

1 Using Pi4J to control LED's using GPIO

Sample Code for turn on LED and turn off via GPIO 15 pin:

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

public class LEDGpioExample {
    final GpioController gpio = GpioFactory.getInstance();
    final GpioPinDigitalOutput pin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_15, "MyLED");
    pin.setShutdownOptions(true, PinState.LOW);



2 Remotely Control Raspberry LED using Java (pi4j) and MQTT Protocol

We will show how to remote control Raspberry Pi using MQTT protocol to receive commands and how to control GPIO pins using Pi4J.

  • We will install Mosquito server in an Amazon Ec2 instances (free tier).
  • We will install a Web server on a desktop computer. In this web server, Mosquito will be used as message broker.
  • In Raspberry Pi, our code is to going connect the Mosquitto message broker with the help of paho library. The client will subscribe the topic and will wait for any message. If any message is received, the client will process the message based on the message to turn on/off LED using pi4j library.

2.1 Setup a MQTT server

MQTT (formerly MQ Telemetry Transport) is a publish-subscribe based "light weight" messaging protocol for use on top of the TCP/IP protocol. It is designed for connections with remote locations where a "small code footprint" is required or the network bandwidth is limited. The publish-subscribe messaging pattern requires a message broker. The broker is responsible for distributing messages to interested clients based on the topic of a message.

We are going to use CloudMQTT Cute Cat plan.

  • Sign up
  • Get account and provide a topic
  • Once connected, from the Overview console you can see your assigned server, username and password. You will need this values to connect to the broker

2.2 Write the Web controller


This section is incomplete and will be concluded as soon as possible.