Spring boot串口通信,windows、linux,docker环境配置说明

docker 知退 4年前 (2020-12-26) 1799次浏览 0个评论 扫描二维码

1.Spring boot有转用于串口通讯包

该包网上教程大多都是监听串口获取数据,如果只接收数据,可以自行百度,该包使用方法

2.使用com.fazecast下的jSerialComm jar包

//打印当前jar包库版本
log.debug("使用库版本:{}", SerialPort.getVersion());
//获取该主机所有串口
SerialPort.getCommPorts();
//通过串口名称获取串口对象,Windows一般COM+数字,Liunx一般ttyUSB+数字
SerialPort.getCommPort("COM")
//预设rts;
serialPort.setRTS();
//获取当前串口名称
serialPort.getDescriptivePortName());
//设定流量控制
serialPort.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
//设置波特率为9600,数据位为8,停止位为1,校验位为偶校验
serialPort.setComPortParameters(9600, 8, SerialPort.ONE_STOP_BIT, SerialPort.EVEN_PARITY);
//设置串口超时,超时读取阻止,超时写入阻止
serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING | SerialPort.TIMEOUT_WRITE_BLOCKING, 1000, 1000);
//向串口写入内容,off为字节数组,返回写入的字节长度
serialPort.writeBytes(off, off.length);
//读取串口输出内容,content为串口输出内容,返回读取长度
 serialPort.readBytes(content, content.length)
//关闭串口
serialPort.closePort();

3.docker容器配置

使用docker发布jar时,如果不映射本机设备,将导致无法访问串口;所以在使用docker发布容器时需要加上–device=/dev/ttyUSB0,指定本机串口映射或者使用 –privileged模式发布发布容器,不过–privileged模式映射所有设备不够安全,所以最好指定特定串口。

idea配置如下:

喜欢 (6)
[支付宝扫码,感谢支持]
分享 (0)
关于作者:
一个很懒的人

您必须 登录 才能发表评论!