奇怪的输出值:b'[value]\r\n' - Python Serial Read

Weird Output Value: b'[value]\r\n' - Python Serial Read

我正在通过 Python 从 Arduino 传感器的串行端口读取一个值。

我的代码(Python):

arduino = serial.Serial(2, 9600, timeout=1)
print("Message from arduino: ") 
while True:
   msg = arduino.readline()
   print(msg)

不知道为什么输出结果是b'[sensor-value]\r\n'这样的。 所以,我得到类似 b'758\r\n' b'534\r\n' b'845\r\n' 等的东西(关于传感器变化值)。

如何转换?

您需要对其进行解码。

print(msg.decode('utf-8'))

请查看 Lexical Analysis Python 3 文档以了解字符串前缀的含义

遇到了与 Raspberry Pi Pico 类似的问题,我需要解码并删除多余的字符。这一切都可以通过一条线来实现。这依赖于 pySerial 包。

msg = ser.readline().decode('utf-8').rstrip()

对于上面的例子,serial.Serial 被命名为 arduino 而不是 ser,所以解决方案就是:

msg = arduino.readline().decode('utf-8').rstrip()

在这个 blog post 中找到了提示。