public-profile
public-profile

Reputation: 17

Why is b'\x02' not the same as the value 2 or int(2) in Python?

I have a PC sending the byte value 2 to a Raspberry Pi.

But I can't figure out why the Python program does not evaluate to true when it receives the value.

If I print the values received it writes b'\x02' as output.

import serial

def GetSerialData():
    x = ser.inWaiting()
    if x > 0:
        received_data = ser.read(x)
        print (received_data)
    return x


ser = serial.Serial ("/dev/ttyAMA0", 9600)
try:
    while True:
        SData = GetSerialData ()
        if ( SData == b'\x02'):
            print ("Ok - value is 2")

except KeyboardInterrupt:
    ser.close()

Upvotes: 1

Views: 9076

Answers (2)

user4734394
user4734394

Reputation:

\x02 is ASCII code for hex 02, which is STX (start of text). \x32 is the ASCII for the digit 2.
If SData is an integer or any non-(binary) string, remember to convert it to string with str(SData).
Also, in general, b'A' != 'A'. You want to use .encode('ascii') to convert a Python string to an ASCII binary string.

>>> binary_A_from_string = 'A'.encode('ascii')
>>> binary_A_from_string
b'A'

>>> binary_A = '\x41' # ASCII 41 (dec 65) is 'A'
>>> binary_A
b'A'

>>> binary_A == 'A'
False
>>> binary_A == binary_A_from_string
True

This is because Python sees binary ASCII strings as different from standard Python strings.

Also, make sure that the information read is actually one byte long.

Upvotes: 1

Kevin
Kevin

Reputation: 76234

Your GetSerialData function does not appear to actually return the serial data. It prints the serial data, but then you never refer to received_data after that, and instead return x, which appears to be an integer representing the size of the response.

Instead of returning x, try returning received_data.

def GetSerialData():
    x = ser.inWaiting()
    if x > 0:
        return ser.read(x)
    else:
        return b"" #or whatever value is appropriate when no data has been sent yet

Upvotes: 1

Related Questions