Skip to content

Commit 7ebfe09

Browse files
committed
esp8266: Add dht.py script for high-level control of DHT11/DHT22 sensor.
TODO: should go in a more port-neutral place, like drivers/dht, but at the moment in relies on specific esp module.
1 parent 45f3416 commit 7ebfe09

1 file changed

Lines changed: 32 additions & 0 deletions

File tree

esp8266/scripts/dht.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# DHT11/DHT22 driver for MicroPython on ESP8266
2+
# MIT license; Copyright (c) 2016 Damien P. George
3+
4+
import esp
5+
6+
class DHTBase:
7+
def __init__(self, pin):
8+
self.pin = pin
9+
self.buf = bytearray(5)
10+
11+
def measure(self):
12+
buf = self.buf
13+
esp.dht_readinto(self.pin, buf)
14+
if (buf[0] + buf[1] + buf[2] + buf[3]) & 0xff != buf[4]:
15+
raise Exception("checksum error")
16+
17+
class DHT11(DHTBase):
18+
def humidity(self):
19+
return self.buf[0]
20+
21+
def temperature(self):
22+
return self.buf[2]
23+
24+
class DHT22(DHTBase):
25+
def humidity(self):
26+
return (self.buf[0] << 8 | self.buf[1]) * 0.1
27+
28+
def temperature(self):
29+
t = ((self.buf[2] & 0x7f) << 8 | self.buf[3]) * 0.1
30+
if self.buf[2] & 0x80:
31+
t = -t
32+
return t

0 commit comments

Comments
 (0)