Python通过TCP读取ModBus的数据

买了个485/串口转TCP的转接模块,能够把485 modbus的数据直接转换为TCP数据(类似串口服务器),直接读485的数据可以用modbus_tk的RtuMaster,读modbus_tcp的数据也可以用TcpMaster,但是直接把485转tcp的就不知道用哪个了,因为数据帧是不一样的。

可以先安装相关的包

pip install modbus_tk modbus_tcprtu

然后这样

import modbus_tk.defines as cst
from modbus_tcprtu import TcpRtuMaster

# create a master
master = TcpRtuMaster(host='127.0.0.1', port=9001)
master.set_timeout(2)
for i in range(10):
    # read data from modbus
    # just use as modbus_tk.Master
    print(i, master.execute(1, cst.READ_HOLDING_REGISTERS, 0, i + 1))

你可能感兴趣的:(嵌入式,tcp/ip,modbus,python)