Read Data from Sensor Port, Convert Datastream

Hi I would like to convert Sensordata but is not working.

what is wrong with the code:

while True:
ser = serial.Serial('/dev/ttyUSB0',115200, timeout = 1)
b = ser.readline()         # read a byte string
print(b)
string_n = b.decode()  # decode byte string into Unicode  
    #string = string_n.rstrip() # remove n and r
flt = string_n        # convert string to float
print(flt)
data.append(flt)           # add to the end of data list
time.sleep(0.1)            # wait (sleep) 0.1 seconds

ab += 1 
ph = 1
print (ab)
ser.close()

I am getting:

/dev/ttyUSB0
connected to: /dev/ttyUSB0 pi b'xaax01x03x00xaexaax02x03x00xafxaax01x03x00xaexaax00x03x00xadxaax02x03x00xafxaax01x03x00xaexaax00x03x00xadxaax01x03x00xaexaax02x03x00xafxaax01x03x00xaexaax02x03x00xafxaax00x03x00xadxaax01x03x00xaexaax02x03x00xafxaax01x03x00xaexaax02x03x00xafxaax01x03x00xaexaax02x03x00xafxaax01x03x00xaexaax02x03x00xafxaax00x03x00xad' Traceback (most recent call last): File "/home/pi/wave1.py", line 35, in string_n = b.decode() # decode byte string into Unicode
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xaa in position 0: invalid start byte

I Have this Sensor: https://wiki.seeedstudio.com/Microwave-Sensor-24GHz-Doppler-Radar-Motion-Sensor-MW2401TR11/

I have a raspberry not a arduino or an Developmentboard.

can you help me to convert the data?

Best regards W

Answer

The first problem you have is that the sensor is spitting out into the serial for a while before you first read it. In the sample code on the link you provided it reads out 5 bytes and makes sure the first one is xaa.

This means for you that you want to read it once at the start and throw away the result. Then read it again, 5 bytes at a time if you can.

Another way to do it is to just grab the last 5-bytes and throw away the rest. Also verify the read starts with xaa then use each byte as in that sample program.

data = b'xaax01x03x00xae' 
       b'xaax01x03x00xae' 
       b'xaax02x03x00xaf' 
       b'xaax00x03x00xad'

last_report = data[-5:]
print(last_report)
print(last_report[0])
if last_report[0] == 170:  # b'xaa':
    print('valid reading:')
    state_code = last_report[1]
    gear_code = last_report[2]
    delay_code = last_report[3]
    check_code = last_report[4]
    print(f' state_code={state_code}n gear_code={gear_code}n delay_code={delay_code}n check_code={check_code}n')

output:

b'xaax00x03x00xad'
170
valid reading:
 state_code=0
 gear_code=3
 delay_code=0
 check_code=173