Sub topic 8
Respecting the sampling interval
This chapter assumes you can wire a DHT11 or DHT22, install the Adafruit DHT library, and read values with readTemperature() and readHumidity(). It also assumes you know setup(), loop(), float, and isnan(). Here you will learn why the sensor limits how often you can read it, what happens when you ignore the limit, and how to build a sketch that stays inside it.
Why the limit exists
A DHT sensor is not a continuous analog output. It contains a humidity element, a temperature element, and a small chip that converts both measurements to digital values. When you request a reading, the chip sends the result of its most recent measurement. The chip needs time to measure again before it can send a fresh result.
The datasheet minimum gaps between requests are:
| Sensor | Minimum interval | Maximum rate |
|---|---|---|
| DHT11 | 1 second | 1 Hz |
| DHT22 (AM2302) | 2 seconds | 0.5 Hz |
These are the shortest gaps you can rely on. A cheaper clone or a sensor on a long cable may need more. Using 2 seconds for both types is a safe default for a sketch that must work with either.
What the library does when you ask too soon
The Adafruit DHT library records the time of the last read in a variable. If you call a read function before the minimum interval has passed, the library does not talk to the sensor again. It returns the values it cached from the previous successful read.
This produces a symptom that is easy to misread. Your sketch reports plausible numbers, but they repeat. If you read five times in one second, you get one real measurement and four copies. The code works, and the data is stale.
The cache also explains a second effect. The first read after dht.begin() always goes to the sensor, because there is no cached value yet. Calls made too soon after a failed read can return NaN again, because the cache holds the failure.
Sampling interval and response time are different
Two numbers are easy to confuse.
- The sampling interval is how often the chip can deliver a new measurement. It is 1 to 2 seconds.
- The response time is how quickly the sensing element follows a change in the air. For the DHT22 this is roughly 2 seconds for humidity and longer for temperature, and it depends on airflow.
Even when you read every 2 seconds, the values do not jump to match the room. If you carry the sensor from a cold porch into a warm kitchen, the readings move gradually over many seconds. Temperature and humidity in a room also change slowly. For most monitoring projects, one reading every 10 to 60 seconds loses no useful information.
A separate cause: self-heating
Reading as often as allowed also warms the sensor slightly. The chip dissipates a little power each time it measures. At the 2-second limit this effect is small, but a sensor that is enclosed and read continuously can read a fraction of a degree high. Sampling every 30 seconds or more reduces the effect. This matters most when you care about absolute accuracy, which a later chapter covers.
The simple approach: delay
The basic sketch from earlier chapters enforces the interval with delay(2000) at the top of loop().
#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"));
}Placing the delay() first has a useful property. The delay runs on every pass, including passes that end early with return after a failed read. The sketch therefore never retries sooner than 2 seconds, whatever the outcome. If you put the delay at the bottom instead, an early return skips it and the next read happens immediately.
The cost is that delay() blocks everything. While it waits, the Arduino cannot check a button, update a display, or drive a motor. A sketch that must stay responsive needs a different structure.
Two calls, one measurement
readHumidity() and readTemperature() are separate function calls, but the sensor sends both values in one transfer. The library reads the whole frame on the first call and serves the second call from the cache, as long as the second call happens within the interval.
This has a practical consequence. Call both functions together, one right after the other, so both values come from the same measurement. If you call readHumidity(), wait several seconds, and then call readTemperature(), the second call triggers a new transfer and the two values describe different moments.
Scheduling with millis
To keep the sketch running while you wait, compare elapsed time instead of pausing. The function millis() returns the number of milliseconds since the board started. You store the time of the last read and read again only when enough time has passed.
const unsigned long READ_INTERVAL_MS = 2000;
unsigned long lastReadMs = 0;
void loop() {
unsigned long now = millis();
if (now - lastReadMs >= READ_INTERVAL_MS) {
lastReadMs = now;
float humidity = dht.readHumidity();
float temperatureC = dht.readTemperature();
if (!isnan(humidity) && !isnan(temperatureC)) {
Serial.print(temperatureC);
Serial.print(',');
Serial.println(humidity);
}
}
// Other work can run here on every pass through loop().
}Check these details when you write this pattern.
- Use
unsigned longfor time variables.millis()returns that type, and a smaller type overflows quickly. - Subtract, then compare:
now - lastReadMs >= interval. This stays correct whenmillis()wraps back to zero after about 49.7 days, because unsigned subtraction wraps the same way. - Do not write
now >= lastReadMs + interval. That form breaks at the wrap. - Set
lastReadMs = nowbefore the read, as shown. The read itself takes a few milliseconds, and this keeps the schedule steady instead of drifting. - The first pass runs a read right away, because
lastReadMsstarts at 0 andnowis already greater than 2000 only after two seconds. If your board needs the first value earlier, that is fine, since the library does not hold a cache yet. If you want the first read to wait, leave the code as is.
The read call itself still blocks for a short time. The library bit-bangs the protocol and disables interrupts during the timing-critical part, for a few milliseconds. This is far shorter than a delay(2000), but it matters if you also run something with strict timing, such as software serial or addressable LED strips.
Choosing an interval
Pick the interval from what the project needs, not from the minimum.
| Project | Suggested interval | Reason |
|---|---|---|
| Quick test on the bench | 2 seconds | Fast feedback while debugging |
| Room display | 5 to 10 seconds | Room air changes slowly |
| Data logger | 30 to 300 seconds | Smaller files, less self-heating |
| Battery-powered node | Minutes, with sleep | Power use dominates |
For a battery project, the interval also sets the power budget. The sensor draws only a small current during a read, so the board is the main consumer. Sleeping between reads saves far more than any change to the sensor code.
Common errors
- Reading in a tight loop with no timing. You get repeated values and sometimes
NaN. - Putting the delay after an early
return, so failed reads retry immediately. - Using
intforlastReadMs. The value overflows after about 32 seconds on an AVR board, and the schedule breaks. - Treating repeated identical values as proof the room is stable. Check your timing first.
- Reading temperature and humidity far apart, so they come from different measurements.
- Assuming a 1-second interval works for a DHT22. It needs 2 seconds.
Exercise
A sketch reads a DHT22 inside loop() with no delay and prints the result each pass. The Serial Monitor shows the same temperature on many consecutive lines, then a new value every two seconds or so. Explain why, and give two ways to fix the sketch so it prints one line per real measurement.
Show answer
The library caches the last result and returns it when a read is requested before the 2-second minimum interval has passed, so most lines repeat a cached value. Fix 1: put delay(2000); at the start of loop(). Fix 2: use millis() to store the time of the last read and read and print only when now - lastReadMs >= 2000, which also leaves loop() free for other work.
Exercise
Why is if (now - lastReadMs >= READ_INTERVAL_MS) preferred over if (now >= lastReadMs + READ_INTERVAL_MS) when millis() can wrap around?
Show answer
millis() returns an unsigned long that wraps to 0 after about 49.7 days. Unsigned subtraction wraps the same way, so now - lastReadMs still gives the correct elapsed time across the wrap. The addition form computes a value that can overflow or stay larger than now near the wrap, so the check misfires for one interval.