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

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

在 Python 3 中,我导入了 pySerial 库,因此我可以通过串行命令与我的 Arduino Uno 通信。
它在 Python 2.7 中运行良好,但在 Python 3 中,我将 运行 保持为一个错误,它说

TypeError: unicode strings are not supported, please encode to 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()

将要写入串行的数据编码,在您的情况下将“serialcmd”编码为bytes.try以下内容:

ser.write(serialcmd.encode())

我发现和你一样的学习问题"Arduino Python Serial"
你可以用另一种方法:

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

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

    ser.write(b'\x0101')

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