22from machine import enable_irq , disable_irq , Pin
33
44
5- class DTH11Result :
6- 'DHT11 sensor result returned by DHT11 .read() method'
5+ class DTHResult :
6+ 'DHT sensor result returned by DHT .read() method'
77
88 ERR_NO_ERROR = 0
99 ERR_MISSING_DATA = 1
@@ -19,32 +19,28 @@ def __init__(self, error_code, temperature, humidity):
1919 self .humidity = humidity
2020
2121 def is_valid (self ):
22- return self .error_code == DTH11Result .ERR_NO_ERROR
22+ return self .error_code == DTHResult .ERR_NO_ERROR
2323
2424
25- class DTH11 :
26- 'DHT11 sensor reader class for Pycom ESP32 board ex : SiPy '
25+ class DTH :
26+ 'DHT sensor (dht11, dht21,dht22) reader class for Pycom'
2727
2828 __pin = Pin ('P3' , mode = Pin .OPEN_DRAIN )
29+ __dhttype = 0
2930
30- def __init__ (self , pin ):
31+ def __init__ (self , pin , sensor = 0 ):
3132 self .__pin = pin
33+ self .__dhttype = sensor
3234
3335 def read (self ):
3436 time .sleep (1 )
35- self .__pin = Pin ('P3' , mode = Pin .OPEN_DRAIN )
36- # RPi.GPIO.setup(self.__pin, RPi.GPIO.OUT)
3737
3838 # send initial high
3939 self .__send_and_sleep (1 , 0.025 )
4040
4141 # pull down to low
4242 self .__send_and_sleep (0 , 0.04 )
4343
44- # change to input using pull up
45- #RPi.GPIO.setup(self.__pin, RPi.GPIO.IN, RPi.GPIO.PUD_UP)
46-
47-
4844 # collect data into an array
4945 data = self .__collect_input ()
5046
@@ -53,7 +49,7 @@ def read(self):
5349 # if bit count mismatch, return error (4 byte data + 1 byte checksum)
5450 #print(pull_up_lengths)
5551 if len (pull_up_lengths ) != 40 :
56- return DTH11Result ( DTH11Result .ERR_MISSING_DATA , 0 , 0 )
52+ return DTHResult ( DTHResult .ERR_MISSING_DATA , 0 , 0 )
5753
5854 # calculate bits from lengths of the pull up periods
5955 bits = self .__calculate_bits (pull_up_lengths )
@@ -64,10 +60,19 @@ def read(self):
6460 # calculate checksum and check
6561 checksum = self .__calculate_checksum (the_bytes )
6662 if the_bytes [4 ] != checksum :
67- return DTH11Result ( DTH11Result .ERR_CRC , 0 , 0 )
63+ return DTHResult ( DTHResult .ERR_CRC , 0 , 0 )
6864
6965 # ok, we have valid data, return it
70- return DTH11Result (DTH11Result .ERR_NO_ERROR , the_bytes [2 ], the_bytes [0 ])
66+ [int_rh , dec_rh , int_t , dec_t , csum ] = the_bytes
67+ if self .__dhttype == 0 : #dht11
68+ rh = int_rh #dht11 20% ~ 90%
69+ t = int_t #dht11 0..50°C
70+ else : #dht21,dht22
71+ rh = ((int_rh * 256 ) + dec_rh )/ 10
72+ t = (((int_t & 0x7F ) * 256 ) + dec_t )/ 10
73+ if (int_t & 0x80 ) > 0 :
74+ t *= - 1
75+ return DTHResult (DTHResult .ERR_NO_ERROR , t , rh )
7176
7277 def __send_and_sleep (self , output , mysleep ):
7378 self .__pin (output )
@@ -193,7 +198,7 @@ def __bits_to_bytes(self, bits):
193198 if ((i + 1 ) % 8 == 0 ):
194199 the_bytes .append (byte )
195200 byte = 0
196-
201+ #print(the_bytes)
197202 return the_bytes
198203
199204 def __calculate_checksum (self , the_bytes ):
0 commit comments