2018-01-31 07:11:06 +00:00
|
|
|
# DHT11/DHT22 driver for MicroPython on ESP8266
|
|
|
|
# MIT license; Copyright (c) 2016 Damien P. George
|
|
|
|
|
2021-06-19 10:00:55 +01:00
|
|
|
import sys
|
|
|
|
|
|
|
|
if sys.platform.startswith("esp"):
|
2018-01-31 07:12:53 +00:00
|
|
|
from esp import dht_readinto
|
2021-06-19 10:00:55 +01:00
|
|
|
elif sys.platform == "mimxrt":
|
|
|
|
from mimxrt import dht_readinto
|
|
|
|
else:
|
2018-01-31 07:12:53 +00:00
|
|
|
from pyb import dht_readinto
|
2018-01-31 07:11:06 +00:00
|
|
|
|
2020-02-27 04:36:53 +00:00
|
|
|
|
2018-01-31 07:11:06 +00:00
|
|
|
class DHTBase:
|
|
|
|
def __init__(self, pin):
|
|
|
|
self.pin = pin
|
|
|
|
self.buf = bytearray(5)
|
|
|
|
|
|
|
|
def measure(self):
|
|
|
|
buf = self.buf
|
2018-01-31 07:12:53 +00:00
|
|
|
dht_readinto(self.pin, buf)
|
2018-01-31 07:11:06 +00:00
|
|
|
if (buf[0] + buf[1] + buf[2] + buf[3]) & 0xFF != buf[4]:
|
|
|
|
raise Exception("checksum error")
|
|
|
|
|
2020-02-27 04:36:53 +00:00
|
|
|
|
2018-01-31 07:11:06 +00:00
|
|
|
class DHT11(DHTBase):
|
|
|
|
def humidity(self):
|
|
|
|
return self.buf[0]
|
|
|
|
|
|
|
|
def temperature(self):
|
|
|
|
return self.buf[2]
|
|
|
|
|
2020-02-27 04:36:53 +00:00
|
|
|
|
2018-01-31 07:11:06 +00:00
|
|
|
class DHT22(DHTBase):
|
|
|
|
def humidity(self):
|
|
|
|
return (self.buf[0] << 8 | self.buf[1]) * 0.1
|
|
|
|
|
|
|
|
def temperature(self):
|
|
|
|
t = ((self.buf[2] & 0x7F) << 8 | self.buf[3]) * 0.1
|
|
|
|
if self.buf[2] & 0x80:
|
|
|
|
t = -t
|
|
|
|
return t
|