Skip to content

Commit ae89762

Browse files
authored
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.
1 parent f70830b commit ae89762

File tree

1 file changed

+8
-8
lines changed

1 file changed

+8
-8
lines changed

adafruit_pm25.py

+8-8
Original file line numberDiff line numberDiff line change
@@ -172,17 +172,17 @@ def __init__(self, uart, reset_pin=None):
172172
super().__init__()
173173

174174
def _read_into_buffer(self):
175-
b = self._uart.read(1)
176-
if not b:
177-
raise RuntimeError("Unable to read from PM2.5 UART")
178-
b = b[0]
179-
if b != 0x42:
180-
raise RuntimeError("Unable to read from PM2.5 UART")
181-
self._buffer[0] = b # read one byte
175+
while True:
176+
b = self._uart.read(1)
177+
if not b:
178+
raise RuntimeError("Unable to read from PM2.5 (no start of frame)")
179+
if b[0] == 0x42:
180+
break
181+
self._buffer[0] = b[0] # first byte and start of frame
182182

183183
remain = self._uart.read(31)
184184
if not remain or len(remain) != 31:
185-
raise RuntimeError("Unable to read from PM2.5 UART")
185+
raise RuntimeError("Unable to read from PM2.5 (incomplete frame)")
186186
for i in range(31):
187187
self._buffer[i + 1] = remain[i]
188188
# print([hex(i) for i in self._buffer])

0 commit comments

Comments
 (0)