Example code for writing Modbus TCP communication program in Python

freeFree Technical Resource

This content is free to read, suitable for basic learning and search traffic.

Example code for writing Modbus TCP communication program in Python缩略图

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.

Put this resource to use in a real project?

Go to the Tool Center for message parsing, CRC verification and device debugging, or submit your requirements for selection and integration advice.

Engineer Membership

Turn this article into actionable debugging resources

After activation, you can use advanced message parsing, resource pack downloads, code examples, engineering cases and priority technical support, suitable for real project delivery.

Unlimited Advanced Tools
Resource & Code Packs
Complete Engineering Case Library
Priority Technical Support

Leave a Reply

Your email address will not be published. Required fields are marked *.