From ae89762cb54bd55ce4474dde4e883fe1c7a44e66 Mon Sep 17 00:00:00 2001 From: David Glaude Date: Sat, 18 Jul 2020 00:55:08 +0200 Subject: [PATCH] Attempt to increase reliability Reading from the UART can return bad values (this can also be tested by unplugging the cable or not fully fitting the cable). With previous version of the library, at the first glitch, the library would never return a valid value. This version agressively try to read a first byte until we have the start of frame signature or there is no more byte to read. It give much better result for me, and this can be tested by playing with the cable. --- adafruit_pm25.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/adafruit_pm25.py b/adafruit_pm25.py index ea22c6a..7ee24a4 100644 --- a/adafruit_pm25.py +++ b/adafruit_pm25.py @@ -172,17 +172,17 @@ def __init__(self, uart, reset_pin=None): super().__init__() def _read_into_buffer(self): - b = self._uart.read(1) - if not b: - raise RuntimeError("Unable to read from PM2.5 UART") - b = b[0] - if b != 0x42: - raise RuntimeError("Unable to read from PM2.5 UART") - self._buffer[0] = b # read one byte + while True: + b = self._uart.read(1) + if not b: + raise RuntimeError("Unable to read from PM2.5 (no start of frame)") + if b[0] == 0x42: + break + self._buffer[0] = b[0] # first byte and start of frame remain = self._uart.read(31) if not remain or len(remain) != 31: - raise RuntimeError("Unable to read from PM2.5 UART") + raise RuntimeError("Unable to read from PM2.5 (incomplete frame)") for i in range(31): self._buffer[i + 1] = remain[i] # print([hex(i) for i in self._buffer])