需要准备以下设备
四路继电器,2262/2272四路遥控模块,树莓派,扩展板,母对母杜邦线12跟,公对公杜邦线2跟
在树莓派安装Pi4J库
执行以下命令安装Pi4J
curl -s get.pi4j.com | sudo bash
2. 插线
将遥控接收模块的5V与扩展板的5.0 VDC对接,GND与扩展板的Ground对接,D0,D1,D2,D3分别与扩展板的GPIO 1,GPIO 2,GPIO 3,GPIO 4对接,把两根公对公杜邦线插在遥控接收模块的ANT口充当天线。
将继电器的VCC与扩展板的5.0 VDC对接,GND与扩展板的Ground对接,IN1,IN2,IN3,IN4分别与扩展板的GPIO 5,GPIO 6,GPIO 7,GPIO 8对接。
3. 编写JAVA代码
工程需要引入pi4j依赖库
gradle:
com.pi4j:pi4j-core:1.0
maven
<dependency> <groupId>com.pi4j</groupId> <artifactId>pi4j-core</artifactId> <version>1.1-SNAPSHOT</version> </dependency>
或下载jar包 http://central.maven.org/maven2/com/pi4j/pi4j-core/1.0/pi4j-core-1.0.jar
JAVA代码部分
import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinPullResistance; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import com.pi4j.io.gpio.event.GpioPinListenerDigital; public class PiController { private static final GpioController GPIOCONTROLLER = GpioFactory.getInstance(); public static void main(String s[]) { final GpioPinDigitalInput input[] = { GPIOCONTROLLER.provisionDigitalInputPin(RaspiPin.GPIO_01), GPIOCONTROLLER.provisionDigitalInputPin(RaspiPin.GPIO_02), GPIOCONTROLLER.provisionDigitalInputPin(RaspiPin.GPIO_03), GPIOCONTROLLER.provisionDigitalInputPin(RaspiPin.GPIO_04) }; final GpioPinDigitalOutput output[] = { GPIOCONTROLLER.provisionDigitalOutputPin(RaspiPin.GPIO_05, PinState.HIGH), GPIOCONTROLLER.provisionDigitalOutputPin(RaspiPin.GPIO_06, PinState.HIGH), GPIOCONTROLLER.provisionDigitalOutputPin(RaspiPin.GPIO_07, PinState.HIGH), GPIOCONTROLLER.provisionDigitalOutputPin(RaspiPin.GPIO_08, PinState.HIGH) }; for (int i = 0; i < input.length; i++) { output[i].setShutdownOptions(true, PinState.HIGH, PinPullResistance.OFF); input[i].addListener(new MyGpioPinListenerDigital(output[i])); } while (true) { try { Thread.sleep(10000); } catch (Exception e) { e.printStackTrace(); } } } } class MyGpioPinListenerDigital implements GpioPinListenerDigital { public MyGpioPinListenerDigital(GpioPinDigitalOutput output) { this.output = output; } GpioPinDigitalOutput output; @Override public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) { if (PinState.HIGH == event.getState()) { output.toggle(); } } }
4. 编译代码,打包部署
将工程导出为jar包,使用ssh工具将打好的包和pi4j-core-1.0.jar一起放到树莓派/home/pi/gpio/目录下。
执行以下命令运行程序:
cd /home/pi/gpio/ sudo java -cp .:classes:/opt/pi4j/lib/'*' PiController
5. 测试与应用
按下遥控的按钮,即可听到继电器的通断声音。
继电器一般有三个插孔,分别是常开,常关,公共。常开和常关根据实际需求选择其一,结合公共接口使用,比如我们要控制电灯,可以将电灯的电线某一跟剪开,剪开的电线一端插入常关接口,一端插入公共接口就实现了电灯的控制。
标签:树莓派
2条评论
😄 有啊 类似于插座插头
线也分公母啊?
发表评论