Java 串口通讯 Demo
  HwStpnXEg1k1 2023年11月02日 30 0


为什么写这篇文章

之前职业生涯中遇到的都是通过tcp协议与其他设备进行通讯,而这个是通过串口与其他设备进行通讯,意识到这里是承重板的连接,但实际上比如拉力、压力等模拟信号转换成数字信号的设备应该是有相当一大部分是通过这种方式通讯的。

研究了2天,有初步的成果,特此记录

整体结构

这几天公司弄来了几台称重板,需要通过程序读取称重板的重量数值。

称重板没有wifi,目前是通过串口与PC相连的形式工作,结构类似如下

Java 串口通讯 Demo_开发语言


Java 串口通讯 Demo_字节数组_02


称重板通过线(不知道叫什么线,有黄绿黑红4根细线组成,其中红黑应该是电源线)与485转usb的工具插电脑上

Java 串口通讯 Demo_字节数组_03

说说Java如何与串口通信

整体来说,java与串口通信有三种模式

  1. Jdk自带的接口comm.jar,没有测试,据说是比较老了,基本不用
  2. RXTXcomm.jar:也是比较老了,2012年开始就没有更新,但是网上很多教程是基于这个的,比如:https://www.jianshu.com/p/7c03ad8a6139,应该是只能在windows下面使用(不确定),需要copy两个dll文件到jdk的安装目录。如果要maven里面引入是这样的
<dependency>
    <groupId>org.rxtx</groupId>
    <artifactId>rxtx</artifactId>
    <version>2.1.7</version>
</dependency>
  1. JSerialComm:较新、且与平台无关

个人认为使用JSerialComm是比较合适的,本文Demo也是基于此实现

JAVA代码

<dependency>
    <groupId>com.fazecast</groupId>
    <artifactId>jSerialComm</artifactId>
    <version>[2.0.0,3.0.0)</version>
</dependency>

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>4.5.15</version>
</dependency>
package com.bt.rs232.JSerialCommDemo2;

import com.bt.rs232.util.StringUtil;
import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.SerialPortDataListener;
import com.fazecast.jSerialComm.SerialPortEvent;

/**
 * @author :GuangXiZhong
 * @date :Created in 2023/7/19 11:29
 * @description:
 */
