简体   繁体   English

在Java中读取树莓派上的引脚的值

[英]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. 我现在在一个项目上工作,我需要在Java中读取树莓派上的pin值。

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. 根据其值,在白天时,我什么都不做;在夜晚时,我需要打开一些LED。

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). 我已经知道如何打开或关闭LED,因为该引脚被设置为输出,但是我真的不知道如何从一个引脚(被设置为输入)读取值。

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). 我一直在pi4j网站上使用示例进行查找,但我发现的唯一内容是监听事件(这与我想要的相距不远,但是我没有成功地使其适应我的情况)。

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). 我想恢复该引脚的值(高或低),以便进行比较(如果状态== HIGH,则打开LED,否则什么也不做)。

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

} }

well I assume that reading value from the pin should be easy to implement. 好吧,我认为从引脚读取值应该易于实现。

Check any tutorial 查看任何教程

Check specification of RaspPi that describes what state deasit counts as HIGH. 检查RaspPi的规范,该规范描述了什么状态无效被计为HIGH。 Adjust your electric set-up to provide enough voltage on that pin on trigger value. 调整电气设置,以在触发值上的该引脚上提供足够的电压。 So basically you have to scale output voltage of light sensitive meter to match high voltage considered as High for that pin. 因此,基本上,您必须缩放光敏仪表的输出电压,以匹配该引脚被视为“高”的高压。

Or you can go with any ADC circuit avaliable for Rpi that will translate analog signal to digital. 或者,您可以使用任何Rpi可用的ADC电路,它将模拟信号转换为数字信号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM