我改进了你的代码 .isError() pymodbus中的方法如下:
.isError()
from pymodbus.client.sync import ModbusSerialClient as ModbusClient from pymodbus.constants import Endian from pymodbus.payload import BinaryPayloadDecoder def error_checker(instance): if not instance.isError(): '''.isError() implemented in pymodbus 1.4.0 and above.''' decoder = BinaryPayloadDecoder.fromRegisters( instance.registers, byteorder=Endian.Big, wordorder=Endian.Big ) return decoder.decode_32bit_float() else: # Error handling. return None def length(x): client = ModbusClient( method='rtu', port='/dev/ttyUSB0', timeout=2, stopbits=1, bytesize=8, parity='N', baudrate=9600 ) try: client.connect() rr = client.read_holding_registers(address=1, count=4, unit=x) c = error_checker(rr) print("length: ", c) rr = client.read_holding_registers(address=7, count=4, unit=x) d = error_checker(rr) print("speed: ", d) return c, d except Exception as exc: print(exc) finally: client.close()