0

I'm new to Python and am working on a sensor. I'm building my code line by line and I have trouble with the encoding/decoding part for bytes to string. Same code, sometime it works, sometime it dosen't.

Here is the code:

import serial
import time
import os

port = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=1,      bytesize=8)
f_w = open('/home/myname/python_serial_output.txt','r+')

port.send_break()

while True:
    op = port.read(2)
    op_str = op.decode('utf-8')
    f_w.write(op_str)
    print(op_str)

It didn't work the first time round, but worked on the second time. Why?

Here is the error I get:

myname@Toshiba:~$ python3 serial_test.py 
Traceback (most recent call last):
  File "serial_test.py", line 13, in <module>
    op_str = op.decode('utf-8') 
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x82 in position 0: invalid start byte

myname@Toshiba:~$ python3 serial_test.py 
Ex
pl
or
er

How do I remove the ambiguity of it running successfully?

1 Answer 1

0

This may have have happened because your string had a non ascii character. When you ran your code again there was no non ascii character in the string and hence it ran successfully.

You can encode the non ascii characters by using encode() function

Sign up to request clarification or add additional context in comments.

1 Comment

So I should encode my entire op before decoding it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.