When i send a command over serial, the slave responds with a hexidecimal sequence, i.e.:
this series:
05 06 40 00 02 05 F6 5C
gives me
05 07 40 05 02 05 71 37 FF
The response always ends with the FF byte. So i want to read the bytes into a buffer untill i encounter FF. Than the buffer should be printed and the function should return.
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)
gives me:
TX:
05
07
40
05
02
05
71
37
ff
Why is the condition never met?
It’s because you’re comparing apples and oranges.
inp.encode("hex")returns a string. Let’s say you read the letter"A"."A".encode("hex")returns the string"41"and0x41 != "41". You should either do:Or, convert
inpinto a number usingord():Then it should work as expected.