@@ -6,10 +6,11 @@ written by Adafruit Industries
6
6
7
7
#include " DHT.h"
8
8
9
+ #define MIN_INTERVAL 2000
10
+
9
11
DHT::DHT (uint8_t pin, uint8_t type, uint8_t count) {
10
12
_pin = pin;
11
13
_type = type;
12
- _firstreading = true ;
13
14
_bit = digitalPinToBitMask (pin);
14
15
_port = digitalPinToPort (pin);
15
16
_maxcycles = microsecondsToClockCycles (1000 ); // 1 millisecond timeout for
@@ -20,17 +21,19 @@ DHT::DHT(uint8_t pin, uint8_t type, uint8_t count) {
20
21
21
22
void DHT::begin (void ) {
22
23
// 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;
26
29
DEBUG_PRINT (" Max clock cycles: " ); DEBUG_PRINTLN (_maxcycles, DEC);
27
30
}
28
31
29
32
// boolean S == Scale. True == Fahrenheit; False == Celcius
30
- float DHT::readTemperature (bool S) {
33
+ float DHT::readTemperature (bool S, bool force ) {
31
34
float f = NAN;
32
35
33
- if (read ()) {
36
+ if (read (force )) {
34
37
switch (_type) {
35
38
case DHT11:
36
39
f = data[2 ];
@@ -64,7 +67,7 @@ float DHT::convertFtoC(float f) {
64
67
return (f - 32 ) * 5 / 9 ;
65
68
}
66
69
67
- float DHT::readHumidity (void ) {
70
+ float DHT::readHumidity (bool force ) {
68
71
float f = NAN;
69
72
if (read ()) {
70
73
switch (_type) {
@@ -113,19 +116,14 @@ float DHT::computeHeatIndex(float temperature, float percentHumidity, bool isFah
113
116
}
114
117
}
115
118
116
- boolean DHT::read (void ) {
119
+ boolean DHT::read (bool force ) {
117
120
// Check if sensor was read less than two seconds ago and return early
118
121
// to use last reading.
119
122
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 )) {
125
124
return _lastresult; // return last correct measurement
126
125
}
127
- _firstreading = false ;
128
- _lastreadtime = millis ();
126
+ _lastreadtime = currenttime;
129
127
130
128
// Reset 40 bits of received data to zero.
131
129
data[0 ] = data[1 ] = data[2 ] = data[3 ] = data[4 ] = 0 ;
@@ -154,7 +152,7 @@ boolean DHT::read(void) {
154
152
delayMicroseconds (40 );
155
153
156
154
// Now start reading the data line to get the value from the DHT sensor.
157
- pinMode (_pin, INPUT );
155
+ pinMode (_pin, INPUT_PULLUP );
158
156
delayMicroseconds (10 ); // Delay a bit to let sensor pull data line low.
159
157
160
158
// First expect a low signal for ~80 microseconds followed by a high signal
0 commit comments