当我通过串口发送命令时,从机以十六进制序列响应,即:
本系列:
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为什么条件永远不会满足?
发布于 2012-10-17 15:58:49
这是因为你在比较苹果和橙子。inp.encode("hex")返回一个字符串。假设你读了"A"这封信。"A".encode("hex")返回字符串"41"和0x41 != "41"。您应该这样做:
if '\xff' == inp:
....或者,使用ord()将inp转换为数字
if 0xff == ord(inp):
....那么它应该会像预期的那样工作。
https://stackoverflow.com/questions/12929593
复制相似问题