python3 pySerial TypeError:不支持unicode字符串,请编码为字节:

Nik*_*cks 20 arduino pyserial python-3.x

在python 3中,我导入了pySerial库,因此我可以通过串行命令与我的arduino uno通信,它在python 2.7中工作得非常好但在python 3中我一直遇到错误,它说这个TypeError:不支持unicode字符串,请编码到bytes:'allon'在python 2.7中我唯一不同的是使用raw_input但是我不知道python 3中发生了什么这里是我的代码

    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()
Run Code Online (Sandbox Code Playgroud)

小智 31

将您正在写入的数据编码为serial,在您的情况下将"serialcmd"编码为bytes.try以下内容:

ser.write(serialcmd.encode())


小智 16

我发现学习“ Arduino Python Serial” 时遇到了同样的问题,
您可以这样做:

ser.write(str.encode('allon'))
Run Code Online (Sandbox Code Playgroud)


Osa*_*Dar 7

如果我们有字符串本身而不是变量,我们可以这样做:

    ser.write(b'\x0101')
Run Code Online (Sandbox Code Playgroud)

这会将字符串转换为bytes类型