【C#】构造协议帧通过串口下发

发布于:2025-04-01 ⋅ 阅读:(19) ⋅ 点赞:(0)

构造一个“协议帧”,打包串口/网络通信帧头部结构的核心部分


🔧 代码:

List<byte> frame = new List<byte>();

// 1. 固定帧头
frame.AddRange(BitConverter.GetBytes(0x0130));        // 帧头 (4B)
frame.AddRange(BitConverter.GetBytes((ushort)22));        // 帧长度 (2B)
frame.AddRange(BitConverter.GetBytes((ushort)type));      // 帧类型 (2B)
frame.AddRange(BitConverter.GetBytes((ushort)0x0000));    // 序号 (2B)

🧠 一行一讲:


🔹 List<byte> frame = new List<byte>();

🔹 创建一个动态的字节集合,用来组装整个“数据帧”。
你会不断往 frameAddRange() 塞字节,构造完整通信包。


🔹 frame.AddRange(BitConverter.GetBytes(0x0130));

🔹 加入帧头字段:固定值 0x0130

含义 字节长度 用途
帧头 0x0130 2 字节 用于帧识别、同步,开头校准

输出的字节是 小端格式(在内存中实际是):[0x30, 0x01 ]


🔹 frame.AddRange(BitConverter.GetBytes((ushort)22));

🔹 加入帧大小字段(2 字节)
这里填的是:22 字节,表示整个帧的总长度(你可以改成动态计算)

例子:220x0016 → 小端字节:[0x16, 0x00]


🔹 frame.AddRange(BitConverter.GetBytes((ushort)type));

🔹 加入帧类型字段(2 字节)
你会传入不同的 type,比如:

类型名
参数设置 0x2001
参数读取 0x2002
启动激励 0x3001

比如 type = 0x2002 → 字节是 [0x02, 0x20](小端)


🔹 frame.AddRange(BitConverter.GetBytes((ushort)0x0000));

🔹 加入序号字段(2 字节)

  • 通常用于帧编号、请求/响应匹配
  • 你现在写死为 0x0000,后续如果你要支持多帧队列、自动序号,也可以这里动态传参

✅ 最终结果:

这段代码打包完的 frame 内容是:

字段 内容 字节数 示例值 (小端)
帧头 0x0130 2 30 01
帧长度 0x0016 2 16 00
帧类型 type(传参) 2 02 40(如0x4002)
序号 0x0000 2 00 00

共:8 字节


👇 后续 还可以追加:

  • CRC 校验(2 字节)
  • 数据段(2字节参数编号 +2字节写入值)
  • 帧尾CRC(2 字节)



网站公告

今日签到

点亮在社区的每一天
去签到