Maven依赖引入
<dependency>
<groupId>com.fazecast</groupId>
<artifactId>jSerialComm</artifactId>
<version>[2.0.0,3.0.0)</version>
</dependency>
开启串口以及监听串口数据
SerialPort[] serialPorts = SerialPort.getCommPorts(); // 获取本机的所有串口
String serialPortName = "COM40"; // 此处定义需要打开的串口
SerialPort serialPort = null;
boolean isPortOpened = false;
for (SerialPort port : serialPorts) {
log.info(String.format("端口名称:%s", port.getSystemPortName()));
if (port.getSystemPortName().equals(serialPortName)) {
serialPort = port;
break;
}
}
if (serialPort == null) {
log.info("未找到指定串口!");
} else {
log.info(String.format("找到指定串口:%s", serialPort.getSystemPortName()));
serialPort.setComPortParameters(9600, 8, SerialPort.ONE_STOP_BIT, SerialPort.NO_PARITY); // 串口参数配置
serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING | SerialPort.TIMEOUT_WRITE_BLOCKING, 1000, 1000);//设置超时
if (!serialPort.isOpen()) {
isPortOpened = serialPort.openPort();
if (isPortOpened) {
log.info("串口已打开");
SerialPort port = serialPort;
serialPort.addDataListener(new SerialPortDataListener() {
@Override
public int getListeningEvents() {
return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
}
@Override
public void serialEvent(SerialPortEvent serialPortEvent) {
String data = "";
if (serialPortEvent.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE) {
return;
}
while (port.bytesAvailable() != 0) {
byte[] newData = new byte[port.bytesAvailable()];
int numRead = port.readBytes(newData, newData.length);
String newDataString = new String(newData);
data = data + newDataString;
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
log.error(e.getMessage());
}
}
log.info(String.format("串口接收完成:%s", data));
}
});
} else log.info("串口打开失败");
}
}
发送数据到串口
serialPort.writeBytes("Hello World!".getBytes(), "Hello World!".getBytes().length);
关闭串口
serialPort.closePort();