From 5973929e63e99a61662e7e1dd1026796d8631cdc Mon Sep 17 00:00:00 2001 From: Matthijs Kooijman Date: Fri, 24 Jul 2015 21:17:16 +0200 Subject: [PATCH] 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. --- DHT.cpp | 11 +++++++---- DHT.h | 1 - 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/DHT.cpp b/DHT.cpp index 6bc87c9..e75ccfe 100644 --- a/DHT.cpp +++ b/DHT.cpp @@ -6,10 +6,11 @@ written by Adafruit Industries #include "DHT.h" +#define MIN_INTERVAL 2000 + DHT::DHT(uint8_t pin, uint8_t type, uint8_t count) { _pin = pin; _type = type; - _firstreading = true; _bit = digitalPinToBitMask(pin); _port = digitalPinToPort(pin); _maxcycles = microsecondsToClockCycles(1000); // 1 millisecond timeout for @@ -22,7 +23,10 @@ void DHT::begin(void) { // set up the pins! pinMode(_pin, INPUT); digitalWrite(_pin, HIGH); - _lastreadtime = 0; + // Using this value makes sure that millis() - lastreadtime will be + // >= MIN_INTERVAL right away. Note that this assignment wraps around, + // but so will the subtraction. + _lastreadtime = -MIN_INTERVAL; DEBUG_PRINT("Max clock cycles: "); DEBUG_PRINTLN(_maxcycles, DEC); } @@ -117,10 +121,9 @@ boolean DHT::read(bool force) { // Check if sensor was read less than two seconds ago and return early // to use last reading. uint32_t currenttime = millis(); - if (!force && !_firstreading && ((currenttime - _lastreadtime) < 2000)) { + if (!force && ((currenttime - _lastreadtime) < 2000)) { return _lastresult; // return last correct measurement } - _firstreading = false; _lastreadtime = currenttime; // Reset 40 bits of received data to zero. diff --git a/DHT.h b/DHT.h index 5040fa3..bbce4f5 100644 --- a/DHT.h +++ b/DHT.h @@ -50,7 +50,6 @@ class DHT { uint8_t data[6]; uint8_t _pin, _type, _bit, _port; uint32_t _lastreadtime, _maxcycles; - bool _firstreading; bool _lastresult; uint32_t expectPulse(bool level);