Python和Arduino Serial,解码问题

时间:2017-10-31 10:47:07

标签: python arduino serial-port byte

我有一个简单的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程序只发送bolean 01

你们有什么想法吗?

1 个答案:

答案 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')

请注意,通常最好尝试找到错误的来源并修复它,但如果偶尔错过的值是可以接受的,那么这将完成这项工作。