Example code for writing Modbus TCP communication program in Python
# 导入pymodbus库
from pymodbus.client.sync import ModbusTcpClient
# 创建Modbus TCP客户端对象
client = ModbusTcpClient('127.0.0.1', port=502)
# 连接Modbus TCP服务器
client.connect()
# 读取保持寄存器的数据
result = client.read_holding_registers(address=0, count=1, unit=1)
# 处理读取结果
if result.isError():
print("读取保持寄存器失败:{0}".format(result))
else:
print("读取保持寄存器成功:{0}".format(result.registers[0]))
# 写入保持寄存器的数据
result = client.write_register(address=0, value=123, unit=1)
# 处理写入结果
if result.isError():
print("写入保持寄存器失败:{0}".format(result))
else:
print("写入保持寄存器成功")
# 关闭Modbus TCP客户端连接
client.close()
The above code has been usedpymodbusThe library implements operations such as connecting to Modbus TCP servers, reading, writing, and holding registers. Installation is required before usepymodbusLibrary.
It should be noted that in practical applications, it is necessary to configure according to specific Modbus device addresses, function codes, data types, and other parameters, and perform data reading and writing according to actual needs. Meanwhile, for complex Modbus applications, program optimization and hardware design may be necessary to ensure stable and reliable communication.
Leave a Reply