如何在python中测试串口上的十六进制输出

时间:2012-10-17 07:51:20

标签: python serial-port hex

当我通过串行发送命令时,从站以十六进制序列响应,即:

这个系列:

05 06 40 00 02 05 F6 5C

给了我

05 07 40 05 02 05 71 37 FF

响应始终以FF字节结束。所以我想把字节读入缓冲区,直到我遇到FF。应该打印缓冲区并且函数应该返回。

import serial

s_port = 'COM1'
b_rate = 2400

#method for reading incoming bytes on serial
def read_serial(ser):
    buf = ''
    while True:
        inp = ser.read(size=1) #read a byte
        print inp.encode("hex") #gives me the correct bytes, each on a newline
        buf = buf + inp #accumalate the response
        if 0xff == inp.encode("hex"): #if the incoming byte is 0xff
            print inp.encode("hex") # never here
            break
    return buf   

#open serial
ser = serial.Serial(
    port=s_port,
    baudrate=b_rate,
    timeout=0.1
)

while True:

    command = '\x05\x06\x40\x00\x02\x05\xF6\x5C' #should come from user input
    print "TX: "
    ser.write(command)
    rx = read_serial(ser)
    print "RX: " + str(rx)

给了我:

TX: 
05
07
40
05
02
05
71
37
ff

为什么这种情况从未得到满足?

1 个答案:

答案 0 :(得分:1)

这是因为你在比较苹果和橘子。 inp.encode("hex")返回一个字符串。假设你读了"A"这封信。 "A".encode("hex")返回字符串"41"0x41 != "41"。你应该这样做:

if '\xff' == inp:
    ....

或者,使用inpord()转换为数字:

if 0xff == ord(inp):
    ....

然后它应该按预期工作。