可通过此代码获取系统中串口
List<String> result = new ArrayList<>();
// 获取系统中所有的通讯端口
Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();
// 循环通讯端口
while (portList.hasMoreElements()) {
CommPortIdentifier commPortId = portList.nextElement();
// 判断是否是串口
if (commPortId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
// 比较串口名称是否是指定串口
result.add(commPortId.getName());
}
}
连接端口
SerialPort serialPort = SerialPort.getCommPort("COM2"); // 替换为你的端口名
serialPort.setComPortParameters(9600, 8, 1, 0); // 设置端口参数
serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING, timeout, 0);//超时时间
if (serialPort.openPort()) {
return "连接成功";
} else {
return "连接失败";
}
发送接收数据
byte[] sendInfo = new byte[] {0x01, 0x03,0x00, 0x01, 0x00, 0x01, 0xD5, 0xCA };
serialPort.writeBytes(sendInfo , sendInfo .length);
byte[] readBuffer = new byte[1024];
int numRead = serialPort.readBytes(readBuffer, readBuffer.length);
byte[] s2 = new byte[numRead];
for (int i = 0; i < numRead; i++) {
s2[i] = readBuffer[i];
}