gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:45:55 24 4
gpt4 key购买 nike

我正在尝试从体重秤(Lexus Matrix One)读取传入数据。我希望代码在 = 出现后开始读取 8 个字符。

问题在于,有时代码会这样做,而有时它会在秤发送的测量结果中间开始读取数据,从而无法正确读取。我在 Windows 上的 python 3 上使用 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'

最佳答案

我认为我们需要更多关于体重秤数据格式的信息才能提供完整的答案。但您当前的代码仅从流中读取前 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

关于python - 当出现特定字符时,开始使用 pyserial 从串行端口读取传入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56990930/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com