I'm having difficulty with unicode strings. Serialport.write ("\ x23o0 \ x23f") is not supported.

We are having difficulty with the following code

#Get the heading from the IMU
#Translate the IMU from magnetic north to true north since the calcs use true north
def getcurheading():
# The escape character for # is \x23 in hex
    serialport.write("\x23o0 \x23f")
    headresponse = serialport.readline()
#   print(headresponse)
    words = headresponse.split(",")
    if len(words) > 2:
        try:
            curheading = (float(words[0])) + 180
            if curheading + Declination > 360: curheading = curheading - 360 + Declination
            else: curheading = curheading + Declination
        except:
            curheading = 999
#   print(curheading)
        return curheading

Here is the error message:

Traceback (most recent call last):
  File "solarrobot7-core.py", line 256, in <module>
    if (getcurheading() < getsolarheading()) and (getsolarangle() > 2) and (getcurheading() != 999):
  File "solarrobot7-core.py", line 118, in getcurheading
    serialport.write("\x23o0 \x23f")
  File "/usr/local/lib/python3.2/dist-packages/serial/serialposix.py", line 518, in write
    d = to_bytes(data)
  File "/usr/local/lib/python3.2/dist-packages/serial/serialutil.py", line 58, in to_bytes
    raise TypeError('unicode strings are not supported, please encode to bytes: %r' % (seq,))
TypeError: unicode strings are not supported, please encode to bytes: '#o0 #f'

It looks like I can use:

a_string = '\x23o0 \x23f Python'
by = a_string.encode('utf-8')
serialport.write("\x23o0 \x23f ") a serialport.write(by)

It is right? Since I am not an encoder, I am not sure if this fix is ​​correct. I tried it, and the code continues until it throws another error, which seems to be related to this step. That is why we go back to make sure it is right before moving on.

+4
source share
1 answer

Python 3.X , "abc" , Unicode. b"abc" ( b). :

serialport.write(b"\x23o0 \x23f")

serialport.write("\x23o0 \x23f".encode('ascii'))

, utf8.

bytearray . Python 3:

>>> bytearray("abc")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string argument without an encoding
>>> bytearray("abc",'ascii')
bytearray(b'abc')

bytearrays:

>>> bytes = bytearray("abc",'ascii')
>>> bytes[1]=50
>>> bytes
bytearray(b'a2c')

:

>>> bytes = b'abc'
>>> bytes[1] = 50
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bytes' object does not support item assignment
+7

Source: https://habr.com/ru/post/1625594/


All Articles