dht.py 858 B

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