Problems with decoding bytes into string or ASCII in python 3 -
i'm having problem decoding received bytes python 3. i'm controlling arduino via serial connection , read following code:
import serial arduino = serial.serial('/dev/ttyacm0', baudrate=9600, timeout=20) print(arduino.isopen()) mydata = arduino.readline() print(mydata)
the outcome looks b'\xe1\x02\xc1\x032\x82\x83\x10\x83\xb2\x80\xb0\x92\x0b\xa0'
or b'\xe1\x02"\xe1\x00\x83\x92\x810\x82\xb2\x82\x91\xb2\n'
, tried decode usual way via mydata.decode('utf-8')
, error unicodedecodeerror: 'utf-8' codec can't decode byte 0xb2 in position 1: invalid start byte
. tried other decodings (ascii, cp437, hex, utf-16), face same error.
do have suggestions, how can decode received bytes or decoding arduino requires? tried decode piece piece using loop, face same error message.
and there general way avoid decoding problems or find out, decoding have use?
thanks in advance.
as @jsbueno said in comments not decoding problem, because byte data being received binary data. had similar problem when reading binary data (bytes) file.
there 2 options use here, first 1 being struct module:
import struct = open("somedata.img", "rb") b = a.read(2) file_size, = struct.unpack("i",a.read(4))
writing code way produces tuple, integer, use struct.unpack('i', a.read(4))[0]
another way used if want store data in numpy array is:
import numpy np f = open("somefile.img", "r") = np.fromfile(f, dtype=np.uint32)
Comments
Post a Comment