DHTNEW class for DHT11 and DHT12 and compatibles.

Today I pushed the DHTNEW class to github: Arduino/libraries/DHTNEW at master · RobTillaart/Arduino · GitHub

This class builds upon my experiences with my DHTlib and should replace it in time

DHTNEW has some new features compared to my DHTlib,

The DHTNEW(pin) constructor has a pin number, so the "one sensor = one object" paradigm is chosen. So you can now make a DHTNEW bathroom(4), kitchen(3) etc objects with names that are more meaningfull than a single object that could read multiple pins like the DHTlib does.

Most important, the read() function recognizes the type of sensor and it reads both DHT11 and DHT22 type sensors. It does the right internal math per sensor type. The underlying code is very much based upon the well tested DHTlib code.

An offset can be set for both temperature and humidity to have a first order calibration in the class. This solves an often mentioned problem of DHT sensors that they are a few degrees off. Of course this offset introduces a possible risk of under- or overflow (esp. humidity), the programmer should be aware of that. For a more elaborated offset I refer to my multimap class, which allows non-linear mapping of values so any calibration curve can be implemented.

Finally lastRead() keeps track of the last time the sensor is read. If this is not too long ago one can decide not to read the sensors but use the current values for temperature and humidity. This saves up to 20+ milliseconds for a DHT11 or 5+ millis for a DHT22. Note that these sensors should have 1-2 seconds between reads according to specification. In the future this functionality is planned to move inside the library by setting a time threshold.

A testsketch is available to show the working of the class.

As always, comments and remarks are welcome.


The demo code below shows the above mentioned functions and works both with a DHT11 or DHT22 connected.

//    FILE: dhtnew_minimum.ino
//  AUTHOR: Rob Tillaart
// Released to the public domain

#include <dhtnew.h>

DHTNEW mySensor(6);

void setup()
{
  Serial.begin(115200);
  Serial.println(__FILE__);
  Serial.println();

  mySensor.setHumOffset(10);
  mySensor.setTempOffset(-1.5);
}

void loop()
{
  if (millis() - mySensor.lastRead() > 2000)
  {
    mySensor.read();
    Serial.print(mySensor.humidity, 1);
    Serial.print("\t");
    Serial.println(mySensor.temperature, 1);
  }
}

// END OF FILE