1. 安装pymodbus:
pip install pymodbus
  1. 编写代码:
from pymodbus.client.sync import ModbusTcpClient

# 创建TCP客户端
client = ModbusTcpClient('localhost', port=502)

# 连接到服务器
client.connect()

# 读取保持寄存器
result = client.read_holding_registers(0, 1, unit=1)
print(result.registers)

# 写入保持寄存器
client.write_registers(0, [12345], unit=1)

# 断开连接
client.close()

在上面的代码中,我们使用ModbusTcpClient类创建了一个TCP客户端,然后通过connect()方法连接到Modbus服务器。接着,我们使用read_holding_registers()方法读取保持寄存器的值,并使用write_registers()方法将新值写入保持寄存器。最后,我们使用close()方法断开与服务器的连接。

需要注意的是,在读取或写入寄存器时,需要指定寄存器的地址、长度和单元标识符。单元标识符是指Modbus网络中的从站地址,通常为1到247之间的整数。在本例中,我们假设从站地址为1,并读取或写入地址为0的保持寄存器。

使用pymodbus 实现tcp通讯

原文地址: https://www.cveoy.top/t/topic/bIJQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录