连续读取串行数据



我正在尝试从我的arduino收集串行数据。

以下是相关代码:

def readSerial():
ser_bytes = ser.readline()
ser_bytes = ser_bytes.decode("utf-8")
text.insert("end", ser_bytes)
after_id=root.after(100,readSerial)

def measure_all():    
global stop_
stop_ = False
ser.write("rf".encode()) #Send string 'rf to arduino', which means Measure all Sensors
readSerial() #Start Reading data

arduino将在接收到字符串'rf'时开始发送数据。

引入BUG时的行为:第一次,我的代码将工作。然而,如果我关闭应用程序,它将无法再次工作——除非我将USB电缆移除并重新插入arduino两次。

有时,当我正常接收数据时,会出现问题,我接收的数据最终会错位。

有时,终端上不会显示任何错误,程序就会冻结。

现在,让我们跳到各自的错误消息。

错误消息:

最常见的是:

ser_bytes = ser_bytes.decode("utf-8").
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfe in position 0: invalid start byte
ser_bytes = ser_bytes.decode("utf-8")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

ser_bytes = ser_bytes.decode("utf-8")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa9 in position 10: invalid  start byte

但有时我也会收到一些其他的,比如:

ser_bytes = ser_bytes.decode("utf-8")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xce in position 40: invalid continuation byte

ser_bytes = ser.readline()
File "C:UsersUser1AppDataLocalProgramsPythonPython38-32libsite-packag
esserialserialwin32.py", line 286, in read
result_ok = win32.GetOverlappedResult()

正如你所看到的,大多数错误消息都涉及这一行:

ser_bytes = ser_bytes.decode("utf-8")

有一次,我在这条线上收到错误:

ser_bytes = ser.readline()

有人明白发生了什么吗?这和我的编码有关吗?请记住,arduino在串行模式下使用Newline选择(例如,与Carriage Return相反(——如果这对您有用的话。

问题是utf-8编解码器被限制为7位(仅值127或0x7F-(,而不是完整的8位字节。所以它不能读取0xFF或0xFE。。。

当你从串行端口读取时,你不需要指定.decode('utf-8'(。但当你像在ser.write((.中那样发送时,你确实需要指定它

默认情况下,ser.readline将返回字节。所以,如果你期待数字,你都很好。。。

最新更新