@@ -6,10 +6,11 @@ written by Adafruit Industries
66
77#include " DHT.h"
88
9+ #define MIN_INTERVAL 2000
10+
911DHT::DHT (uint8_t pin, uint8_t type, uint8_t count) {
1012 _pin = pin;
1113 _type = type;
12- _firstreading = true ;
1314 _bit = digitalPinToBitMask (pin);
1415 _port = digitalPinToPort (pin);
1516 _maxcycles = microsecondsToClockCycles (1000 ); // 1 millisecond timeout for
@@ -20,17 +21,19 @@ DHT::DHT(uint8_t pin, uint8_t type, uint8_t count) {
2021
2122void DHT::begin (void ) {
2223 // set up the pins!
23- pinMode (_pin, INPUT);
24- digitalWrite (_pin, HIGH);
25- _lastreadtime = 0 ;
24+ pinMode (_pin, INPUT_PULLUP);
25+ // Using this value makes sure that millis() - lastreadtime will be
26+ // >= MIN_INTERVAL right away. Note that this assignment wraps around,
27+ // but so will the subtraction.
28+ _lastreadtime = -MIN_INTERVAL;
2629 DEBUG_PRINT (" Max clock cycles: " ); DEBUG_PRINTLN (_maxcycles, DEC);
2730}
2831
2932// boolean S == Scale. True == Fahrenheit; False == Celcius
30- float DHT::readTemperature (bool S) {
33+ float DHT::readTemperature (bool S, bool force ) {
3134 float f = NAN;
3235
33- if (read ()) {
36+ if (read (force )) {
3437 switch (_type) {
3538 case DHT11:
3639 f = data[2 ];
@@ -64,7 +67,7 @@ float DHT::convertFtoC(float f) {
6467 return (f - 32 ) * 5 / 9 ;
6568}
6669
67- float DHT::readHumidity (void ) {
70+ float DHT::readHumidity (bool force ) {
6871 float f = NAN;
6972 if (read ()) {
7073 switch (_type) {
@@ -113,19 +116,14 @@ float DHT::computeHeatIndex(float temperature, float percentHumidity, bool isFah
113116 }
114117}
115118
116- boolean DHT::read (void ) {
119+ boolean DHT::read (bool force ) {
117120 // Check if sensor was read less than two seconds ago and return early
118121 // to use last reading.
119122 uint32_t currenttime = millis ();
120- if (currenttime < _lastreadtime) {
121- // ie there was a rollover
122- _lastreadtime = 0 ;
123- }
124- if (!_firstreading && ((currenttime - _lastreadtime) < 2000 )) {
123+ if (!force && ((currenttime - _lastreadtime) < 2000 )) {
125124 return _lastresult; // return last correct measurement
126125 }
127- _firstreading = false ;
128- _lastreadtime = millis ();
126+ _lastreadtime = currenttime;
129127
130128 // Reset 40 bits of received data to zero.
131129 data[0 ] = data[1 ] = data[2 ] = data[3 ] = data[4 ] = 0 ;
@@ -154,7 +152,7 @@ boolean DHT::read(void) {
154152 delayMicroseconds (40 );
155153
156154 // Now start reading the data line to get the value from the DHT sensor.
157- pinMode (_pin, INPUT );
155+ pinMode (_pin, INPUT_PULLUP );
158156 delayMicroseconds (10 ); // Delay a bit to let sensor pull data line low.
159157
160158 // First expect a low signal for ~80 microseconds followed by a high signal
0 commit comments