本次使用rxtx对接串口,完成交互通信。共遇到两个坑:
1、rxtx在linux下有的版本有问题,安装后会报错。已上传windows和linux下通用的版本压缩包,地址如下:
/download/weixin_42193415/12245957
2、(byte[])阻塞的坑,造成线程阻塞,获取不到数据,最后优化为如下代码:
/**
* 从串口读取数据
*
* @param serialPort 当前已建立连接的SerialPort对象
* @return 读取到的数据
*/
public static byte[] readFromPort(SerialPort serialPort) {
InputStream in = null;
byte[] bytes = {};
try {
in = ();
// 缓冲区大小为一个字节
byte[] readBuffer = new byte[1];
int bytesNum = 1;
while (bytesNum > 0) {
//如果缓冲区读取结束,且数组长度为7(防止串口数据发送缓慢读取到空数据),跳出循环
if (() > 0) {
bytesNum = (readBuffer);
bytes = (bytes, readBuffer);
}else if(==7){
break;
}
}
} catch (IOException e) {
new ReadDataFromSerialPortFailure().printStackTrace();
} finally {
try {
if (in != null) {
();
in = null;
}
} catch (IOException e) {
new SerialPortInputStreamCloseFailure().printStackTrace();
}
}
return bytes;
}