Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python pyserial 2.7和USB中继模块_Python_Pyserial - Fatal编程技术网

Python pyserial 2.7和USB中继模块

Python pyserial 2.7和USB中继模块,python,pyserial,Python,Pyserial,我已经购买了两个lctech-inc.com 011801 USB中继模块。我试图用python和pyserial来控制它们。该模块显示为USB串行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,

我已经购买了两个lctech-inc.com 011801 USB中继模块。我试图用python和pyserial来控制它们。该模块显示为USB串行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来关闭继电器,而不是发送字符串“开”和“关”

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

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

回答:

我需要编码为十六进制。这就是成功的原因

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()

我尝试了serPort.write(“0xA0 0x01”),但没有成功。还有其他建议吗?不要引用。另外,尝试只发送0xA0,然后再发送0x01,并再次调用writeI。我尝试了这两种方法,但仍然没有成功。对于Python 3.6.0:serPort.write(codecs.decode(b'A00101A2','hex'))