public class Test {
    public static void main(String[] args) throws InterruptedException {
        SerialPort[] serialPorts = SerialPort.getCommPorts();//查找所有串口
        for (SerialPort port : serialPorts) {
            System.out.println("Port:" + port.getSystemPortName());//打印串口名称,如COM4
            System.out.println("PortDesc:" + port.getPortDescription());//打印串口类型,如USB Serial
            System.out.println("PortDesc:" + port.getDescriptivePortName());//打印串口的完整类型,如USB-SERIAL CH340(COM4)

            port.addDataListener(new SerialPortDataListener() {//添加监听器。由于该监听器有两个函数,无法使用Lambda表达式

                @Override
                public int getListeningEvents() {
                    return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;//返回要监听的事件类型,以供回调函数使用。可发回的事件包括:SerialPort.LISTENING_EVENT_DATA_AVAILABLE,SerialPort.LISTENING_EVENT_DATA_WRITTEN,SerialPort.LISTENING_EVENT_DATA_RECEIVED。分别对应有数据在串口(不论是读的还是写的),有数据写入串口,从串口读取数据。如果AVAILABLE和RECEIVED同时被监听,优先触发RECEIVED
                }

                @Override
                public void serialEvent(SerialPortEvent event) {//事件处理函数
                    String data = "";
                    if (event.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE) {
                        return;//判断事件的类型
                    }
                    while (port.bytesAvailable() != 0) {
                        //同样使用循环读取法读取所有数据
                        //由于这里是监听函数,所以也可以不使用循环读取法,在监听器外创建一个全局变量,然后将每次读取到的数据添加到全局变量里
                        byte[] newData = new byte[port.bytesAvailable()];
                        int numRead = port.readBytes(newData, newData.length);
//                        String newDataString = new String(newData);
                        String newDataString = StringUtil.bytesToHexString(newData);
                        data = data + newDataString;
                        try {
                            Thread.sleep(20);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("readString:" + data);
                }
            });
        }
        SerialPort serialPort = serialPorts[0];//获取到第一个串口
        serialPort.setBaudRate(19200);//设置波特率为112500
        serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING | SerialPort.TIMEOUT_WRITE_BLOCKING, 1000, 1000);//设置超时
        serialPort.setRTS();//设置RTS。也可以设置DTR
        serialPort.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);//设置串口的控制流,可以设置为disabled,或者CTS, RTS/CTS, DSR, DTR/DSR, Xon, Xoff, Xon/Xoff等
        // 一次性设置所有的串口参数,第一个参数为波特率,默认9600;
        // 第二个参数为每一位的大小,默认8,可以输入5到8之间的值;
        // 第三个参数为停止位大小,只接受内置常量,可以选择(ONE_STOP_BIT, ONE_POINT_FIVE_STOP_BITS, TWO_STOP_BITS);
        // 第四位为校验位,同样只接受内置常量,可以选择 NO_PARITY, EVEN_PARITY, ODD_PARITY, MARK_PARITY,SPACE_PARITY。
        serialPort.setComPortParameters(19200, 8, SerialPort.ONE_STOP_BIT, SerialPort.EVEN_PARITY);

        boolean isCommOpeded = serialPort.openPort();//判断串口是否打开,如果没打开,就打开串口。打开串口的函数会返回一个boolean值,用于表明串口是否成功打开了
        if (!isCommOpeded) {
            System.out.println("串口打开失败,请确认是否有其他设备正在使用此串口!");
        }
//        for (SerialPort port : serialPorts) {
        // 一开始以为要用这个转,用了虚拟助手才发现传输的是16个字节,排查下来需要用new byte,这边要特别注意
        String writeData = "0203002C000205F1";//要发送的字符串
//            byte[] bytes = writeData.getBytes();//将字符串转换为字节数组
        byte[] bytes = StringUtil.hexStringToByteArray(writeData);

        byte[] bytes1 = new byte[8];
        bytes1[0] = (byte) Integer.parseInt("02", 16);
        bytes1[1] = (byte) Integer.parseInt("03", 16);
        bytes1[2] = (byte) Integer.parseInt("00", 16);
        bytes1[3] = (byte) Integer.parseInt("2C", 16);
        bytes1[4] = (byte) Integer.parseInt("00", 16);
        bytes1[5] = (byte) Integer.parseInt("02", 16);
        bytes1[6] = (byte) Integer.parseInt("05", 16);
        bytes1[7] = (byte) Integer.parseInt("F1", 16);

        serialPort.writeBytes(bytes, bytes.length);//将字节数组全部写入串口
        Thread.sleep(1000);//休眠0.1秒,等待下位机返回数据。如果不休眠直接读取,有可能无法成功读到数据
//            String readData = "";
//            while (serialPort.bytesAvailable() > 0) {//循环读取所有的返回数据。如果可读取数据长度为0或-1,则停止读取
//                byte[] newData = new byte[serialPort.bytesAvailable()];//创建一个字节数组,长度为可读取的字节长度
//                int numRead = serialPort.readBytes(newData, newData.length);//将串口中可读取的数据读入字节数组,返回值为本次读取到的字节长度
//                String newDataString = new String(newData);//将新数据转为字符串
//                readData = readData + newDataString;//组合字符串
//                Thread.sleep(20);//休眠0.02秒,等待下位机传送数据到串口。如果不休眠,直接再次使用port.bytesAvailable()函数会因为下位机还没有返回数据而返回-1,并跳出循环导致数据没读完。休眠时间可以自行调试,时间越长,单次读取到的数据越多。
//            }
//            System.out.println("readString:" + readData);
//        }
        serialPort.closePort();//关闭串口。该函数同样会返回一个boolean值,表明串口是否成功关闭
    }
}
public class StringUtil {
   /**
     * 将字符串转换为十六进制
     *
     * @param value
     * @return
     */
    public static String stringToHex(String value) {
        StringBuffer sb = new StringBuffer();
        byte[] by = new byte[0];
        try {
            by = value.getBytes("GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < by.length; i++) {
            String str = Integer.toHexString(by[i] & 0XFF);
            sb.append(str.toUpperCase(Locale.ROOT));
        }
        return sb.toString();
    }
}

推荐两个好用的调试工具

