深眸分享——Java串口通信

java读写串口数据可以使用jSerialComm包

在build.gradle中引入jSerialComm

ion "com.fazecast:jSerialComm:2.9.2"

1、查询所有串口

/**  
 查找所有可用串口 

@return  
 */  
public static List<String> findPorts() {  
 // 获得当前所有可用串口  
 SerialPort[] serialPorts = SerialPort.getCommPorts();  
 List<String> portNameList = new ArrayList<>();  
 // 将可用串口名添加到List并返回该List  
 for (SerialPort serialPort : serialPorts) {  
 portNameList.add(serialPort.getSystemPortName());  
 log.info(JSON.toJSONString(serialPort));  
 }  
 //去重  
 portNameList = portNameList.stream().distinct().collect(Collectors.toList());  
 return portNameList;  
}

可以获取到串口对象

{"baudRate":9600,"cTS":false,"dCD":false,"dSR":false,"dTR":false,"descriptivePortName":"Bluetooth-Incoming-Port","deviceReadBufferSize":4096,"deviceWriteBufferSize":4096,"flowControlSettings":0,"lastErrorCode":0,"lastErrorLocation":0,"numDataBits":8,"numStopBits":1,"open":false,"outputStream":{},"parity":0,"portDescription":"Bluetooth-Incoming-Port","portLocation":"0-0","rI":false,"rTS":false,"readTimeout":0,"systemPortName":"cu.Bluetooth-Incoming-Port","systemPortPath":"/dev/cu.Bluetooth-Incoming-Port","writeTimeout":0}

2、打开串口

/**
     打开串口

     @param portName 串口名称
     @param baudRate 波特率    9600/11520
     @return 串口对象
     */
    public static SerialPort openPort(String portName, int baudRate) {
        if (!findPorts().contains(portName)) {
            log.error("未找到串口 {}", portName);
            return null;
        }
        SerialPort serialPort = SerialPort.getCommPort(portName);
        if (serialPort.isOpen()) {
            serialPort.setBaudRate(baudRate);
            return serialPort;
        }
        //开启串口
        boolean isOpen = serialPort.openPort();
        if (!isOpen) {
            log.error("打开串口 {} 失败", portName);
            // 开启失败,占用
            return null;
        }
        // 设置一下串口的波特率等参数
        // 数据位:8
        // 停止位:1
        // 校验位:None
        serialPort.setBaudRate(baudRate);
        serialPort.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
        serialPort.setComPortParameters(baudRate, 8, SerialPort.ONE_STOP_BIT, SerialPort.NO_PARITY);
        serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING | SerialPort.TIMEOUT_WRITE_BLOCKING, 1000, 1000);
        log.info("打开串口 {}: {}", portName, JSON.toJSONString(serialPort));
        return serialPort;
    }

3、发送数据

/**  
 往串口发送数据  

 @param serialPort 串口对象  
 @param content    待发送数据  
 */  
public static void sendToPort(SerialPort serialPort, byte[] content) {  
    if (serialPort != null && serialPort.isOpen()) {  
        log.info("向串口 {} 发送数据: {}", serialPort.getSystemPortName(), content);  
        serialPort.writeBytes(content, content.length);  
    }  
}

向打开的串口发送数据

4、读取数据

/**
     从串口读取数据
     @param serialPort 当前已建立连接的SerialPort对象
     @return 读取到的数据
     */
    public static byte[] readFromPort(SerialPort serialPort) {
        byte[] recvData = null;
        if (serialPort == null || !serialPort.isOpen()) {
            return null;
        }
        while (serialPort.bytesAvailable() != 0) {
            byte[] readBuffer = new byte[serialPort.bytesAvailable()];
            int numRead = serialPort.readBytes(readBuffer, readBuffer.length);
            if (recvData == null) {
                recvData = readBuffer;
            } else {
                recvData = ArrayUtils.addAll(recvData, readBuffer);
            }

            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        log.info("收到串口 {} 数据: {}", serialPort.getSystemPortName(), recvData);
        return recvData;
    }

从串口读取数据,串口打开后和两次读取之间一定要休眠,不然程序感知不到输入流里有数据

5、关闭串口

/**
     关闭串口

     @param serialPort 待关闭的串口对象
     */
    public static void closePort(SerialPort serialPort) {
        if (serialPort != null && serialPort.isOpen()) {
            log.info("关闭串口 {}", serialPort.getSystemPortName());
            serialPort.closePort();
        }
    }

传入打开的串口对象关闭串口

6、完整流程

public static void main(String[] args) {
        SerialPort serialPort = openPort("cu.Bluetooth-Incoming-Port", 9600);
        sendToPort(serialPort, new byte[]{-6, 0, -81, -1});
        closePort(serialPort);
    }

执行结果

打开串口 cu.Bluetooth-Incoming-Port: {"baudRate":9600,"cTS":false,"dCD":false,"dSR":false,"dTR":true,"descriptivePortName":"Bluetooth-Incoming-Port","deviceReadBufferSize":4096,"deviceWriteBufferSize":4096,"flowControlSettings":0,"lastErrorCode":0,"lastErrorLocation":470,"numDataBits":8,"numStopBits":1,"open":true,"outputStream":{},"parity":0,"portDescription":"Bluetooth-Incoming-Port","portLocation":"0-0","rI":false,"rTS":true,"readTimeout":1000,"systemPortName":"cu.Bluetooth-Incoming-Port","systemPortPath":"/dev/cu.Bluetooth-Incoming-Port","writeTimeout":0}
向串口 cu.Bluetooth-Incoming-Port 发送数据: [-6, 0, -81, -1]
关闭串口 cu.Bluetooth-Incoming-Port
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值