Read value of a pin on raspberry pi in java Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Read value of a pin on raspberry pi in java without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.

Answer

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.io.*;
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");
}
}

}

We are here to answer your question about Read value of a pin on raspberry pi in java - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji