@@ -55,7 +55,15 @@ class DHTBase:
5555
5656 __hiLevel = 51
5757
58- def __init__ (self , dht11 : bool , pin : Pin , trig_wait : int , use_pulseio : bool ):
58+ def __init__ (
59+ self ,
60+ dht11 : bool ,
61+ pin : Pin ,
62+ trig_wait : int ,
63+ use_pulseio : bool ,
64+ * ,
65+ max_pulses : int = 81
66+ ):
5967 """
6068 :param boolean dht11: True if device is DHT11, otherwise DHT22.
6169 :param ~board.Pin pin: digital pin used for communication
@@ -65,6 +73,7 @@ def __init__(self, dht11: bool, pin: Pin, trig_wait: int, use_pulseio: bool):
6573 self ._dht11 = dht11
6674 self ._pin = pin
6775 self ._trig_wait = trig_wait
76+ self ._max_pulses = max_pulses
6877 self ._last_called = 0
6978 self ._humidity = None
7079 self ._temperature = None
@@ -74,7 +83,7 @@ def __init__(self, dht11: bool, pin: Pin, trig_wait: int, use_pulseio: bool):
7483 # We don't use a context because linux-based systems are sluggish
7584 # and we're better off having a running process
7685 if self ._use_pulseio :
77- self .pulse_in = PulseIn (self ._pin , maxlen = 81 , idle_state = True )
86+ self .pulse_in = PulseIn (self ._pin , maxlen = self . _max_pulses , idle_state = True )
7887 self .pulse_in .pause ()
7988
8089 def exit (self ) -> None :
@@ -179,7 +188,7 @@ def _get_pulses_bitbang(self) -> array.array:
179188 transitions .append (time .monotonic ()) # save the timestamp
180189 # convert transtions to microsecond delta pulses:
181190 # use last 81 pulses
182- transition_start = max (1 , len (transitions ) - 81 )
191+ transition_start = max (1 , len (transitions ) - self . _max_pulses )
183192 for i in range (transition_start , len (transitions )):
184193 pulses_micro_sec = int (1000000 * (transitions [i ] - transitions [i - 1 ]))
185194 pulses .append (min (pulses_micro_sec , 65535 ))
@@ -294,3 +303,17 @@ class DHT22(DHTBase):
294303
295304 def __init__ (self , pin : Pin , use_pulseio : bool = _USE_PULSEIO ):
296305 super ().__init__ (False , pin , 1000 , use_pulseio )
306+
307+
308+ class DHT21 (DHTBase ):
309+ """Support for DHT21/AM2301 device.
310+
311+ :param ~board.Pin pin: digital pin used for communication
312+ """
313+
314+ # DHT21/AM2301 is sending three more dummy bytes after the "official" protocol.
315+ # Pulseio will take only the last pulses up to maxPulses.
316+ # If that would be 81, the dummy pulses will be read and the real data would be truncated.
317+ # Hence setting maxPulses to 129, taking both real data and dummy bytes into buffer.
318+ def __init__ (self , pin : Pin , use_pulseio : bool = _USE_PULSEIO ):
319+ super ().__init__ (False , pin , 1000 , use_pulseio , max_pulses = 129 )
0 commit comments