Modbus TCP使用代码示例
时间: 2024-05-14 07:15:39 浏览: 157
以下是Modbus TCP使用代码示例:
```python
import socket
# 设置Modbus TCP的IP地址和端口
TCP_IP = '192.168.1.1' # Modbus TCP IP 地址
TCP_PORT = 502 # Modbus TCP 端口
# 创建 TCP 连接
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
# 构造读单个寄存器的命令报文
def build_single_reg_read_msg(addr):
msg = bytearray(12)
msg[0] = 0x00 # 事务 ID 高位字节
msg[1] = 0x01 # 事务 ID 低位字节
msg[2] = 0x00 # 协议标识符高位字节
msg[3] = 0x00 # 协议标识符低位字节
msg[4] = 0x00 # 长度高位字节
msg[5] = 0x06 # 长度低位字节
msg[6] = 0x01 # 单元标识符
msg[7] = 0x04 # 读取单个寄存器功能码
msg[8] = (addr >> 8) & 0xff # 内存地址高位字节
msg[9] = addr & 0xff # 内存地址低位字节
msg[10] = 0x00 # 寄存器数量高位字节
msg[11] = 0x01 # 寄存器数量低位字节
return msg
# 发送读单个寄存器的命令报文到服务器
req = build_single_reg_read_msg(0x0000)
s.send(req)
# 接收并解析命令响应报文
res = s.recv(1024)
print(res)
# 关闭 TCP 连接
s.close()
```
这段代码使用 Python socket 库实现了 Modbus TCP 的读单个寄存器功能,将地址为 0x0000 的寄存器的值读取出来并打印到标准输出。用户可以根据自己的需求修改代码来实现其它 Modbus TCP 的功能。
阅读全文
相关推荐















