使用pymodbus实现 tcp通讯进行读写数据
下面是一个使用pymodbus实现tcp通讯进行读写数据的示例代码:
from pymodbus.client.sync import ModbusTcpClient
# 创建Modbus TCP客户端
client = ModbusTcpClient('localhost', port=502)
# 连接到Modbus TCP服务器
client.connect()
# 读取保持寄存器(0x03)中的数据
result = client.read_holding_registers(address=0, count=2, unit=1)
# 打印读取到的数据
print(result.registers)
# 写入保持寄存器(0x03)中的数据
client.write_register(address=0, value=1234, unit=1)
# 断开与Modbus TCP服务器的连接
client.close()
在上面的示例中,我们使用ModbusTcpClient类创建了一个Modbus TCP客户端,并使用connect()方法连接到Modbus TCP服务器。然后,我们使用read_holding_registers()方法读取保持寄存器中的数据,并使用write_register()方法写入保持寄存器中的数据。最后,我们使用close()方法断开与Modbus TCP服务器的连接。
原文地址: https://www.cveoy.top/t/topic/bIsA 著作权归作者所有。请勿转载和采集!