语言:java
虚拟串口工具:Virtual Serial Port Driver Pro 9.0,选择pairing模块下,点击add virtual paring按钮即可创建串口对,还无法自定义out和in。
串口助手:xcom2.6,在串口选择框中选择刚创建好的虚拟串口,使用默认设置,点击打开串口,输入框中输入数据,点击发送数据即可发送数据。如果接收端没有接收到数据(稍微等等),则重新选择串口,互换输入输出端。
相关组件:jSerialComm==2.9.3
1.导入maven依赖:
<dependency> <groupId>com.fazecast</groupId> <artifactId>jSerialComm</artifactId> <version>[2.0.0,3.0.0)</version>
</dependency>
2.也可以直接导入jar包:把jSerialComm-2.9.3存入java项目的lib目录中,在IDEA下,选中jar包然后点击右键,选择add ad library,即可在代码中引用。
具体代码实现:
public void read(String portDescriptor) { //portDescriptor= e.g., "/dev/ttyS0" or "COM3" SerialPort[] serialPorts = SerialPort.getCommPorts(); //serialPorts[0]是接收端 SerialPort com3 = serialPorts[0]; com3.setParity(SerialPort.EVEN_PARITY); com3.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED); boolean isOpened = com3.openPort(); if (isOpened) { //基于事件监听 try { Thread.sleep(1000); SerialPort finalCom = com3; //监听器监听串口数据变化 com3.addDataListener(new SerialPortDataListener() { @Override public int getListeningEvents() { return SerialPort.LISTENING_EVENT_DATA_AVAILABLE; } @Override public void serialEvent(SerialPortEvent serialPortEvent) { if (serialPortEvent.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE) { return; } while (finalCom.bytesAvailable() != 0) { byte[] data = new byte[com3.bytesAvailable()]; int numRead = finalCom.readBytes(data, data.length); System.out.println("the length of data: "+ numRead); System.out.println(new String(data)); try { Thread.sleep(2000); } catch (Exception e) { e.printStackTrace(); } } } }); } catch (Exception e) { e.printStackTrace(); } } }
标签:java,读取,com3,SerialPort,串口,finalCom,data From: https://www.cnblogs.com/lanoBlog/p/17027484.html