ModbusRTU从站扫描工具 python实现
扫描指定串口下,有哪些modbusRTU服务端[1-247]
参考连接:https://pymodbus.readthedocs.io/en/dev/source/examples.html
from pymodbus.client import ModbusSerialClient as ModbusClient from pymodbus.exceptions import ModbusIOException, ConnectionException, NoSuchSlaveException import time def read_holding_registers(client, slave_address): """尝试读取指定从站的保持寄存器40001的数据""" try: # 使用client.read_holding_registers函数读取保持寄存器 result = client.read_holding_registers(0, 1, slave_address) if isinstance(result, ModbusIOException): raise result # 重新抛出异常以便在外部统一处理 if isinstance(result, NoSuchSlaveException): raise result # 打印从站号和读取到的数据 print(f"Slave {slave_address}: {result.registers[0]}") except NoSuchSlaveException: # 如果没有这样的从站,则捕获异常并打印信息 print(f"Slave {slave_address} not found.") except ModbusIOException as e: # 其他Modbus通信错误 print(f"Error communicating with Slave {slave_address}: {e}") if __name__ == "__main__": # 初始化串口客户端,这里以9600波特率、8数据位、无校验、1停止位为例 client = ModbusClient(port='COM1', baudrate=9600, bytesize=8, parity='N', stopbits=1) # 连接到Modbus RTU设备 if client.connect(): print("Connected to Modbus device.") # 循环遍历从站地址1至247 for slave_address in range(1, 247): read_holding_registers(client, slave_address) time.sleep(0.200) # 延迟200毫秒 # 关闭连接 client.close() else: print("Failed to connect to the Modbus device.")
__EOF__
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 本地部署 DeepSeek:小白也能轻松搞定!
· 如何给本地部署的DeepSeek投喂数据,让他更懂你
· 在缓慢中沉淀,在挑战中重生!2024个人总结!
· 从 Windows Forms 到微服务的经验教训
· 李飞飞的50美金比肩DeepSeek把CEO忽悠瘸了,倒霉的却是程序员
2018-05-16 使用WinDbg分析蓝屏dump原因