0
當我通過串口發送命令,從一個十六進制序列響應,即:如何測試爲十六進制輸出串行端口上的蟒蛇
這個系列:
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
爲什麼從來沒有遇到過的情況?
上一個工作對我來說,下一個抱怨ORD需要一個字符串,它收到的長度爲0 – jorrebor
這聽起來像一串'inp'可以是一個空字符串,然後('「」')...這是預期的嗎?如果是這樣,字符串匹配(第一個選項)可能會更好。儘管如此,你可能想要做一些特殊的事情。我假設你使用的是pyserial,而一個空字符串通常意味着操作超時。 – jszakmeister
是的,字符串比答案更好地匹配數字。感謝您的輸入 – jorrebor