python3 pySerial TypeError: unicode strings are not supported, please encode to bytes:

一曲冷凌霜 提交于 2019-11-27 14:34:15

问题


In Python 3 I imported the pySerial library so I could communicate with my Arduino Uno by serial commands.
It worked very well in Python 2.7 but in Python 3 I keep running into a error it says this

TypeError: unicode strings are not supported, please encode to bytes: 'allon'

In Python 2.7 the only thing I did differently is use raw_input but I don't know what is happening in Python 3. Here is my code

    import serial, time
    import tkinter
    import os








    def serialcmdw():
    os.system('clear')
    serialcmd = input("serial command: ")
    ser.write (serialcmd)
    serialcmdw()

    ser = serial.Serial()
    os.system('clear')
    ser.port = "/dev/cu.usbmodem4321"
    ser.baudrate = 9600
    ser.open()
    time.sleep(1)
    serialcmdw()

回答1:


Encode your data which you are writing to serial,in your case "serialcmd" to bytes.try the following :

ser.write(serialcmd.encode())




回答2:


i found same you problem for learn "Arduino Python Serial"
You can do another way this:

ser.write(str.encode('allon'))


来源:https://stackoverflow.com/questions/35642855/python3-pyserial-typeerror-unicode-strings-are-not-supported-please-encode-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!