B.T
B.T

Reputation: 551

Python and Arduino Serial, decoding issue

I have a simple python script that is listening to my serial port on which my arduino send strings.

import serial

ser = serial.Serial("/dev/ttyACM0", 9600, timeout=0.5)

while True:    
    print (str(ser.readline())

The connection is etablished, but I can't compare the readed line with a string, as the line comes with unwanted caracters : [value]/r/n

I want to get rid of these caracters. I've tried the following :

ser.readline().decode().strip('\r\n')

It's working fine.. until python read an unknown caracter that it is not able to decode :

0
0
0
Traceback (most recent call last):
  File "/home/testserial.py", line 6, in <module>
    value = ser.readline().decode().strip('\r\n')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8d in position 1: invalid start byte

I don't understand why this caracter is there. My arduino program only send bolean 0 or 1

Do you guys have any ideas ?

Upvotes: 2

Views: 6061

Answers (2)

Max
Max

Reputation: 1

I think there is more to this than @JamesKent Arduino code, I had the same problem with tried and tested C code running on an XMC talking to a Pi where the Pi would send a request as an ASCII string and the XMC would respond with a fixed number of \n terminated strings of data. Rarely, (between 30 seconds and many hours) I would get the dreaded decode error. I ended up fixing it by doing this for the case that data ends up being an empty string which is essentially the same thing:

try:
    data = ser.readline().decode().strip()
except UnicodeDecodeError:  # catch serial data errors
    print('Serial Error\n')

if data:
    ..Do other stuff with data

Strangely enough the error hasn't reoccurred (yet)

Upvotes: 0

James Kent
James Kent

Reputation: 5933

to ignore the error:

import serial

ser = serial.Serial("/dev/ttyACM0", 9600, timeout=0.5)

while True:
    try:
        print (str(ser.readline())
    except UnicodeDecodeError: # catch error and ignore it
        print('uh oh')

note that its usually better to try and find the source of the error and fix it, but if an occasional missed value is acceptable then this will do the job.

Upvotes: 3

Related Questions