  1. 友善串口调试助手(可以手动往某个串口发送数据)
  2. Java 串口通讯 Demo_java_04

  3. Virtual Serial Port Driver Pro(串口虚拟工具,用以模拟一个串口)
  4. Java 串口通讯 Demo_串口_05

总结自己调试过程中遇到的问题

一开始我遵循了协议往对应的串口发,却没有办法收到称重板给的返回数据,经过排查是我发送的方法错误

String writeData = "0203002C000205F1";
// 将字符串转换为字节数组,这种方式是不对的
// byte[] bytes = writeData.getBytes();

// 这是对的方式,把String类型的16进制字符串转化成字节数组
byte[] bytes = HexUtil.decodeHex(writeData)
serialPort.writeBytes(bytes, bytes.length);

关于CRC16校验码

我调试的这个指令最后两位是指CRC16校验码,这个东西相当于对一整段数据的简单校验,用以接收方判断收到的数据是否完整

PS:之前我一直以为这种协议是这个称的厂家自己定义的,后来才知道这个协议叫Modbus-RTU协议,是一种比较简单、可靠的协议,常用于串口通讯,他的报文结构如下

Java 串口通讯 Demo_开发语言_06


正所谓师傅领进门,修行在个人。真的很多不复杂的东西但是如果没有人领进门的话自己需要摸索很久,哪怕学习都不知道从哪里开始

在Java中生成CRC16校验码的代码如下

package com.yrt.common.utils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CRC16Util {
    static byte[] crc16_tab_h = {(byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0,
            (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1,
            (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
            (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
            (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40};

    static byte[] crc16_tab_l = {(byte) 0x00, (byte) 0xC0, (byte) 0xC1, (byte) 0x01, (byte) 0xC3, (byte) 0x03, (byte) 0x02, (byte) 0xC2, (byte) 0xC6, (byte) 0x06, (byte) 0x07, (byte) 0xC7, (byte) 0x05, (byte) 0xC5, (byte) 0xC4, (byte) 0x04, (byte) 0xCC, (byte) 0x0C, (byte) 0x0D, (byte) 0xCD, (byte) 0x0F, (byte) 0xCF, (byte) 0xCE, (byte) 0x0E, (byte) 0x0A, (byte) 0xCA, (byte) 0xCB, (byte) 0x0B, (byte) 0xC9, (byte) 0x09, (byte) 0x08, (byte) 0xC8, (byte) 0xD8, (byte) 0x18, (byte) 0x19, (byte) 0xD9, (byte) 0x1B, (byte) 0xDB, (byte) 0xDA, (byte) 0x1A, (byte) 0x1E, (byte) 0xDE, (byte) 0xDF, (byte) 0x1F, (byte) 0xDD, (byte) 0x1D, (byte) 0x1C, (byte) 0xDC, (byte) 0x14, (byte) 0xD4, (byte) 0xD5, (byte) 0x15, (byte) 0xD7, (byte) 0x17, (byte) 0x16, (byte) 0xD6, (byte) 0xD2, (byte) 0x12,
            (byte) 0x13, (byte) 0xD3, (byte) 0x11, (byte) 0xD1, (byte) 0xD0, (byte) 0x10, (byte) 0xF0, (byte) 0x30, (byte) 0x31, (byte) 0xF1, (byte) 0x33, (byte) 0xF3, (byte) 0xF2, (byte) 0x32, (byte) 0x36, (byte) 0xF6, (byte) 0xF7, (byte) 0x37, (byte) 0xF5, (byte) 0x35, (byte) 0x34, (byte) 0xF4, (byte) 0x3C, (byte) 0xFC, (byte) 0xFD, (byte) 0x3D, (byte) 0xFF, (byte) 0x3F, (byte) 0x3E, (byte) 0xFE, (byte) 0xFA, (byte) 0x3A, (byte) 0x3B, (byte) 0xFB, (byte) 0x39, (byte) 0xF9, (byte) 0xF8, (byte) 0x38, (byte) 0x28, (byte) 0xE8, (byte) 0xE9, (byte) 0x29, (byte) 0xEB, (byte) 0x2B, (byte) 0x2A, (byte) 0xEA, (byte) 0xEE, (byte) 0x2E, (byte) 0x2F, (byte) 0xEF, (byte) 0x2D, (byte) 0xED, (byte) 0xEC, (byte) 0x2C, (byte) 0xE4, (byte) 0x24, (byte) 0x25, (byte) 0xE5, (byte) 0x27, (byte) 0xE7,
            (byte) 0xE6, (byte) 0x26, (byte) 0x22, (byte) 0xE2, (byte) 0xE3, (byte) 0x23, (byte) 0xE1, (byte) 0x21, (byte) 0x20, (byte) 0xE0, (byte) 0xA0, (byte) 0x60, (byte) 0x61, (byte) 0xA1, (byte) 0x63, (byte) 0xA3, (byte) 0xA2, (byte) 0x62, (byte) 0x66, (byte) 0xA6, (byte) 0xA7, (byte) 0x67, (byte) 0xA5, (byte) 0x65, (byte) 0x64, (byte) 0xA4, (byte) 0x6C, (byte) 0xAC, (byte) 0xAD, (byte) 0x6D, (byte) 0xAF, (byte) 0x6F, (byte) 0x6E, (byte) 0xAE, (byte) 0xAA, (byte) 0x6A, (byte) 0x6B, (byte) 0xAB, (byte) 0x69, (byte) 0xA9, (byte) 0xA8, (byte) 0x68, (byte) 0x78, (byte) 0xB8, (byte) 0xB9, (byte) 0x79, (byte) 0xBB, (byte) 0x7B, (byte) 0x7A, (byte) 0xBA, (byte) 0xBE, (byte) 0x7E, (byte) 0x7F, (byte) 0xBF, (byte) 0x7D, (byte) 0xBD, (byte) 0xBC, (byte) 0x7C, (byte) 0xB4, (byte) 0x74,
            (byte) 0x75, (byte) 0xB5, (byte) 0x77, (byte) 0xB7, (byte) 0xB6, (byte) 0x76, (byte) 0x72, (byte) 0xB2, (byte) 0xB3, (byte) 0x73, (byte) 0xB1, (byte) 0x71, (byte) 0x70, (byte) 0xB0, (byte) 0x50, (byte) 0x90, (byte) 0x91, (byte) 0x51, (byte) 0x93, (byte) 0x53, (byte) 0x52, (byte) 0x92, (byte) 0x96, (byte) 0x56, (byte) 0x57, (byte) 0x97, (byte) 0x55, (byte) 0x95, (byte) 0x94, (byte) 0x54, (byte) 0x9C, (byte) 0x5C, (byte) 0x5D, (byte) 0x9D, (byte) 0x5F, (byte) 0x9F, (byte) 0x9E, (byte) 0x5E, (byte) 0x5A, (byte) 0x9A, (byte) 0x9B, (byte) 0x5B, (byte) 0x99, (byte) 0x59, (byte) 0x58, (byte) 0x98, (byte) 0x88, (byte) 0x48, (byte) 0x49, (byte) 0x89, (byte) 0x4B, (byte) 0x8B, (byte) 0x8A, (byte) 0x4A, (byte) 0x4E, (byte) 0x8E, (byte) 0x8F, (byte) 0x4F, (byte) 0x8D, (byte) 0x4D,
            (byte) 0x4C, (byte) 0x8C, (byte) 0x44, (byte) 0x84, (byte) 0x85, (byte) 0x45, (byte) 0x87, (byte) 0x47, (byte) 0x46, (byte) 0x86, (byte) 0x82, (byte) 0x42, (byte) 0x43, (byte) 0x83, (byte) 0x41, (byte) 0x81, (byte) 0x80, (byte) 0x40};

    byte[] bytes = new byte[]{(byte) 0xaa, (byte) 0x55, (byte) 0x01, (byte) 0x05, (byte) 0x0d, (byte) 0x31, (byte) 0x10, (byte) 0x01, (byte) 0x0c, (byte) 0x00, (byte) 0x01, (byte) 0x04, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x59};

    /**
     * 计算CRC16校验  对外的接口
     *
     * @param data 需要计算的数组
     * @return CRC16校验值
     */
    public static int calcCrc16(byte[] data) {
        return calcCrc16(data, 0, data.length);
    }

    /**
     * 计算CRC16校验
     *
     * @param data   需要计算的数组
     * @param offset 起始位置
     * @param len    长度
     * @return CRC16校验值
     */
    public static int calcCrc16(byte[] data, int offset, int len) {
        return calcCrc16(data, offset, len, 0xffff);
    }

    /**
     * 计算CRC16校验
     *
     * @param data   需要计算的数组
     * @param offset 起始位置
     * @param len    长度
     * @param preval 之前的校验值
     * @return CRC16校验值
     */
    public static int calcCrc16(byte[] data, int offset, int len, int preval) {
        int ucCRCHi = (preval & 0xff00) >> 8;
        int ucCRCLo = preval & 0x00ff;
        int iIndex;
        for (int i = 0; i < len; ++i) {
            iIndex = (ucCRCLo ^ data[offset + i]) & 0x00ff;
            ucCRCLo = ucCRCHi ^ crc16_tab_h[iIndex];
            ucCRCHi = crc16_tab_l[iIndex];
        }
        return ((ucCRCHi & 0x00ff) << 8) | (ucCRCLo & 0x00ff) & 0xffff;
    }

    /**
     * byte转16进制取低位
     * @param b
     * @return
     */
    public static String byteToHex(byte b) {
        String hex = Integer.toHexString(b & 0xFF);
        if (hex.length() < 2) {
            hex = "0" + hex;
        }
        return hex;
    }

    public static String getCountCode(String s){
        byte[] bytes = SocketServer.hexStringToByteArray(s);
        byte count = 0;
        for (byte aByte : bytes) {
            count += aByte;
        }
        return byteToHex(count);
    }

    /**
     * 16 进制的高低位倒置
     *
     * @param hex
     * @return
     */
    public static String reverseHex(String hex) {
        char[] charArray = hex.toCharArray();
        int length = charArray.length;
        int times = length / 2;
        for (int c1i = 0; c1i < times; c1i += 2) {
            int c2i = c1i + 1;
            char c1 = charArray[c1i];
            char c2 = charArray[c2i];
            int c3i = length - c1i - 2;
            int c4i = length - c1i - 1;
            charArray[c1i] = charArray[c3i];
            charArray[c2i] = charArray[c4i];
            charArray[c3i] = c1;
            charArray[c4i] = c2;
        }
        return new String(charArray);
    }

    public static void main(String[] args) {
        String s = "02 03 00 2C 00 02";
        // 得到crc16校验码
        int i = CRC16Util.calcCrc16(StringUtil.hexStringToByteArray(s));
        // 转化为16进制的string字符串
        String crc = HexUtil.toHex(i1)  //F105
        // 大小端转换
        crc = CRC16Util.reverseHex(crc) //05F1
    }
}

有时候协议中需要传入数据的长度

Java 串口通讯 Demo_数据_07


获取数据长度的代码如下,返回的长度是以16进制表示的

/**
 * 将名称以GBK编码方式计算字节数长度之后转十六进制返回
 *
 */
private static String bytesToHex(String name) {
    int length = 0;
    try {
        length = name.getBytes("GBK").length;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    StringBuilder sb = new StringBuilder(8);
    char[] b = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    while (length != 0) {
        sb = sb.append(b[length % 16]);
        length = length / 16;
    }
    String value = sb.reverse().toString();
    if (value.length() == 1) {
        value = "0" + value;
    }
    return value;
}
输入:测试名称0719
返回:0C


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
HwStpnXEg1k1