Add force parameter to read methods

This allows forcing a read, even if the previous read was less than 2
seconds ago. This is useful in cases where the millis() timer is not
reliable, such as when sleeping. In this case, it is up to the caller to
ensure that at least 2 seconds elapse between calls with force set to
true.
This commit is contained in:
Matthijs Kooijman 2015-07-24 17:37:24 +02:00
parent 5cd78aead6
commit 04905bc5cd
2 changed files with 8 additions and 8 deletions

10
DHT.cpp
View File

@ -27,10 +27,10 @@ void DHT::begin(void) {
} }
//boolean S == Scale. True == Fahrenheit; False == Celcius //boolean S == Scale. True == Fahrenheit; False == Celcius
float DHT::readTemperature(bool S) { float DHT::readTemperature(bool S, bool force) {
float f = NAN; float f = NAN;
if (read()) { if (read(force)) {
switch (_type) { switch (_type) {
case DHT11: case DHT11:
f = data[2]; f = data[2];
@ -64,7 +64,7 @@ float DHT::convertFtoC(float f) {
return (f - 32) * 5 / 9; return (f - 32) * 5 / 9;
} }
float DHT::readHumidity(void) { float DHT::readHumidity(bool force) {
float f = NAN; float f = NAN;
if (read()) { if (read()) {
switch (_type) { switch (_type) {
@ -113,7 +113,7 @@ float DHT::computeHeatIndex(float temperature, float percentHumidity, bool isFah
} }
} }
boolean DHT::read(void) { boolean DHT::read(bool force) {
// Check if sensor was read less than two seconds ago and return early // Check if sensor was read less than two seconds ago and return early
// to use last reading. // to use last reading.
uint32_t currenttime = millis(); uint32_t currenttime = millis();
@ -121,7 +121,7 @@ boolean DHT::read(void) {
// ie there was a rollover // ie there was a rollover
_lastreadtime = 0; _lastreadtime = 0;
} }
if (!_firstreading && ((currenttime - _lastreadtime) < 2000)) { if (!force && !_firstreading && ((currenttime - _lastreadtime) < 2000)) {
return _lastresult; // return last correct measurement return _lastresult; // return last correct measurement
} }
_firstreading = false; _firstreading = false;

6
DHT.h
View File

@ -39,12 +39,12 @@ class DHT {
public: public:
DHT(uint8_t pin, uint8_t type, uint8_t count=6); DHT(uint8_t pin, uint8_t type, uint8_t count=6);
void begin(void); void begin(void);
float readTemperature(bool S=false); float readTemperature(bool S=false, bool force=false);
float convertCtoF(float); float convertCtoF(float);
float convertFtoC(float); float convertFtoC(float);
float computeHeatIndex(float temperature, float percentHumidity, bool isFahrenheit=true); float computeHeatIndex(float temperature, float percentHumidity, bool isFahrenheit=true);
float readHumidity(void); float readHumidity(bool force=false);
boolean read(void); boolean read(bool force=false);
private: private:
uint8_t data[6]; uint8_t data[6];