大佬的文章
https://blog.youkuaiyun.com/wangmx1993328/article/details/88692848
这篇只做信息补充
rxtx 资源包地址
rxtx项目资源 x86 jar
https://download.youkuaiyun.com/download/ling_zhi_xin/89623027
rxtx项目资源 x64 jar
https://download.youkuaiyun.com/download/ling_zhi_xin/89623018
java 调用 串口信息 并获取信息, 具体SerialPortTool 采用上方大佬的工具类,
SerialPort addEventListener 实现读取信息的监听用来 使用
SerialPort com6 = SerialPortTool.openComPort("COM6", 9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
Thread.sleep(2000);
System.out.println(DateFormatUtils.format(new Date(), "yyyy-MM-dd hh:mm:ssZZ"));
com6.notifyOnDataAvailable(true);
BlockingQueue<Boolean> queue = new LinkedBlockingQueue<>();
com6.addEventListener(new SerialPortEventListener() {
@Override
public void serialEvent(SerialPortEvent serialPortEvent) {
System.out.println(serialPortEvent.getNewValue());
if(serialPortEvent.getNewValue()){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
try {
System.out.println("erw: "+SerialPortTool.readData(com6));
queue.add(false);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
});
String s="open";
SerialPortTool.sendDataToComPort(com6,s.getBytes(StandardCharsets.UTF_8));
while (true){
if(queue.take()){
break;
}
}
SerialPortTool.closeComPort(com6);
读取方法补充
/**
* 从串行端口读取数据
*
* @param serialPort 串行端口对象
* @return 读取到的数据
* @throws IOException 如果读取过程中出现异常
*/
public static String readData(SerialPort serialPort) throws IOException {
InputStream inputStream = serialPort.getInputStream();
byte[] buffer = new byte[1024];
int len;
StringBuilder sb = new StringBuilder();
while ((len = inputStream.read(buffer)) > 0) {
String data = new String(buffer, 0, len, StandardCharsets.UTF_8);
int index = data.indexOf('\n'); // 查找换行符的位置
buffer = new byte[1024];
if (index >= 0) {
sb.append(data.substring(0, index)); // 添加数据到 StringBuilder
break; // 找到换行符后结束循环
} else {
sb.append(data); // 如果没有找到换行符,继续读取数据
}
}
return sb.toString();
}