pyserial 2.7 和 USB 中继模块

pyserial 2.7 and USB Relay module

我购买了两个 lctech-inc.com 011801 USB 继电器模块。我试图用 python 和 pyserial 来控制它们。该模块确实显示为 USB-SERIAL CH340 (COM5)。支持信息说:

Communication baud rate: 9600bps; Protocol: start: 0 x A0, 
switch address: 0 x 01, operation data: 0 x 00 (off), 0 x 01 (on), 
check code: on: A0 01 01 A2, off: A0 01 00 A1

我正在使用以下 python 代码来打开继电器,但它不起作用:

    import sys
    import serial
    portName = "COM5"
    relayNum = "1"
    relayCmd = "on"
    #Open port for communication    
    serPort = serial.Serial(portName, 9600, timeout=1)
    #Send the command
    serPort.write("relay "+ str(relayCmd) +" "+ str(relayNum) + "\n\r")
    print "Command sent..."
    #Close the port
    serPort.close()

只要我使用正确的 COM 端口,COM5,我就不会收到任何错误。

有什么建议吗?任何帮助将不胜感激。 TIA

看起来你需要发送字节 0x01 来打开继电器和 0x00 来关闭它,而不是字符串 "on" 和 "off".

尝试serPort.write(0x01)打开继电器。

编辑:您可能还需要先发送起始字节 0xA0。

答案:

我需要编码为 HEX。这是有效的方法。

import serial
port = 'COM3'
ser = serial.Serial(port, 9600, timeout=1)
# To close relay (ON)
code = 'A00101A2'
ser.write(code.decode('HEX'))
ser.close()
# To open relay (OFF)
code = 'A00100A1'
ser.write(code.decode('HEX'))
ser.close()