如何从串行正确读取最新值?

问题描述

我正在从具有 32x32 个独立压力点的压力传感垫读取值。它将串行读数输出为 1 到 250 + 1 个“结束标记”字节之间的 1024 个字节,始终为 255(或 xFF)。

我认为下面的函数会刷新/重置输入缓冲区,然后获取“新”读数并在我调用它时返回该读数的最大压力值。

然而,ser.reset_input_buffer() 和类似的方法似乎都没有真正清空缓冲区。当我按下垫子,运行程序并立即释放压力时,我没有看到最大值立即下降。相反,它似乎正在一个一个地通过缓冲区。

import serial
import numpy as np
import time

def read_serial():
        ser_bytes = bytearray([0])
        
        # none of these seem to make a differece
        ser.reset_input_buffer()
        ser.flushinput()
        ser.flush()

        # 2050 bytes should always contain a whole chunk of 1025 bytes ending with 255 (xFF)
        while len(ser_bytes) <= 2050:
            ser_bytes = ser_bytes + ser.read_until(b'\xFF')

        ser_ints = np.array(ser_bytes,dtype='int32')                #bytes to ints
        last_end_byte_index = np.max( np.where(ser_ints == 255) )    #find the last end byte

        # get only the 1024 sensor readings as 32x32 np array
        mat_reading = np.array( ser_ints[last_end_byte_index-1024: last_end_byte_index]).reshape(32,32)
        return np.amax(mat_reading)

ser = serial.Serial('/dev/tty.usbmodem14201',115200,timeout=1)

while True:
    print(read_serial())
    time.sleep(1)

目前我找到的最好的解决方案是使用一个指定的线程来不断读取缓冲区并更新全局变量。它有效,但如果我只想每 60 秒读取一次值,则似乎有点缺乏资源。有没有更好的办法?

还有……有没有更好的方法来读取代表整个垫子的 1025 字节块?没有换行符,因此 ser.readline() 不起作用。

谢谢!不知道如何使用串行制作 MWE,对此感到抱歉 ;)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)