How to properly read most recent value from serial?

Viewed 162

I am reading values from a pressure sensing mat which has 32x32 individual pressure points. It outputs the readings on serial as 1024 bytes between 1 and 250 + 1 'end token' byte which is always 255 (or xFF).

I thought the function bellow would flush/reset the input buffer and then take a 'fresh' reading and return the max pressure value from that reading whenever I call it.

However, none of the ser.reset_input_buffer() and similar methods seem to actually empty the buffer. When I press down on the mat, run the program and immediately release the pressure, I don't see the max value drop immediately. Instead, it seems to be going through the buffer one by one.

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)

The best solution I found so far is having a designated thread which keeps reading the buffer and updating a global variable. It works but seems a bit unresourceful if I only want to read the value about every 60 seconds. Is there a better way?

Also... is there a better way to read the 1025-byte chunk representing the entire mat? There are no line breaks, so ser.readline() won't work.

Thanks! Not sure how to make an MWE with serial, sorry about that ;)

0 Answers
Related