【串口】Java中串口通讯的基本用例

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();
        }
    }

4.查验流数据是否写入到端口所在硬件设备

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值