Skip to main content
 首页 » 编程设计

python之无法使用 Python 的 modbus_tk 连接到从站

2025年04月02日20yyy_WW

我目前正在尝试开发一个使用 Modbus-RTU 协议(protocol)的应用程序,我必须在 Python 2.7 中使用 modbus_tk。

我应该使用来自另一个能够通过 modbus 与微 Controller 通信的应用程序的代码。当我运行以下代码时,它可以在该应用程序上运行,但是当我在我的应用程序中运行相同的行时出现错误。

import modbus_tk 
import modbus_tk.defines as cst 
import modbus_tk.modbus_rtu as modbus_rtu 
import serial 
 
MB_Add_Status = 8 + 5001 
 
def MB_GetStatus(MB_Master_handle): 
    try: 
        status = MB_Master_handle.execute(1, cst.READ_HOLDING_REGISTERS, MB_Add_Status, 1) 
        return status 
    except modbus_tk.modbus.ModbusError, e: 
        logger.error("%s- Code=%d" % (e, e.get_exception_code())) 
 
MB_port  = 3 
masterMB = modbus_rtu.RtuMaster(serial.Serial(port='COM'+str(MB_port), baudrate=19200, bytesize=8, parity='N', stopbits=2, xonxoff=0)) 
status = MB_GetStatus(masterMB) 

首先,我需要删除构造函数调用中的参数 baudrate、bytesize 等,因为它引发了如下错误:

TypeError: __init__() got an unexpected keyword argument 'stopbits' 

但是当我们调用 execute 时,又出现了一个错误,我还没有解决:

modbus_tk.modbus.ModbusInvalidResponseError: Response length is invalid 0 

我找到的唯一文档是:https://github.com/Nobatek/modbus-tk/tree/master/docs , 但我不太明白其中的大部分内容。如果有人能首先向我解释这个错误的真正含义,以及我应该查看的位置,我们将不胜感激。非常感谢!

请您参考如下方法:

该库的正确存储库是 https://github.com/ljean/modbus-tk 它需要 PySerial 2.7