Class for DHT11, DHT21 and DHT22 (temperature & humidity)

Well done Mark,

Looked at your code and it looks like a decent piece of work. It is similar to a version I'm working on and yes I better stop with that version :wink:

The difference between your code and mine is that your code encapsulated an individual sensor while mine encapsulates the handshake so multiple sensors use one instance.
Footprint will differ too but not measured. I like the auto-detect functionality, well done

There is one improvement I want to propose to your class which I had build in my draft. If there is a time-out I would return the previous values instead of NaN. The error flag should still be the same. To do this the results temperature & humidity should have class scope.

If the program requests the temperature too fast it just gets the prev value which is seldom far from the actual value (instead of a NaN)

something like this

DHT::DHT_t DHT::read()
{
  // don't poll the sensor too often
  // - Max sample rate DHT11 is 1 Hz   (duty cycle 1000 ms)
  // - Max sample rate DHT22 is 0.5 Hz (duty cycle 2000 ms)

  unsigned long startTime = millis();
  if ( (startTime - lastReadTime) < getMinimalDelay()  )   // use the internal function
  {
   results.error = ERROR_TOO_QUICK;
   return results;  // returns previous temperature and humidity
  }
  lastReadTime = startTime;

  results.error = ERROR_NONE;
  results.temperature = NAN;
  results.humidity = NAN;
  // Request sample
  ...

the way I coded the interface was 3 public functions

float DHT::getHumidity()
{
  if ( millis() - lastReadTime > 2000 || status != ERROR_NONE )  // time to refresh or to retry
  {
    status = read();  // fetch new hum & temp
  }
  else 
  {
    lastReadTime  = millis();
  }
  return humidity;
}


float DHT::getTemperature()
{
  if ( millis() - lastReadTime > 2000 || status != ERROR_NONE ) 
  {
    status = read(); // status and read() are private
  }
  else 
  {
    lastReadTime  = millis();
  }
  return temperature;  // private member
}

float DHT::getStatus()
{
   status = read();  // fetch new data
}

typing this you could also add the "retry" condition.

my 2 cents,
regards / groeten,
Rob