我有一个简单的 python 脚本,它正在监听我的 arduino 发送字符串的串行端口。
import serial
ser = serial.Serial("/dev/ttyACM0", 9600, timeout=0.5)
while True:
print (str(ser.readline())
连接已建立,但我无法将读取的行与字符串进行比较,因为该行带有不需要的字符:[value]/r/n
我想摆脱这些角色。我尝试过以下方法:
ser.readline().decode().strip('\r\n')
它工作正常..直到 python 读取到一个无法解码的未知字符:
0
0
0
Traceback (most recent call last):
File "/home/testserial.py", line 6, in <module>
value = ser.readline().decode().strip('\r\n')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8d in position 1: invalid start byte
我不明白为什么会有这个角色。我的arduino程序仅发送 bool 值0
或1
你们有什么想法吗?
最佳答案
忽略错误:
import serial
ser = serial.Serial("/dev/ttyACM0", 9600, timeout=0.5)
while True:
try:
print (str(ser.readline())
except UnicodeDecodeError: # catch error and ignore it
print('uh oh')
请注意,通常最好尝试找到错误来源并修复它,但如果偶尔丢失的值是可以接受的,那么这将完成工作。
关于Python和Arduino串口,解码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47033476/