Skip to content

Commit 142f395

Browse files
committed
Do not update sensor values on error
Currently, we update self._temperature and self._humidity, even if it turns out that the data returned by the sensor was bogus. If the user queries the data within two seconds after an error, they will actually get wrong data. Fix this by updating _temperature and _humidity attributes only if no error was detected.
1 parent 0ea15b6 commit 142f395

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

adafruit_dht.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,9 @@ def measure(self):
175175
(time.monotonic()-self._last_called) > delay_between_readings):
176176
self._last_called = time.monotonic()
177177

178+
new_temperature = 0
179+
new_humidity = 0
180+
178181
if _USE_PULSEIO:
179182
pulses = self._get_pulses_pulseio()
180183
else:
@@ -188,19 +191,19 @@ def measure(self):
188191

189192
if self._dht11:
190193
# humidity is 1 byte
191-
self._humidity = buf[0]
194+
new_humidity = buf[0]
192195
# temperature is 1 byte
193-
self._temperature = buf[2]
196+
new_temperature = buf[2]
194197
else:
195198
# humidity is 2 bytes
196-
self._humidity = ((buf[0]<<8) | buf[1]) / 10
199+
new_humidity = ((buf[0]<<8) | buf[1]) / 10
197200
# temperature is 2 bytes
198201
# MSB is sign, bits 0-14 are magnitude)
199202
raw_temperature = (((buf[2] & 0x7f)<<8) | buf[3]) / 10
200203
# set sign
201204
if buf[2] & 0x80:
202205
raw_temperature = -raw_temperature
203-
self._temperature = raw_temperature
206+
new_temperature = raw_temperature
204207
# calc checksum
205208
chk_sum = 0
206209
for b in buf[0:4]:
@@ -213,10 +216,14 @@ def measure(self):
213216

214217
elif len(pulses) >= 10:
215218
# We got *some* data just not 81 bits
216-
raise RuntimeError("A full buffer was not returned. Try again.")
219+
raise RuntimeError("A full buffer was not returned. Try again.")
217220
else:
218221
# Probably a connection issue!
219222
raise RuntimeError("DHT sensor not found, check wiring")
223+
224+
self._temperature = new_temperature
225+
self._humidity = new_humidity
226+
220227
@property
221228
def temperature(self):
222229
""" temperature current reading. It makes sure a reading is available

0 commit comments

Comments
 (0)