Close

Temperature and Humidity Sensor

A project log for Desk Buddy

A small device that lets work colleagues know if you'll be at your desk today so they know if they can sit there.

tony-kambourakisTony Kambourakis 05/14/2017 at 00:360 Comments

The DHT22 is a popular and simple to use temperature and humidity sensor comprising a single Data pin with VCC and GND.

The DHT22 is connected to the NodeMCU via the D2 pin (GPIO4) and initiated with the following code:

// Temperature and Humidity Sensor (DHT22) Configuration
#define DHTPIN D2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
This code utilises the DHT sensor Library (ID 19) installed within Platform.io. Note that there are a few DHT22 libraries, I found this one worked best for me with the DHT22 and NodeMCU under platform.io.

When reading the temperature and humidity it is important to check that actual values are returned using isnan().

void readDHTSensor() {
   // reading DHT22

  h = dht.readHumidity();
  t = dht.readTemperature();

  // Check if we fail to read from the DHT sensor
  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor");
    publishDebug("Failed to read from DHT sensor");
    //TODO: Do more here
  }

  hic = dht.computeHeatIndex(t, h, false);
}

Discussions