Sub topic 6
Reading Temperature and Humidity
This chapter assumes you can write a basic sketch with setup() and loop(), upload it, and open the Serial Monitor. It also assumes you have wired a DHT11 or DHT22 to the Arduino with a pull-up resistor on the data line, and installed the Adafruit DHT sensor library with its Adafruit Unified Sensor dependency. Here you will read values from the sensor, understand what each call does, and learn the errors that show up most often.
The working model
The Adafruit library hides the single-wire protocol behind a DHT object. You create the object once with the data pin and the sensor type. In setup() you call begin(). After that, each call to readHumidity() or readTemperature() asks the sensor for data and returns a float.
The sensor measures slowly and keeps its latest result internally. The library also caches the last good reading. If you ask again within the minimum interval, you get the cached values, not a new measurement. So calling the read functions more often than the sensor allows does not give you fresher data. It only wastes time.
Declaring the sensor
Three lines set up the sensor. The first includes the library. The second defines the pin and type. The third creates the object.
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);DHTTYPE must match your hardware. The library supports DHT11, DHT21, and DHT22. If you declare a DHT11 as a DHT22, the library decodes the data bytes with the wrong format. You then get readings that are consistently wrong, or NaN. A DHT11 gives whole numbers, so its raw data decodes to values that are far off if treated as a DHT22 layout.
A first complete sketch
This sketch reads both values every two seconds and prints them.
#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"));
}Several details matter here.
Serial.begin(9600)must match the baud rate selected in the Serial Monitor. A mismatch prints garbage characters.dht.begin()sets the data pin up and starts the library's timing. Skipping it is a common cause of constant NaN.delay(2000)comes first inloop(). This gives the sensor time to settle after power-up on the first pass, and spaces later reads two seconds apart.- The
F()macro keeps string literals in flash memory instead of RAM. On an Uno with 2 KB of RAM this matters once a sketch grows. readHumidity()returns relative humidity as a percentage.readTemperature()returns degrees Celsius by default.
Reading order and what each call costs
Each read call can trigger a full transaction with the sensor. A transaction takes several milliseconds, because the sensor sends 40 bits and the library times each one. During this time the library disables interrupts on many boards so that the timing stays accurate. On an AVR board this means that millis() can lose a tick, and serial input can be dropped, if you read very often.
The sensor sends temperature and humidity together in one 40-bit frame. Because of the cache, calling readHumidity() and then readTemperature() right after each other normally triggers only one transaction. The second call reuses the data the first one fetched. This is why the order of the two calls does not matter, and why both values come from the same moment.
The two calls are not guaranteed to be coherent if the interval expires between them. That is rare at a two-second interval, but it is a reason to read both values in one block and not spread them across the sketch.
Selecting units
The default unit is Celsius. Pass true to get Fahrenheit.
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 third argument of computeHeatIndex() is isFahrenheit. It defaults to true. When you pass a Celsius value you must pass false. If you forget, the library treats your Celsius number as Fahrenheit, and the heat index will be far too low. This is one of the more common unit mistakes with this library.
The library converts internally. It does not take a second reading for Fahrenheit, so the two calls above come from the same data frame.
Handling a failed read
A read fails when the sensor does not answer, the pulses cannot be timed, or the checksum does not match. In that case the library returns NaN, which stands for "not a number". A comparison with NaN is always false, so you cannot test for it with ==. You must use isnan().
If you skip the check, NaN flows through your code. It prints as nan on the Serial Monitor. It also poisons any calculation it touches, because any arithmetic with NaN gives NaN. A running average that receives one NaN stays NaN forever.
The common causes, roughly from most to least frequent:
| Symptom | Likely cause | Fix |
|---|---|---|
| NaN on every read | Wrong pin, missing `begin()`, or wrong `DHTTYPE` | Check the three declaration lines |
| NaN on every read, wiring looks right | Missing pull-up resistor on the data line | Add a 4.7 kΩ to 10 kΩ resistor between data and VCC |
| Works for a few reads, then fails | Reading faster than the sensor allows | Wait at least 2 s (DHT22) or 1 s (DHT11) |
| Occasional NaN | Long wires, electrical noise, weak supply | Shorten the wire, add a 100 nF capacitor near the sensor |
| Values stuck and never change | Cached data while the interval has not passed | Check your timing logic |
| Reads fail only with other libraries | Interrupts or timing conflicts | Read less often, or avoid other interrupt-heavy code during a read |
Some boards also run at 3.3 V logic. The DHT sensors work from 3.3 V to 5 V, but at 3.3 V the data line is more sensitive to long cables.
Retrying instead of giving up
An occasional failure is normal. Instead of discarding the cycle, you can keep the last good value and count the failures. That makes a single bad read invisible, while a stuck sensor still shows up.
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
float lastTemperatureC = NAN;
float lastHumidity = NAN;
uint8_t failCount = 0;
void setup() {
Serial.begin(9600);
dht.begin();
}
void loop() {
delay(2000);
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
failCount++;
Serial.print(F("Read failed, count = "));
Serial.println(failCount);
} else {
failCount = 0;
lastHumidity = h;
lastTemperatureC = t;
}
if (failCount >= 5) {
Serial.println(F("Sensor not responding. Check wiring."));
}
if (!isnan(lastTemperatureC)) {
Serial.print(lastTemperatureC);
Serial.print(F(" C, "));
Serial.print(lastHumidity);
Serial.println(F(" %"));
}
}Starting the stored values at NAN means that before the first good read, nothing is printed, so you never show a fake zero.
Range and resolution
Know what the numbers can and cannot tell you.
| Property | DHT11 | DHT22 |
|---|---|---|
| Temperature range | 0 to 50 °C | -40 to 80 °C |
| Humidity range | 20 to 90 % | 0 to 100 % |
| Resolution | 1 unit | 0.1 unit |
| Typical accuracy | ±2 °C, ±5 % | ±0.5 °C, ±2 to 5 % |
| Minimum interval | about 1 s | about 2 s |
Printing a DHT11 value with two decimals does not add information. The sensor only reports whole numbers, so extra digits are noise or padding. Likewise a DHT22 reading of 23.46 should be understood as "about 23.5, give or take half a degree".
Common pitfalls
- Reading inside a tight loop with no delay. The sensor cannot keep up, and you get cached values or NaN.
- Using
intfor results.int humidity = dht.readHumidity();drops the decimals and also hides NaN, because NaN converted to an integer has an undefined value. Always store results infloatand test them first. - Testing with
humidity == NAN. This is always false. Useisnan(). - Holding the sensor in your hand. Body heat and breath raise both readings. That is useful for testing that the values change, but not for judging accuracy.
- Placing the sensor next to the Arduino or a regulator. The board warms the air around it, and temperature reads high.
- Printing before checking. Always check first and then print or use the value.
Check your understanding
Exercise
Your sketch calls dht.readTemperature() inside loop() with no delay, and the Serial Monitor shows the same temperature on many lines, then an occasional "nan". Explain both symptoms and give one fix.
Show answer
The DHT22 produces a new measurement only about every 2 seconds. When the sketch asks sooner, the library returns its cached value, so the same number repeats. When a read does go out to the sensor too soon after the previous transaction, the sensor may not answer or the checksum may fail, and the library returns NaN. The fix is to space reads at least 2 seconds apart, for example by putting delay(2000) at the start of loop() or by using a millis() timer, and to check each result with isnan() before using it.
Exercise
You pass a temperature in Celsius to dht.computeHeatIndex(tempC, humidity) and get a heat index that is lower than the air temperature. What went wrong, and how do you correct the call?
Show answer
The third argument, isFahrenheit, defaults to true, so the library treated the Celsius value as Fahrenheit. A number like 30 is then read as 30 °F and gives a very low heat index. Pass false as the third argument: dht.computeHeatIndex(tempC, humidity, false).