如何正确编码字符串变量以通过串口将其发送到 Arduino?

How to encode a string variable correctly to send it to Arduino via serial?

我想通过串口将变量的值从 RaspberryPi 发送到 Arduino Uno。 如果我输入 :

ser.write(b'RED')

我可以在 Arduino 串行监视器上将其读取为 RED。但是如果我输入:

color = "GREEN"
ser.write(color)

ser.write(color.encoding('utf-8'))

那我什么都看不到了。我应该怎么做才能使用变量发送字符串? Python 和 pyserial 库 运行 o Raspberry。

ser.write(b'RED')ser.write('RED'.encode()) 的作用相同,因此您将字符串转换为其等效字节,然后将其发送到 Arduino。

color = 'GREEN' (我认为你的意思是因为 GREEN 未定义)没有进行任何转换所以你发送的字符串文字 ser.write(color)

ser.write(color.encode()) 随心所欲