当出现特定字符时,开始使用pyserial从串行端口读取传入数据

2024-05-16 11:34:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着从重量秤(雷克萨斯矩阵一)读取输入数据。我希望代码在=出现后开始读取8个字符。在

问题是,有时代码会这样做,而有时它会在天平发送的测量值中间开始读取数据,从而导致无法正确读取数据。我使用的是windows上python3上的pyserial模块。在

import serial
ser=serial.Serial("COM4", baudrate=9600)
a=0
while a<10:
  b=ser.read(8)
  a=a+1
  print(b)

预期结果是:b'= 0004.0'

但有时我得到:b'4.0= 000'


Tags: 模块数据代码importwindowsserial矩阵读取数据
1条回答
网友
1楼 · 发布于 2024-05-16 11:34:09

我想我们需要更多关于体重秤数据格式的信息来提供完整的答案。但是您当前的代码只从流中读取前80个字节,每次8个字节。在

如果您想读取任何等号后面的8个字节,可以尝试如下操作:

import serial
ser = serial.Serial("COM4", baudrate=9600)
readings = []
done = False
while not done:
    current_char = ser.read()
    # check for equals sign
    if current_char == b'=':
        reading = ser.read(8)
        readings.append(reading)

    # this part will depend on your specific needs.
    # in this example, we stop after 10 readings
    # check for stopping condition and set done = True
    if len(readings) >= 10:
        done = True

相关问题 更多 >