python Modbus 进行通讯时抛出Modbus Error: Exception code = 2
源码:
import modbus_tk from modbus_tk import modbus_tcp import modbus_tk.defines as cst PORT = 'com1' def main(): """main""" logger = modbus_tk.utils.create_logger(name="console", record_format="%(message)s") # Create the server server = modbus_tcp.TcpServer(address="127.0.0.1", port=502) try: logger.info("running...") logger.info("enter 'quit' for closing the server") server.start() slave_1 = server.add_slave(1) slave_1.add_block('0', cst.HOLDING_REGISTERS, 0, 4) slave_1.set_values('0', 0, [1,2,3,1]) except Exception as exc: print(str(exc)) server.stop() if __name__ == "__main__": main() MASTER = modbus_tcp.TcpMaster('127.0.0.1', 502) hold_value = MASTER.execute(slave=1, function_code=cst.READ_HOLDING_REGISTERS, starting_address=0, quantity_of_x=10) print(hold_value)
或者打开应用端:
![](https://img2022.cnblogs.com/blog/1973860/202205/1973860-20220520180445218-1948726155.png)
执行后抛出异常:
Modbus Error: Exception code = 2 Modbus Error: Exception code = 2 Modbus Error: Exception code = 2 Modbus Error: Exception code = 2 Modbus Error: Exception code = 2
问题原因:
浅显分析:
slave_1.add_block('0', cst.HOLDING_REGISTERS, 0, 4) 此处相当于创建了4个设备
hold_value = MASTER.execute(slave=1, function_code=cst.READ_HOLDING_REGISTERS, starting_address=0, quantity_of_x=10) 代码中 starting_address=0, quantity_of_x=10 访问了10个设备,大于创建的设备数
Modbus Polls中访问的设备数大于创建的设备数
专业分析:
查询中接收到的数据地址不是从属服务器允许的地址。更具体地说,参考号和传输长度的组合是无效的。
总结:
访问的设备数必须小于等于创建的数量