java因为语言本身特性,并不能和硬件直接通信,所以想要调用串口和硬件通信,需要借助其他语言开发的插件,例如RXTX,树莓派中的pi4j。这里讲的是nrjavaserial这一插件,个人推荐使用
https://github.com/NeuronRobotics/nrjavaserial
这是RXTX 库的一个分支,侧重于易用性和在其他库中的嵌入性。
这个jar中包含了各个操作系统的native文件, 不需要在JDK中添加dll, so和jar,只需要在项目中引用依赖就可以正常使用,注意如果已自己安装了RXTX,有可能会冲突,最好卸载掉再使用
<dependency>
<groupId>com.neuronrobotics</groupId>
<artifactId>nrjavaserial</artifactId>
<version>5.1.1</version>
</dependency>
使用示例
import gnu.io.NRSerialPort;
String port = "";
for(String s:NRSerialPort.getAvailableSerialPorts()){
System.out.println("Availible port: "+s);
port=s;
}
int baudRate = 115200;
NRSerialPort serial = new NRSerialPort(port, baudRate);
serial.connect();
DataInputStream ins = new DataInputStream(serial.getInputStream());
DataOutputStream outs = new DataOutputStream(serial.getOutputStream());
try{
//while(ins.available()==0 && !Thread.interrupted());// wait for a byte
while(!Thread.interrupted()) {// read all bytes
if(ins.available()>0) {
char b = ins.read();
//outs.write((byte)b);
System.out.print(b);
}
Thread.sleep(5);
}
}catch(Exception ex){
ex.printStackTrace();
}
serial.disconnect();
Comments | 0 条评论