Skip to content

Commit

Permalink
Merge pull request #77 from semancik/main
Browse files Browse the repository at this point in the history
Support for DHT21/AM2301
  • Loading branch information
tannewt committed Nov 19, 2021
2 parents 244a7d1 + 88569bb commit c71bdaf
Showing 1 changed file with 26 additions and 3 deletions.
29 changes: 26 additions & 3 deletions adafruit_dht.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,15 @@ class DHTBase:

__hiLevel = 51

def __init__(self, dht11: bool, pin: Pin, trig_wait: int, use_pulseio: bool):
def __init__(
self,
dht11: bool,
pin: Pin,
trig_wait: int,
use_pulseio: bool,
*,
max_pulses: int = 81
):
"""
:param boolean dht11: True if device is DHT11, otherwise DHT22.
:param ~board.Pin pin: digital pin used for communication
Expand All @@ -65,6 +73,7 @@ def __init__(self, dht11: bool, pin: Pin, trig_wait: int, use_pulseio: bool):
self._dht11 = dht11
self._pin = pin
self._trig_wait = trig_wait
self._max_pulses = max_pulses
self._last_called = 0
self._humidity = None
self._temperature = None
Expand All @@ -74,7 +83,7 @@ def __init__(self, dht11: bool, pin: Pin, trig_wait: int, use_pulseio: bool):
# We don't use a context because linux-based systems are sluggish
# and we're better off having a running process
if self._use_pulseio:
self.pulse_in = PulseIn(self._pin, maxlen=81, idle_state=True)
self.pulse_in = PulseIn(self._pin, maxlen=self._max_pulses, idle_state=True)
self.pulse_in.pause()

def exit(self) -> None:
Expand Down Expand Up @@ -179,7 +188,7 @@ def _get_pulses_bitbang(self) -> array.array:
transitions.append(time.monotonic()) # save the timestamp
# convert transtions to microsecond delta pulses:
# use last 81 pulses
transition_start = max(1, len(transitions) - 81)
transition_start = max(1, len(transitions) - self._max_pulses)
for i in range(transition_start, len(transitions)):
pulses_micro_sec = int(1000000 * (transitions[i] - transitions[i - 1]))
pulses.append(min(pulses_micro_sec, 65535))
Expand Down Expand Up @@ -294,3 +303,17 @@ class DHT22(DHTBase):

def __init__(self, pin: Pin, use_pulseio: bool = _USE_PULSEIO):
super().__init__(False, pin, 1000, use_pulseio)


class DHT21(DHTBase):
"""Support for DHT21/AM2301 device.
:param ~board.Pin pin: digital pin used for communication
"""

# DHT21/AM2301 is sending three more dummy bytes after the "official" protocol.
# Pulseio will take only the last pulses up to maxPulses.
# If that would be 81, the dummy pulses will be read and the real data would be truncated.
# Hence setting maxPulses to 129, taking both real data and dummy bytes into buffer.
def __init__(self, pin: Pin, use_pulseio: bool = _USE_PULSEIO):
super().__init__(False, pin, 1000, use_pulseio, max_pulses=129)

0 comments on commit c71bdaf

Please sign in to comment.