1.获取串口通讯端口
点击,【此电脑】-【管理】-【设备管理器】-【端口】
查看需要建立通讯的端口名称
2.项目引入RXTX依赖包
依赖包、串口调试工具、驱动地址:
链接:https://pan.baidu.com/s/1Cigd60l1T3UjLLHRp0TpiQ?pwd=rtxp
提取码:rtxp
3.示例代码
public class SerialCommunicationExample {
public static void main(String[] args) {
try {
// 获取串口通信端口
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("COM5");
// 打开串口
CommPort commPort = portIdentifier.open("SerialCommunicationExample", 8089);
// 判断通信端口类型
if (commPort instanceof SerialPort) {
SerialPort serialPort = (SerialPort) commPort;
// 配置串口参数
serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
// 获取输入流和输出流
InputStream inputStream = serialPort.getInputStream();
OutputStream outputStream = serialPort.getOutputStream();
// 创建线程读取串口数据
Thread readThread = new Thread(() -> {
try {
while (true) {
// int data = inputStream.read();
// System.out.print(data);
int a = 0;
while ((a = inputStream.read()) != -1) {
String data = String.format("%04x%n", a);
System.out.print("原始int:" + a + "转换后值:" + data);
}
}
} catch (IOException e) {
e.printStackTrace();
}
});
// 启动读取线程
readThread.start();
// 写入串口数据
byte[] array = new byte[5];
array[0] = (byte) 0xD1;
array[1] = (byte) 0xF5;
array[2] = (byte) 0x01;
array[3] = (byte) 0x01;
array[4] = (byte) 0x24;
// outputStream.write("D1 F5 01 01 24".getBytes());
outputStream.write(array);
System.out.println("写入完毕!");
// 关闭输入流、输出流和串口
// inputStream.close();
outputStream.close();
// serialPort.close();
} else {
System.out.println("Error: Only serial ports are handled by this example.");
}
} catch (Exception e) {
e.printStackTrace();
}
}