Skip to content

Commit 1833318

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 20c4da3 commit 1833318

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

adafruit_dht.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,9 @@ def measure(self):
180180
):
181181
self._last_called = time.monotonic()
182182

183+
new_temperature = 0
184+
new_humidity = 0
185+
183186
if _USE_PULSEIO:
184187
pulses = self._get_pulses_pulseio()
185188
else:
@@ -195,19 +198,19 @@ def measure(self):
195198

196199
if self._dht11:
197200
# humidity is 1 byte
198-
self._humidity = buf[0]
201+
new_humidity = buf[0]
199202
# temperature is 1 byte
200-
self._temperature = buf[2]
203+
new_temperature = buf[2]
201204
else:
202205
# humidity is 2 bytes
203-
self._humidity = ((buf[0] << 8) | buf[1]) / 10
206+
new_humidity = ((buf[0] << 8) | buf[1]) / 10
204207
# temperature is 2 bytes
205208
# MSB is sign, bits 0-14 are magnitude)
206209
raw_temperature = (((buf[2] & 0x7F) << 8) | buf[3]) / 10
207210
# set sign
208211
if buf[2] & 0x80:
209212
raw_temperature = -raw_temperature
210-
self._temperature = raw_temperature
213+
new_temperature = raw_temperature
211214
# calc checksum
212215
chk_sum = 0
213216
for b in buf[0:4]:
@@ -220,11 +223,14 @@ def measure(self):
220223

221224
elif len(pulses) >= 10:
222225
# We got *some* data just not 81 bits
223-
raise RuntimeError("A full buffer was not returned. Try again.")
226+
raise RuntimeError("A full buffer was not returned. Try again.")
224227
else:
225228
# Probably a connection issue!
226229
raise RuntimeError("DHT sensor not found, check wiring")
227230

231+
self._temperature = new_temperature
232+
self._humidity = new_humidity
233+
228234
@property
229235
def temperature(self):
230236
""" temperature current reading. It makes sure a reading is available

0 commit comments

Comments
 (0)