在pymodbus中,write_coil函数用于向Modbus从机写入单个线圈的值。该函数将返回一个包含以下值的Response对象:

  • Function code:写入线圈功能码(0x05)。
  • Address:写入的线圈地址。
  • Value:写入线圈的值(True或False)。

如果写入成功,Response对象的isError属性将为False,否则为True。如果isError为True,Response对象的exceptionCode属性将包含Modbus从机返回的异常代码。

以下是一个使用write_coil函数并解析返回值的示例:

from pymodbus.client.sync import ModbusTcpClient

# connect to Modbus TCP server
client = ModbusTcpClient('localhost', port=502)
client.connect()

# write a coil value
address = 0x0001
value = True
response = client.write_coil(address, value)

# parse the response
if response.isError():
    print("Error: " + str(response))
else:
    print("Write success:")
    print("Function code: " + str(response.function_code))
    print("Address: " + str(response.address))
    print("Value: " + str(response.value))

# close the connection
client.close()

在上面的示例中,如果写入成功,将打印以下内容:

Write success:
Function code: 5
Address: 1
Value: True

如果写入失败,将打印类似以下内容的错误消息:

Error: Modbus Error: [Input/Output] Modbus Error: [Invalid Message] Incomplete message received, expected at least 8 bytes (0 received)
pymodbus解析 write_coil返回值

原文地址: https://www.cveoy.top/t/topic/bLMt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录