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
Become a Hackaday.io Member
Create an account to leave a comment. Already have an account? Log In.