当我通过串行发送命令时,从机以十六进制序列响应,即:
这个系列:
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
为什么条件从未满足?