2

I'm trying to test the data received from a serial port and can't seem to get it right. I need to check if the first byte received in a packet is 0xBE thus:

#ser is instance of pyserial serial object
data=ser.read(5)
print "serial RX: " + binascii.b2a_hex(data)
if data[0] != 0xBE:
    print"wrong value"

always prints:

serial RX: beef000008
wrong value

Even though the binary to ascii print shows that the correct value has been received.

Where am i going wrong in this really basic task?

Thanks, Robin.

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
user2512377
  • 501
  • 1
  • 3
  • 9
  • well why don't you print out data[0], data[1], data[2] and data[3] and see what is there? – MK. Jun 22 '13 at 20:16
  • if I print data[0] I get a 3/4 character which is chr(0xBE) so it's the right value (as confirmed by the bin2ascii also) but serial.read() should return a bytes object in python >= 2.4 according to the docs. is it really a string perhaps? – user2512377 Jun 22 '13 at 20:20
  • I think bytes are sort of strings. just reading about it now. but in any case the fix for your situation is to compare data[0] to chr(0xbe) then :) – MK. Jun 22 '13 at 20:24
  • you can test the type of your byte using print type(data[0]) to be sure that what you're having is what the documentation says. – zmo Jun 22 '13 at 20:37

1 Answers1

3

from pyserial's documentation:

Changed in version 2.5: Returns an instance of bytes when available (Python 2.6 and newer) and str otherwise.

so I tested:

>> bytes(0xbe) == 0xbe
False

but if you convert it to int:

>> int(bytes(0xbe)) == 0xbe
True

as this stackoverflow question shows, the bytes type is included by [PEP-31373]. It is like a bytearray for python3, but just an alias for str in python2.

So, basically, just treat pyserial's output as a str while you're doing python2 code.

Community
  • 1
  • 1
zmo
  • 24,463
  • 4
  • 54
  • 90