首页 > 解决方案 > 一致地读取串行数据

问题描述

我正在尝试从我的 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'

引入错误时的行为:第一次,我的代码将工作。但是,如果我关闭应用程序,它将无法再次工作 - 除非我移除 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:\Users\User1\AppData\Local\Programs\Python\Python38-32\lib\site-packag
es\serial\serialwin32.py", line 286, in read
    result_ok = win32.GetOverlappedResult()

如您所见,大多数错误消息都涉及此行:

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

有一次,我在这一行收到错误:

ser_bytes = ser.readline()

有谁明白发生了什么?这与我的编码有关吗?请记住,arduinoNewline在串行模式下使用选择(而不是Carriage Return例如) - 如果这对您有任何用处。

标签: python-3.xpyserial

解决方案


问题在于 utf-8 编解码器仅限于 7 位(值 127 - 或 0x7F - 仅限),而不是完整的 8 位字节。所以它无法读取 0xFF 或 0xFE ...

从串行端口读取时,不需要指定 .decode('utf-8') 。但是您确实需要在发送时指定它,就像在 ser.write() 中所做的那样。

默认情况下, ser.readline 将返回字节。因此,如果您期望数字,那么一切都很好...


推荐阅读