Read value of a pin on raspberry pi in java

I work on a project now, and I need to read the value of a pin on raspberry pi in java.

I works with a light sensor. Depending on its value, when it is day, I do nothing, and if it is night, I need to switch on some LEDs.

I already know how to switch on or off LEDs, because the pin are set as output, but I don’t really know how to read a value from a pin(which is set as input).

I have been looking on pi4j websites, using there examples, but the only thing I found was to listen for an event.(which is not very far from what I want, but I didn’t succed to adapt it for my case).

I would like to recover the value of this pin (high or low), to be able to compare it (if state == HIGH, switch on the LEDs, else do nothing).

Thank you for your attention, don’t hesitate to tell me if you need any further information.


I finally find a way to do what I wanted.

It is not very “clean”, but it works. I post it here if it can help for others. It was very easy at the end… I hope it will help.

import com.pi4j.wiringpi.Gpio;
import com.pi4j.wiringpi.GpioUtil;

public class Test {

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

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

Gpio.pinMode (3, Gpio.INPUT) ;          

if (Gpio.digitalRead(3) == 0){ // it is day, so doesn't need LEDs
      System.out.println("Day, LEDs are not switched on");
}else{ // it is night, LEDs are needed
      System.out.println("Night, LEDs are switched on");


Leave a Reply

Your email address will not be published. Required fields are marked *