Sub topic 7
Detecting Failed Readings
This chapter assumes you can wire a DHT11 or DHT22 to an Arduino, have the Adafruit DHT library installed, and can read temperature and humidity in a basic sketch. It covers how a read fails, how to detect it, and how to respond.
Why DHT reads fail
A DHT sensor sends its data over one wire, and the Arduino must sample that wire at precise moments. The read can fail in several ways:
- The sensor does not answer the start signal, usually because of a wiring fault or no power.
- The pull-up resistor is missing, so the data line never returns to a clean high level.
- The pulses arrive but the checksum does not match, which means at least one bit was misread.
- The sketch calls the sensor again before it has finished preparing a new measurement.
- Interrupts on the board disturb the timing while the library is sampling bits.
When any of these happens, the library does not stop your sketch or raise an error. It returns a special value, and your code has to check for it.
What the library returns
readHumidity() and readTemperature() return a float. On failure they return NaN, short for "not a number". NaN is a legal floating-point value that means "no valid result".
NaN has an unusual property: it is not equal to anything, including itself. This means you cannot test for it with ==.
float h = dht.readHumidity();
if (h == NAN) {
// Never runs. A comparison with NaN is always false.
}Use isnan() instead. It returns true only when the value is NaN.
float h = dht.readHumidity();
if (isnan(h)) {
Serial.println(F("Humidity read failed"));
}The basic check
The standard pattern reads both values, then rejects the whole sample if either one failed.
#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"));
}Three details matter here.
- The
||operator means one bad value discards the sample. Humidity and temperature come from the same transmission, so if one is bad you should not trust the other. returnends this pass throughloop(). The next pass tries again after the delay.F("...")keeps the message text in flash memory instead of RAM. This matters on small boards such as the Uno, which has 2 KB of RAM.
If you convert units, check every value you request. readTemperature(true) returns Fahrenheit and can also return NaN.
float temperatureF = dht.readTemperature(true);
float temperatureC = dht.readTemperature();
float humidity = dht.readHumidity();
if (!isnan(temperatureF) && !isnan(temperatureC) && !isnan(humidity)) {
float heatIndexF = dht.computeHeatIndex(temperatureF, humidity);
float heatIndexC = dht.computeHeatIndex(temperatureC, humidity, false);
}The pattern here is the reverse: compute only when all three values are valid.
What the check does not catch
isnan() finds failed reads. It does not find wrong reads. A sensor can return a valid number that is still bad, for example when the sensor is damaged, wet, or near a heat source.
A cheap extra guard is a range check against the sensor's datasheet limits. The DHT22 measures about -40 to 80 °C and 0 to 100 % humidity. The DHT11 measures about 0 to 50 °C and 20 to 90 % humidity.
bool plausibleDht22(float tempC, float humidity) {
return tempC >= -40.0 && tempC <= 80.0 &&
humidity >= 0.0 && humidity <= 100.0;
}Call it after the isnan check. A value outside the range means a fault, not a real measurement.
Common causes and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| Every read fails from the start | Wrong pin, wrong power or ground, or wrong `DHTTYPE` | Check the wiring against the pin number in `DHTPIN` and confirm the type matches the sensor |
| Every read fails with a bare sensor | No pull-up resistor on the data line | Add a 4.7 kΩ to 10 kΩ resistor between data and VCC (many breakout boards include one) |
| Reads fail now and then | Calls are too frequent, or the wire is long and noisy | Wait at least the minimum interval, shorten the wire, or lower the pull-up value |
| Works on a 5 V board, fails on a 3.3 V board | Supply voltage too low for the sensor or the pull-up | Power the sensor from 3.3 V or 5 V as its datasheet allows, and match the pull-up to the logic level |
| Fails only when other code runs | Interrupts or long tasks disturb the timing | Keep the read away from heavy interrupt use, and keep other work out of the way |
Retrying a failed read
Occasional failures are normal, so one retry often saves a sample. Wait before retrying, because the sensor needs time between reads. The DHT22 needs about 2 seconds, and the DHT11 needs about 1 second.
bool readDht(float &tempC, float &humidity, int attempts) {
for (int i = 0; i < attempts; i++) {
humidity = dht.readHumidity();
tempC = dht.readTemperature();
if (!isnan(humidity) && !isnan(tempC)) {
return true;
}
delay(2000);
}
return false;
}The function returns true and fills in the two variables on success. The & makes the parameters references, so the function writes into the caller's variables. The caller then decides what to do on failure.
void loop() {
float t, h;
if (readDht(t, h, 3)) {
Serial.print(t);
Serial.print(',');
Serial.println(h);
} else {
Serial.println(F("Sensor unavailable"));
}
delay(2000);
}Limit the number of attempts. A sensor that is unplugged will fail forever, and an unbounded retry loop would freeze the sketch.
Tracking repeated failures
A single failure is noise. A long run of failures is a fault. Count consecutive failures and react when the count passes a limit.
const int MAX_FAILURES = 5;
int failureCount = 0;
void recordResult(bool ok) {
if (ok) {
failureCount = 0;
} else if (failureCount < MAX_FAILURES) {
failureCount++;
}
}
bool sensorFaulted() {
return failureCount >= MAX_FAILURES;
}Reset the counter on every success so that scattered errors never add up to a false alarm. When sensorFaulted() is true, you can turn on an error LED, print a clear message, or stop acting on old data.
Do not reuse stale values
A common mistake is to keep the last good reading in a variable and keep using it after reads start failing. Your output then looks healthy while the sensor is dead. If you store the last good value, store the time it was taken as well, and treat it as expired after a set age.
float lastTempC = 0.0;
unsigned long lastGoodMs = 0;
const unsigned long MAX_AGE_MS = 30000;
bool lastValueFresh() {
return (millis() - lastGoodMs) <= MAX_AGE_MS;
}Update lastTempC and lastGoodMs only on a valid read. Subtracting lastGoodMs from millis() stays correct even when millis() wraps around after about 49 days, because the arithmetic uses unsigned numbers.
The flow of a safe read
Edge cases
- First read after power-up. The sensor needs about one to two seconds to settle. A read right after
dht.begin()can fail, so wait before the first call. - Cached results. The library returns the previous result if you call it again before the minimum interval has passed. That value is valid but old, so calling too quickly hides the problem instead of showing it.
- Partial failure. Because both values come from one transmission, treat a
NaNin either as a failure of both. - Long cables. Cable capacitance rounds off the pulses. Keep the wire short, ideally under about 20 m for a DHT22, and under a few metres when prototyping with a weak pull-up.
Summary of the approach
- Read both values.
- Check each one with
isnan(). - Optionally check that the values are plausible.
- Retry a small, fixed number of times with the required delay.
- Count consecutive failures and flag a fault past a limit.
- Never present old data as current.
Exercise
A sketch contains if (temperatureC == NAN) { ... } to catch failed reads, but the block never runs even when the sensor is unplugged. Why, and what is the fix?
Show answer
A comparison with NaN is always false, because NaN is not equal to any value, including itself. Replace the test with if (isnan(temperatureC)) { ... }.
Exercise
Your sketch reads humidity and temperature, and humidity returns a valid number while temperature returns NaN. Should you use the humidity value? Give one reason.
Show answer
No. Both values come from the same transmission, so a failure in one means the sample is not trustworthy. Check both with isnan and discard the whole sample if either is NaN.
Exercise
Why should a retry loop have a fixed maximum number of attempts, and what should the sketch do when the limit is reached?
Show answer
An unplugged or broken sensor fails every time, so an unbounded loop would freeze the sketch. After the limit, return a failure to the caller, which can count it, show an error, and stop using old data.