modbus协议
Modbus通信协议由Modicon公司(现已经为施耐德公司并购,成为其旗下的子品牌)于1979年发明的,是全球最早用于工业现场的总线规约。由于其免费公开发行,使用该协议的厂家无需缴纳任何费用,Modbus通信协议采用的是主从通信模式(即Master/Slave通信模式),其在分散控制方面应用极其广泛,从而使得Modbus协议在全球得到了广泛的应用。
Modbus通信协议具有多个变种,其具有支持串口(主要是RS-485总线),以太网多个版本,其中最著名的是Modbus RTU,Modbus ASCII和Modbus TCP三种。其中Modbus RTU与Modbus ASCII均为支持RS-485总线的通信协议,其中Modbus RTU由于其采用二进制表现形式以及紧凑数据结构,通信效率较高,应用比较广泛。而Modbus ASCII由于采用ASCII码传输,并且利用特殊字符作为其字节的开始与结束标识,其传输效率要远远低于Modbus RTU协议,一般只有在通信数据量较小的情况下才考虑使用Modbus ASCII通信协议,在工业现场一般都是采用Modbus RTU协议,一般而言,大家说的基于串口通信的Modbus通信协议都是指Modbus RTU通信协议。
Modbus can work on top of RS-232, RS-485 or TCP/IP over Ethernet.
- Modbus RTU (binary over serial link)
- Modbus ASCII (text-based over serial link)
- Modbus TCP (binary over TCP/IP transport)
Modbus RTU Protocol
Modbus RTU is a master-slave protocol. This means that only one device, the master, is allowed to initiate communication. The other devices on the network are called slaves and they may only respond to the requests. Modbus RTU can support up to 247 devices on the same physical network. It’s possible to modify the protocol to support more slaves, but in most applications the standard limit of slaves if enough.
Modbus RTU encodes data as binary and uses big-endian encoding for 16-bit values. This means that the most significant byte of a 16-bit word is sent first.
There are only two data types in Modbus: coils and registers.
Coils are simply single bits. The bits can be ON (1) or they can be OFF (0). Some coils represent inputs, meaning they contain the status of some physical discrete input. Or they represent outputs, meaning that they hold the state of some physical discrete output signal.
Registers are simply 16-bit unsigned register data. Registers can have a value from 0 to 65535 (0 to FFFF hexadecimal). There is no representation for negative values, no representation for values greater than 65535, and no representation for real data like 200.125.
Registers are grouped into Input Registers and Holding Registers. Like Input Coils, Input Registers report the state of some external input as a value between 0 and 65535. The original intent of an Input Register was to reflect the value of some analog input. It is a digital representation of an analog signal like a voltage or a current. Most Modbus devices today are not I/O devices, and Input Registers simply function identically to Holding Registers.
| 地址码 | 功能码 | 数据区 | 错误校验码 |
|---|---|---|---|
| 8位 | 8位 | N × 8位 | 16位 |
发送数据
01 03 01 8E 00 04 25 DE |
返回数据
01 03 08 00 01 00 01 00 01 00 01 28 D7 |
|
ModBus 功能码与数据类型对应表:
RTU 方式读取整数据的例子:
解析一下:主机发送指令,访问从站地址为1,使用功能码03(读保持寄存器),起始地址高8位、低8位:表示想读取的模拟量的起始地址(起始地址为0)。比如例子中的起始地址为38,十进制为:56。寄存器数量高8位、低8位:表示从起始地址开始读多少个模拟量。例子中为1个模拟量。注意,在返回的信息中一个模拟量需要返回两个字节。错误校验为CRC校验。
从站应答:设备地址和命令号和上面的相同。返回的字节数:表示数据的字节个数,也就是数据1,2…n中的n的值。例子中返回了1个模拟量的数据,因为一个模拟量需要2个字节所以共2个字节。数据高低字节:41和24代表返回的1个模拟量的值,即十进制的16676。错误校验为CRC校验。