Skip to content

Commit a384b7d

Browse files
authored
Merge pull request #10 from jerryneedell/jerryn_negative
fix DHT22 handling of negative temperatures
2 parents ddda939 + 2aaaf1b commit a384b7d

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

adafruit_dht.py

+10-5
Original file line numberDiff line numberDiff line change
@@ -148,18 +148,24 @@ def measure(self):
148148
for byte_start in range(0, 80, 16):
149149
buf.append(self._pulses_to_binary(pulses, byte_start, byte_start+16))
150150

151-
# humidity is 2 bytes
152151
if self._dht11:
152+
# humidity is 1 byte
153153
self._humidity = buf[0]
154154
else:
155+
# humidity is 2 bytes
155156
self._humidity = ((buf[0]<<8) | buf[1]) / 10
156157

157-
# temperature is 2 bytes
158158
if self._dht11:
159+
# temperature is 1 byte
159160
self._temperature = buf[2]
160161
else:
161-
self._temperature = ((buf[2]<<8) | buf[3]) / 10
162-
162+
# temperature is 2 bytes
163+
# MSB is sign, bits 0-14 are magnitude)
164+
raw_temperature = (((buf[2] & 0x7f)<<8) | buf[3]) / 10
165+
# set sign
166+
if buf[2] & 0x80:
167+
raw_temperature = -raw_temperature
168+
self._temperature = raw_temperature
163169
# calc checksum
164170
chk_sum = 0
165171
for b in buf[0:4]:
@@ -170,7 +176,6 @@ def measure(self):
170176
# check sum failed to validate
171177
raise RuntimeError("Checksum did not validate. Try again.")
172178

173-
174179
else:
175180
raise RuntimeError("A full buffer was not returned. Try again.")
176181

0 commit comments

Comments
 (0)