Sub topic 7
Detecting Failed Readings from a DHT Sensor
Assume you know the Arduino setup() and loop() structure, can upload a sketch, and can read the Serial Monitor. You should also know basic C++ types such as float.
A DHT11 or DHT22 can fail to return a valid measurement. The wiring may be wrong, the sensor may be read too quickly, or electrical noise may interrupt its response. Your sketch must check each result before using it.
What `NaN` Means
The Adafruit DHT library returns NaN when it cannot decode a valid temperature or humidity value. NaN means “not a number.” It is a special floating-point value used to represent an undefined or invalid result.
Do not compare it with a normal number. For example, this check is unreliable:
if (temperature == NAN) {
// This is not the correct test.
}Use the isnan() function instead:
if (isnan(temperature)) {
// The reading failed.
}Check both values. A sensor transaction can produce an invalid temperature, invalid humidity, or both.
Check Before Using a Reading
The following sketch reads a DHT22 on digital pin 2. It prints a measurement only when both values are valid.
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
dht.begin();
}
void loop() {
delay(2000);
float humidity = dht.readHumidity();
float temperatureC = dht.readTemperature();
if (isnan(humidity) || isnan(temperatureC)) {
Serial.println(F("Failed to read from DHT sensor."));
return;
}
Serial.print(F("Humidity: "));
Serial.print(humidity);
Serial.print(F(" % Temperature: "));
Serial.print(temperatureC);
Serial.println(F(" C"));
}The || operator means “or.” Therefore, the error branch runs if humidity is invalid or temperature is invalid.
The return statement exits the current pass through loop(). It prevents the rest of the code from using bad values. Arduino calls loop() again immediately afterward, so the sketch can try again on the next cycle.
Preserve the Last Valid Measurement
Sometimes a project should continue displaying the last known good value instead of showing an error value. Store a new reading only after validation.
float lastTemperatureC = NAN;
float lastHumidity = NAN;
void updateSensorValues() {
float newHumidity = dht.readHumidity();
float newTemperatureC = dht.readTemperature();
if (isnan(newHumidity) || isnan(newTemperatureC)) {
Serial.println(F("Reading failed; keeping the previous values."));
return;
}
lastHumidity = newHumidity;
lastTemperatureC = newTemperatureC;
}This approach keeps invalid data out of the stored state. However, the display should indicate that the value is old if failures continue. A timestamp or failure counter can help you detect a sensor that has stopped responding.
Common Causes
| Symptom | Likely cause | First check |
|---|---|---|
| Every reading is `NaN` | Wrong wiring or sensor type | Power, ground, data pin, and `DHTTYPE` |
| Occasional failures | Electrical noise or loose wires | Connections and cable length |
| Failures after fast reads | Sampling interval is too short | Wait at least two seconds |
| Humidity seems impossible | Damaged or unsuitable sensor | Test with a known-good sensor |
Exercise
Why should a sketch test both humidity and temperatureC with isnan() before using either value?
Show answer
Either result can be invalid, and using an invalid value can produce incorrect calculations or unsafe control decisions.