首先下载
http://get.pi4j.com/download/pi4j-1.2-SNAPSHOT.zip(使用SNAPSHOT是因为3B要用这个新版本才正常,1.1版本不能在3B上运行),解的jar文件使用eclipse进行开发,把3B作为伺服器进行socket端口监听,没有实现多线程多客户端监听,简单的点对点监听。
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import com.pi4j.io.gpio.*;
//Raspberry Server ,accept action 1/0
public class Rasp {
public static final GpioController gpio=GpioFactory.getInstance();
public static void main(String[] args) {
ServerSocket server = null;
Socket you = null;
DataOutputStream out = null;
DataInputStream in = null;
GpioPinDigitalOutput led=gpio.provisionDigitalOutputPin(RaspiPin.GPIO_29, "",PinState.LOW);
try {
server = new ServerSocket(8970);
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println("Wait.....");
you = server.accept();
in = new DataInputStream(you.getInputStream());
out = new DataOutputStream(you.getOutputStream());
while (true) {
int i = in.readInt();
System.out.println(i);
// GPIO Control
if (i == 1) {
led.high();
out.writeUTF("LED ON");
} else if (i == 0) {
led.low();
out.writeUTF("LED OFF");
} else
out.writeUTF("Invalid");
Thread.sleep(500);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
编译好的class文件上传到3B上,3B上也需要安装pi4j