RobTillaart / DHTNew

Arduino library for DHT11 and DHT22 with automatic sensor recognition
MIT License
98 stars 15 forks source link

read() should return DHTLIB_WAITING_FOR_READ when waiting for read #34

Closed budulinek closed 3 years ago

budulinek commented 3 years ago

At the moment, read() function returns DHTLIB_OK, without distinguishing between two situations:

1) Read successful 2) Waiting for read. Type is known from some previous readings (or from setType() function), but we actually do not know whether the sensor is connected or not.

Example:

#include <dhtnew.h>

DHTNEW mySensor(16);

void setup()
{
  Serial.begin(115200);
  Serial.println("start");
  Serial.println();
  mySensor.setType(22);
} 

void loop()
{
  if (mySensor.read() == DHTLIB_OK) {
    Serial.print("OK:\t");
    Serial.println(mySensor.getTemperature(), 1);
  } else {
    Serial.println("ERROR");
  }
  delay(1000);      // < DHTLIB_DHT22_READ_DELAY
}

Gives me the following output with sensor not connected:

start

OK: 0.0
OK: 0.0
ERROR
ERROR
ERROR
OK: -999.0
ERROR
ERROR
OK: -999.0
ERROR
ERROR
ERROR
OK: -999.0
ERROR

setWaitForReading(true) is not an option, I need non-blocking sketch.

I propose a simple solution: differentiate between DHTLIB_OK and DHTLIB_WAITING_FOR_READ

It will also allow us to implement non-blocking wait for read, for example:

#include <dhtnew.h>

DHTNEW mySensor(16);

void setup()
{
  Serial.begin(115200);
  Serial.println("start");
  Serial.println();
  mySensor.setType(22);
}

void loop()
{
  int chk = mySensor.read();
  if (chk != DHTLIB_WAITING_FOR_READ) {
    if (chk == DHTLIB_OK) {
      Serial.print("OK:\t");
      Serial.println(mySensor.getTemperature(), 1);
    } else {
      Serial.println("ERROR");
    }
  }
  delay(100);      // << DHTLIB_DHT22_READ_DELAY
  // do other stuff while waiting for DHT22
}
RobTillaart commented 3 years ago

Looks good and useful, Can you add the example (2) in the lib/examples folder ? e.g dhtnew_waitForRead_2.ino

budulinek commented 3 years ago

Sure, here is an example, put together from your existing examples.

budulinek commented 3 years ago

Corrected. I am still relatively new to github...

budulinek commented 3 years ago

As you can see, I have also tried to fix dhtnew_setReadDelay.ino

Now the calculation of readDelay works. I think that it is an interesting idea. What about adding calculateReadDelay() function to the library, as a complement to setReadDelay() ??

RobTillaart commented 3 years ago

Corrected. I am still relatively new to github...

Definitely not bad at all, in fact looks good to me, thanks for the updates.

I will check the code tomorrow again as now it is quite late. Tomorrow I have a pair of fresh eyes :)

budulinek commented 3 years ago

BTW, dhtnew_setReadDelay.ino calculated readDelay 434 ms for my DHT22. Quite interesting, if you compare it to default 2000 ms.

OK, good night.