Skip to content

Commit 5973929

Browse files
Remove the firstreading variable
By cleverly setting _lastreadtime in begin() to make sure that it looks like the last read was alrady 2000 ms ago, even on startup when millis() still returns 0, there is no longer a need to keep a separate firstreading variable, saving a byte of memory and a bit of code.
1 parent f1b7902 commit 5973929

File tree

2 files changed

+7
-5
lines changed

2 files changed

+7
-5
lines changed

DHT.cpp

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,11 @@ written by Adafruit Industries
66

77
#include "DHT.h"
88

9+
#define MIN_INTERVAL 2000
10+
911
DHT::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
@@ -22,7 +23,10 @@ void DHT::begin(void) {
2223
// set up the pins!
2324
pinMode(_pin, INPUT);
2425
digitalWrite(_pin, HIGH);
25-
_lastreadtime = 0;
26+
// Using this value makes sure that millis() - lastreadtime will be
27+
// >= MIN_INTERVAL right away. Note that this assignment wraps around,
28+
// but so will the subtraction.
29+
_lastreadtime = -MIN_INTERVAL;
2630
DEBUG_PRINT("Max clock cycles: "); DEBUG_PRINTLN(_maxcycles, DEC);
2731
}
2832

@@ -117,10 +121,9 @@ boolean DHT::read(bool force) {
117121
// Check if sensor was read less than two seconds ago and return early
118122
// to use last reading.
119123
uint32_t currenttime = millis();
120-
if (!force && !_firstreading && ((currenttime - _lastreadtime) < 2000)) {
124+
if (!force && ((currenttime - _lastreadtime) < 2000)) {
121125
return _lastresult; // return last correct measurement
122126
}
123-
_firstreading = false;
124127
_lastreadtime = currenttime;
125128

126129
// Reset 40 bits of received data to zero.

DHT.h

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,6 @@ class DHT {
5050
uint8_t data[6];
5151
uint8_t _pin, _type, _bit, _port;
5252
uint32_t _lastreadtime, _maxcycles;
53-
bool _firstreading;
5453
bool _lastresult;
5554

5655
uint32_t expectPulse(bool level);

0 commit comments

Comments
 (0)