Modbus RTU

一是什么

工业串口 问答 协议 走RS485/RS232,主站问,从站答

RTU(Remote Terminal Unit)远程终端单元

二RTU帧格式

从站地址 功能码 数据区 CRC16 校验
1 字节 1 字节 N 字节 2 字节(低字节在前)

三串口基础

3.1引用

cs 复制代码
using System.IO.Ports;

3.2串口参数(必须和从站完全一致!)

cs 复制代码
SerialPort sp = new SerialPort("COM1")
{
    BaudRate=9600,
    DataBits =8, 
    Parity = StopBits.One,
    ReadTimeout = 1000,
    WriteTiemout = 1000
};
sp.Open();
sp.Close();

3.3CRC校验(Modbus)

发之前算,收之后验。 CRC 不包含自己的两个字节。

cs 复制代码
// Modbus CRC16
public static ushort Crc16(byte[] data, int len)
{
    ushort crc = 0xFFFF;
    for (int i = 0; i < len; i++)
    {
        crc ^= data[i];
        for (int j = 0; j < 8; j++)
        {
            if ((crc & 0x0001) != 0)
                crc = (ushort)((crc >> 1) ^ 0xA001);
            else
                crc >>= 1;
        }
    }
    return crc;
}

使用

cs 复制代码
byte[] frame = new byte[] { 0x01, 0x03, 0x00, 0x00, 0x00, 0x02 };
ushort crc = Crc16(frame, frame.Length);
// 拼到后面:低字节在前
byte[] sendBuf = frame.Concat(new byte[] { (byte)crc, (byte)(crc >> 8) }).ToArray();

四发送RTU请求

目标:从站地址 1,读寄存器 0,数量 2

cs 复制代码
// 1. 构造帧(不含 CRC)
byte[] req = new byte[]
{
    0x01,       // 从站地址
    0x03,       // 功能码:读保持寄存器
    0x00, 0x00, // 起始地址 0
    0x00, 0x02  // 寄存器数量 2
};

// 2. 加 CRC
ushort crc = Crc16(req, req.Length);
byte[] send = new byte[req.Length + 2];
Buffer.BlockCopy(req, 0, send, 0, req.Length);
send[req.Length] = (byte)crc;
send[req.Length + 1] = (byte)(crc >> 8);

// 3. 串口发送
sp.Write(send, 0, send.Length);

五C# 接收 RTU 应答

应答帧格式(03 应答)

从站地址 03 字节数 N 数据1 数据2 ... CRC低 CRC高

接收 + 校验 + 解析

cs 复制代码
// 收 1 帧(先按最大长度收,再处理)
byte[] recvBuf = new byte[256];
int len = sp.Read(recvBuf, 0, recvBuf.Length);
byte[] frame = recvBuf.Take(len).ToArray();

// 1. 校验 CRC
if (frame.Length < 2) return;
ushort recvCrc = (ushort)(frame[frame.Length - 2] | (frame[frame.Length - 1] << 8));
ushort calcCrc = Crc16(frame, frame.Length - 2);
if (recvCrc != calcCrc)
{
    Console.WriteLine("CRC 错误");
    return;
}

// 2. 检查地址、功能码
byte slaveId = frame[0];
byte func = frame[1];
if (slaveId != 1 || func != 0x03)
{
    Console.WriteLine("应答不匹配");
    return;
}

// 3. 解析数据
byte numBytes = frame[2];
for (int i = 0; i < numBytes; i += 2)
{
    ushort val = (ushort)(frame[3 + i] << 8 | frame[3 + i + 1]);
    Console.WriteLine("寄存器值:" + val);
}

完整示例

cs 复制代码
using System;
using System.IO.Ports;
using System.Linq;

class ModbusRtuDemo
{
    static SerialPort sp;

    static void Main()
    {
        sp = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One)
        {
            ReadTimeout = 1000,
            WriteTimeout = 1000
        };
        sp.Open();
        Console.WriteLine("串口打开");

        // 发:从站1,读寄存器0,2个
        byte[] req = { 0x01, 0x03, 0x00, 0x00, 0x00, 0x02 };
        ushort crc = Crc16(req, req.Length);
        byte[] send = req.Concat(new byte[] { (byte)crc, (byte)(crc >> 8) }).ToArray();
        sp.Write(send, 0, send.Length);
        Console.WriteLine("已发送:" + BitConverter.ToString(send));

        // 收
        byte[] buf = new byte[256];
        int len = sp.Read(buf, 0, buf.Length);
        byte[] frame = buf.Take(len).ToArray();
        Console.WriteLine("收到:" + BitConverter.ToString(frame));

        // CRC 校验
        ushort rCrc = (ushort)(frame[frame.Length - 2] | (frame[frame.Length - 1] << 8));
        ushort cCrc = Crc16(frame, frame.Length - 2);
        Console.WriteLine(rCrc == cCrc ? "CRC 正确" : "CRC 错误");

        sp.Close();
    }

    public static ushort Crc16(byte[] data, int len)
    {
        ushort crc = 0xFFFF;
        for (int i = 0; i < len; i++)
        {
            crc ^= data[i];
            for (int j = 0; j < 8; j++)
            {
                if ((crc & 0x0001) != 0)
                    crc = (ushort)((crc >> 1) ^ 0xA001);
                else
                    crc >>= 1;
            }
        }
        return crc;
    }
}

六第三方库

NModbus4/新Modbus

NModbus4 示例

cs 复制代码
using Modbus.Device;
using System.IO.Ports;

var sp = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
sp.Open();
var master = ModbusFactory.CreateRtuMaster(sp);
ushort[] regs = master.ReadHoldingRegisters(1, 0, 2); // 从站1,地址0,2个
相关推荐
古法老登瞎折腾9 小时前
大数据智能运维实战(十一):运维 MCP 的工程化——权限、限流、审计与错误处理
java·大数据·运维·spring ai·mcp
琥珀.9 小时前
mysql中json数组转列表查询
linux·运维·服务器
dawnsky.liu10 小时前
在 RHEL 中使用 goose 实现远程主机管理
linux·运维·ai
Linux运维技术栈12 小时前
CVE-2026-91403 高危漏洞修复:Rocky Linux 9 多版本 JDK 环境清理实操
java·linux·运维
云边云科技_云网融合12 小时前
连锁门店组网怎么做?SD-WAN 多分支组网的架构选型、部署与成本结构
服务器·数据库·php
云上先途112 小时前
企业 AI 服务部署周期多久,会不会影响原有业务运转?
大数据·运维·人工智能
网络小江13 小时前
组网第35课:静态路由——下一跳、出接口、默认路由、浮动静态与黑洞路由
服务器·网络·默认路由·黑洞路由·浮动静态路由
执伞人ONLY13 小时前
AI知识库自动化知识加工没做对,人工整理永远追不上知识产生
运维·人工智能·自动化
slongzhang_13 小时前
linux 递归删除源码文件|递归删除目录下 *.js,但排除 *.min.js
linux·开发语言·javascript
叼烟扛炮13 小时前
Linux 学习笔记(三十三):线程互斥——互斥锁(Mutex)与死锁
linux·运维·服务器·笔记·学习·1024程序员节