Sub topic 12
Reading without blocking the sketch
This chapter assumes you can wire a DHT22 (or DHT11) to an Arduino, read values with the Adafruit DHT library, and check for NaN results. It also assumes you know setup() and loop(), and the float, unsigned long, and bool types. Here you replace delay() with millis() timing so the sensor reads on schedule while the rest of the sketch keeps running.
Why delay() causes trouble
A DHT22 cannot be read more often than once every two seconds. The simplest way to respect that limit is delay(2000) at the top of loop(). That works for a sketch that does nothing else.
delay() is blocking. The processor sits in a wait loop and runs none of your other code until the time is up. In a sketch with a button, a display refresh, or a second sensor, you see these symptoms:
- A button press shorter than two seconds is missed, because nothing reads the pin while the sketch is waiting.
- An LED blink pattern stutters, because its timing is tied to the sensor's pace.
- Serial commands pile up in the receive buffer, which holds only 64 bytes on most AVR boards, so data can be lost.
The fix is to ask a different question on every pass through loop(): "Has enough time passed since the last read?" If not, skip the read and continue. The sketch then spins through loop() thousands of times per second and reads the sensor only when it is due.
Timing with millis()
millis() returns the number of milliseconds since the board started. It is an unsigned long, a 32-bit unsigned integer. You store the time of the last read and compare it to the current time.
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
const unsigned long READ_INTERVAL_MS = 2000;
unsigned long lastReadMs = 0;
void setup() {
Serial.begin(9600);
dht.begin();
}
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().
}The pattern has three parts:
- Read the clock once into
now, so every comparison in this pass uses the same value. - Compare the elapsed time,
now - lastReadMs, to the interval. - When the interval has passed, update
lastReadMsand do the work.
Each pass through loop() costs only a few microseconds when the read is not due. The read itself still blocks for a few milliseconds, because the single-wire protocol is bit-banged by the library. Non-blocking here means "the sketch is not idle for two seconds", not "the read takes no time".
Why subtraction survives rollover
On AVR boards, millis() wraps back to 0 after about 49.7 days, because a 32-bit counter holds 4,294,967,295 milliseconds at most. A sketch that runs for weeks will meet this.
Compare elapsed time with subtraction, as above. Do not compare timestamps directly. This version breaks at rollover:
// Wrong: fails when millis() wraps around
if (millis() >= lastReadMs + READ_INTERVAL_MS) {
// ...
}Suppose lastReadMs is 4,294,966,000 and the interval is 2000. The sum exceeds the 32-bit range and wraps to a small number, so the condition is true on every pass. The sensor is then read far too often, and the DHT returns stale values or NaN.
The subtraction form works because unsigned arithmetic is modular. If now has wrapped to 500 and lastReadMs is 4,294,966,000, then now - lastReadMs evaluates to 1,796. That is the true elapsed time. This holds only when both variables and the result are unsigned long. If you store the timestamp in an int, the pattern breaks after about 32 seconds.
Drift and the fixed schedule
The code above sets lastReadMs = now. If loop() is slow on some pass, the read happens late, and the next one is scheduled two seconds after that late read. Over time the readings drift. For a DHT sensor this is fine, because the interval is a minimum.
If you want evenly spaced samples, for example for logging with timestamps, advance the schedule by the interval instead:
lastReadMs += READ_INTERVAL_MS;This keeps the average rate exact. The cost is that after a long stall, such as a blocking call elsewhere, several reads become due in quick succession, and the DHT will return NaN or repeated values for the ones that come too soon. If you use this form, guard against catch-up by resetting lastReadMs = now when the sketch has fallen more than one interval behind.
| Approach | Update line | Behavior | Use when |
|---|---|---|---|
| Reset to now | `lastReadMs = now;` | Interval is at least 2 s, may drift | Display or control loops where spacing is not critical |
| Advance by interval | `lastReadMs += READ_INTERVAL_MS;` | Average rate is exact, risk of burst after a stall | Timestamped logging with a guard against stalls |
Doing other work in the same loop
The benefit appears when loop() has other tasks. This sketch blinks an LED every 500 ms, reads the DHT22 every 2000 ms, and prints the values. Each task has its own timestamp.
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT22
#define LED_PIN LED_BUILTIN
DHT dht(DHTPIN, DHTTYPE);
const unsigned long READ_INTERVAL_MS = 2000;
const unsigned long BLINK_INTERVAL_MS = 500;
unsigned long lastReadMs = 0;
unsigned long lastBlinkMs = 0;
bool ledOn = false;
float lastTempC = NAN;
float lastHumidity = NAN;
void setup() {
Serial.begin(9600);
pinMode(LED_PIN, OUTPUT);
dht.begin();
}
void loop() {
unsigned long now = millis();
if (now - lastBlinkMs >= BLINK_INTERVAL_MS) {
lastBlinkMs = now;
ledOn = !ledOn;
digitalWrite(LED_PIN, ledOn ? HIGH : LOW);
}
if (now - lastReadMs >= READ_INTERVAL_MS) {
lastReadMs = now;
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println(F("Read failed, keeping last good values"));
} else {
lastHumidity = h;
lastTempC = t;
Serial.print(lastTempC);
Serial.print(',');
Serial.println(lastHumidity);
}
}
}Two details matter here. First, the sketch keeps lastTempC and lastHumidity as the last good readings, so other code can use them at any time without calling the sensor. Second, a failed read does not overwrite them with NaN. Code that decides, say, whether to switch a fan can keep working from the most recent valid data.
The blink will show a brief hiccup, a few milliseconds, each time the sensor is read. That is the cost of the bit-banged read, and it is invisible for a blinking LED. It matters for tight real-time work such as driving a stepper motor at high speed or reading a fast serial stream, where you should consider a sensor with a hardware interface (see the I2C chapter).
Structuring the timing as a function
When a sketch has several timed tasks, repeating the comparison gets noisy. A small helper keeps each task readable:
bool intervalElapsed(unsigned long &lastMs, unsigned long intervalMs) {
unsigned long now = millis();
if (now - lastMs >= intervalMs) {
lastMs = now;
return true;
}
return false;
}The helper takes the timestamp by reference, so it updates the caller's variable. The loop then reads:
if (intervalElapsed(lastReadMs, READ_INTERVAL_MS)) {
// read the sensor
}Common errors
- Reading before the sensor is ready. With
lastReadMs = 0, the first read happens as soon asmillis()reaches 2000, which gives the sensor its warm-up time. If you want an immediate first read, wait for the sensor to settle after power-up first, because the DHT22 needs about two seconds after power is applied. - Using
delay()inside the read block. Adelay(100)added for debounce or smoothing inside the timed block brings blocking back. Replace it with another timestamp. - Calling the sensor from several places. If two parts of the sketch call
dht.readTemperature()anddht.readHumidity()independently, the library may read the sensor twice within the minimum interval. The Adafruit library caches results for two seconds and returns the previous values on a too-early call, so you do not get an error, but you also do not get fresh data. Read once on a schedule and share the stored values. - Interval shorter than the sensor allows. A DHT11 can be read about once per second and a DHT22 once per two seconds. Setting
READ_INTERVAL_MSbelow these limits yields repeated orNaNvalues. - Wrong type for elapsed time. Mixing
intwithunsigned longin the comparison gives incorrect results after 32 seconds, or at rollover.
Execution flow
The diagram shows what happens on each pass through loop() in the combined sketch.
Exercise
A sketch stores its last read time in int lastReadMs and uses if (millis() - lastReadMs >= 2000). It works for the first half minute, then behaves oddly. Explain what goes wrong and give the fix.
Show answer
An int on AVR boards is 16 bits and holds at most 32,767, which millis() passes after about 32.8 seconds. Once millis() is larger than that, lastReadMs cannot hold the value assigned to it, so it overflows and the computed elapsed time is wrong, which breaks the 2000 ms check. The fix is to declare unsigned long lastReadMs = 0;, matching the type returned by millis(), so the unsigned subtraction stays correct even when the counter rolls over after about 49.7 days.
Exercise
Extend the combined sketch so a second LED on pin 8 turns on whenever the last good temperature is above 28 C, without adding any delay() calls and without reading the sensor more often than every two seconds. Which variable should the check use, and where does it go?
Show answer
Add pinMode(8, OUTPUT); in setup(). Then, outside the timed read block and on every pass through loop(), add digitalWrite(8, (!isnan(lastTempC) && lastTempC > 28.0) ? HIGH : LOW);. The check uses lastTempC, the stored last good reading, not a new call to the sensor. The isnan test covers the period before the first successful read, because lastTempC starts as NAN.