user1584421
user1584421

Reputation: 3843

Reading serial data consistently

I am trying to collect serial data from my arduino.

Here is the relevant code:

def readSerial():
    ser_bytes = ser.readline()
    ser_bytes = ser_bytes.decode("utf-8")
    text.insert("end", ser_bytes)
    after_id=root.after(100,readSerial)



def measure_all():    
   global stop_
   stop_ = False
   ser.write("rf".encode()) #Send string 'rf to arduino', which means Measure all Sensors
   readSerial() #Start Reading data

The arduino will start sending data when it receives the string 'rf'.

BEHAVIOUR WHEN BUG IS INTRODUCED: The first time, my code will work. However, if i close the application it won't work again - unless i remove and re-insert the USB cable to the arduino twice.

Sometimes, when i receive data normally, something will go wrong, and the data i receive will end up out of place.

Sometimes, no error will be displayed on the terminal, and the program will just freeze.

Now let's jump to the error messages themsevles.

ERROR MESSAGES:

The most common one is this:

ser_bytes = ser_bytes.decode("utf-8").
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfe in position 0: invalid start byte

ser_bytes = ser_bytes.decode("utf-8")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte


ser_bytes = ser_bytes.decode("utf-8")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa9 in position 10: invalid  start byte

But sometimes i have received some other ones like:

  ser_bytes = ser_bytes.decode("utf-8")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xce in position 40: invalid continuation byte


    ser_bytes = ser.readline()
  File "C:\Users\User1\AppData\Local\Programs\Python\Python38-32\lib\site-packag
es\serial\serialwin32.py", line 286, in read
    result_ok = win32.GetOverlappedResult()

As you can see, the majority of the error messages involve this line:

ser_bytes = ser_bytes.decode("utf-8")

and once, i have received error on this line:

ser_bytes = ser.readline()

Does anyone understand what is going on? Does this have to do with my encoding? Keep in mind that the arduino uses the Newline selection in the serial mode (as opposed to Carriage Return for example) - if that is of any use to you.

Upvotes: 0

Views: 654

Answers (1)

Frederic Durville
Frederic Durville

Reputation: 11

The problem is that the utf-8 codec is limited to 7-bits (value of 127 - or 0x7F - only) instead of the full 8-bit byte. So it cannot read 0xFF or 0xFE...

You do not need to specify the .decode('utf-8') when you read from a serial port. But you DO need to specify it when you send out as you did in ser.write().

By default, the ser.readline will return bytes. So if you expect numbers, you are all good...

Upvotes: 1

Related Questions