Skip to content

Temperature and Humidity with DHT

Temperature and Humidity with DHT

The DHT family packs temperature and humidity into one part and reports both over a single wire using a custom protocol. It is cheap and quick to integrate, but its accuracy and timing fragility are written into its design. By the end of this section you will be able to:

  • Tell what actually separates DHT11 from DHT22 in accuracy, range and sampling cadence
  • Understand why its single-wire timing gets broken by Wi-Fi interrupts, and how to tolerate that in engineering terms
  • Write sampling code with retries and validity gates instead of “one failure means the sensor is dead”
  • Judge when to move to an I2C digital humidity/temperature part instead

Before starting this section, make sure you:

  • Completed Sections 2 and 4 of Chapter 25
  • Have a DHT11 or DHT22 (AM2302) module
  • Have a trustworthy reference thermo-hygrometer to compare against (a phone app does not count)

Three tiers of part, and where the differences lie

Section titled “Three tiers of part, and where the differences lie”
Aspect DHT11 DHT22 / AM2302 SHT30 (I2C, for comparison)
Temperature accuracy ±2 °C ±0.5 °C ±0.3 °C
Temperature range 0…50 °C −40…+80 °C −40…+125 °C
Humidity accuracy ±5 %RH ±2–3 %RH ±2–3 %RH
Humidity range 20…90 %RH 0…100 %RH 0…100 %RH
Output granularity Integer humidity and temperature (decimals often 0) 0.1 %RH, 0.1 °C 14-bit, with CRC
Minimum sampling interval 1 s 0.5 s output, plan for 2 s As needed, milliseconds
Interface Custom single-wire timing Custom single-wire timing Standard I2C
Pull-up 4.7–10 kΩ 4.7–10 kΩ Already on the bus
Part cost Lowest Medium Medium-high

The sentence that must be said plainly: DHT11’s ±5 %RH and ±2 °C mean it can only tell you “dryish / damp / roughly this warm”. If a customer writes “humidity ±3 %” into an acceptance sheet, a DHT11 is simply the wrong part — switch to DHT22 or SHT30 at quotation stage instead of explaining afterwards.

My selection rule: teaching demos, humidity trend logging, loose alarm thresholds (e.g. alert above 80 %RH) → DHT11. Environmental monitoring, greenhouses and warehousing, any figure that ends up in a report → DHT22 at minimum. Production products that need long-term stability and verifiable data → I2C SHT3x.

A DHT frame is 40 bits: humidity integer, humidity decimal, temperature integer, temperature decimal, checksum. Bits are distinguished by how long the line stays high — a short high is 0, a long high is 1, on a scale of tens of microseconds. The host must:

  1. Pull the line low for at least 1 ms (18 ms is customary for DHT11 start)
  2. Release the bus and wait for the device’s response pulse
  3. Perform 40 iterations of “pull low, then measure high-pulse width”
  4. Sum the bytes, compare the checksum, discard on mismatch

That is microsecond-scale bit-banging. The catch is that the ESP32 Wi-Fi stack generates non-deferrable interrupts; when one lands mid-bit, the measured widths are wrong and the checksum fails. Consequently:

  • A failed frame is normal behaviour, not a broken part. Retry two or three times, and trigger an alarm only after N consecutive failed rounds.
  • Slowing the sampling rate is the most effective mitigation. Humidity is a slow variable; 2–30 s is plenty.
  • To escape timing risk entirely, move to an I2C part: standard protocol, CRC-protected payloads, and drivers an order of magnitude more predictable.

Condensation: the number-one cause of a stuck humidity reading

Section titled “Condensation: the number-one cause of a stuck humidity reading”

The DHT’s sensing element is a capacitive polymer film. Once condensation forms, the water film lingers and the reading parks high (often above 90 %) for a long time; recovery needs tens of minutes to hours in dry air. Typical triggers:

  • The part mounted on a cold surface (metal enclosure, condensing cabinet wall)
  • Direct exposure to an ultrasonic mist outlet, an air-conditioner jet, or human breath
  • Outdoor enclosures with large day-night swings and no ventilation or anti-condensation design

This is a mechanical design problem, not a software bug. Mitigations: suspend the sensor in flowing air away from walls and thermal bridges, add a breathable cover (keeps dust and splash out but does not block vapour), and add a firmware “sustained high humidity timeout” alert so operations can check for condensation.

The worst failure mode is silently continuing to report the last good value after sampling stops working — the data looks stable while having decoupled from reality. Report a status instead:

Field Values Purpose
hum / temp Number or empty The actual reading
sensor_status ok / retry / fail Lets dashboards and alarms distinguish “no data” from “data is zero”
retry_count 0–3 Long-run indicator of bus health; sustained growth predicts wiring or supply degradation

This hooks directly into Chapter 10’s data-processing section, and it is the shortest path to agreeing with a customer what counts as valid data.

Non-blocking sampling with retries and a validity gate

Section titled “Non-blocking sampling with retries and a validity gate”
#include <Adafruit_Sensor.h>
#include <DHT.h>
const uint8_t DHT_PIN = 5;
const uint8_t DHT_TYPE = DHT22; // switch to DHT11 by changing this line only
const unsigned long SAMPLE_MS = 5000; // one sample every 5 s: stable and responsive enough
const uint8_t MAX_RETRY = 3;
DHT dht(DHT_PIN, DHT_TYPE);
unsigned long nextSampleAt = 0;
struct Reading {
float hum;
float temp;
uint8_t retry;
bool valid;
};
bool plausibleHumidityTemp(float hum, float temp) {
return !isnan(hum) && !isnan(temp) && hum >= 0.0f && hum <= 100.0f && temp > -40.0f && temp < 80.0f;
}
Reading sampleOnce() {
Reading r{NAN, NAN, 0, false};
for (uint8_t i = 0; i < MAX_RETRY; i++) {
float h = dht.readHumidity();
float t = dht.readTemperature();
if (plausibleHumidityTemp(h, t)) {
r.hum = h; r.temp = t; r.retry = i; r.valid = true;
return r;
}
delay(30); // gap between retries, let the bus settle
r.retry = i + 1;
}
return r; // all attempts failed: valid=false, caller keeps last frame and reports fail
}
void setup() {
Serial.begin(115200);
dht.begin();
}
void loop() {
if (millis() >= nextSampleAt) {
nextSampleAt = millis() + SAMPLE_MS;
Reading r = sampleOnce();
if (!r.valid) {
Serial.println("dht: fail after retries (check pull-up / wiring / condensation)");
} else {
Serial.printf("hum=%.1f %%RH temp=%.1f C retry=%u\n", r.hum, r.temp, r.retry);
}
}
// MQTT keep-alive and button scanning run here; sampling never blocks
}

Note that the retry count is itself valuable telemetry: retry sitting at 0 means the bus is healthy; if it starts hovering at 1 or more, expect a loose contact, a degraded pull-up, or a weakening supply. Treat it as a device-health indicator.

Switching to an I2C SHT30: the timing problem disappears

Section titled “Switching to an I2C SHT30: the timing problem disappears”
#include <Adafruit_SHT31.h>
Adafruit_SHT31 sht;
void setup() {
Serial.begin(115200);
if (!sht.begin()) {
Serial.println("SHT3x not found (check I2C address 0x44/0x45 and wiring)");
while (true);
}
}
void loop() {
float t = sht.readTemperature();
float h = sht.readHumidity();
if (isnan(h) || isnan(t)) {
Serial.println("sht3x read failed (I2C wiring or address)");
delay(1000);
return;
}
Serial.printf("hum=%.2f %%RH temp=%.2f C\n", h, t);
delay(5000);
}

The I2C route also solves two more things: the bus is shared (an OLED and a light sensor can live on the same two wires), and CRC-verified payloads inspire more confidence than a custom checksum. The price is address planning — SHT30 commonly sits at 0x44, which can collide with other devices.

Check Expected result Verified
Normal reading Within the part’s spec versus a reference meter (DHT22 ≈ ±0.5 °C / ±3 %RH)
Breathe on the device for a few seconds Humidity rises visibly (typically +10–30 %RH), then decays slowly
Held in the hand for 30 s Temperature up 2–5 °C; humidity wobbles slightly from local evaporation
Unplug or short the data line valid=false, status fail reported — never a zero
Sampling interval set to 200 ms Failure rate jumps (proof the minimum interval is a real constraint)
One hour continuous run Average retry near 0, no parked high humidity

Simple two-point humidity sanity check (optional but worth it)

Section titled “Simple two-point humidity sanity check (optional but worth it)”
  1. Low point: seal the sensor in a box with desiccant for 30 minutes — the reading should fall into the sub-20 % region
  2. High point: place a damp cloth (not water, to avoid direct condensation) in a sealed box — the reading should climb towards 85–95 %RH

If both points are far off, check the pull-up and supply first, then consider moisture-induced ageing. DHT parts are consumables; drift after a year in high humidity is a normal outcome.

Issue 1: it never reads, or the checksum fails constantly

Section titled “Issue 1: it never reads, or the checksum fails constantly”

Symptoms: valid=false most of the time, or five or six failures out of ten.

Possible causes:

  • No pull-up resistor, or one above 10 kΩ with long wiring
  • Sampling faster than the device’s minimum interval
  • Bit-banging corrupted by Wi-Fi/Bluetooth interrupts
  • Insufficient supply (the 3.3 V rail sagging under other loads)

Solutions:

  1. Add a 4.7 kΩ pull-up on the data line — first confirm whether you are using a bare component or a module (modules usually have one fitted)
  2. Raise the sampling interval above 2 s and set retries to 3
  3. Run once with Wi-Fi disabled as an A/B test; if failures drop sharply, it is interrupt preemption — absorb it with slower sampling plus retries
  4. Measure the actual VCC; a DHT under-volted returns plausible-looking but wrong numbers

Issue 2: humidity parks above 90 % and will not come down

Section titled “Issue 2: humidity parks above 90 % and will not come down”

Symptoms: the value seems glued.

Possible causes: condensation or water-film contamination; long-term high humidity can also drift the polymer film.

Solutions:

  1. Move the part to a ventilated spot away from walls and thermal bridges, and watch for several hours
  2. Let it recover in mild dry air — do not use hot air, high temperature damages the sensing film
  3. Add a breathable cover and splash protection mechanically; in firmware, alert on “>95 %RH for X hours” so condensation is handled as an operations event rather than a sensor defect

Issue 3: readings disagree with the air conditioner or dehumidifier display

Section titled “Issue 3: readings disagree with the air conditioner or dehumidifier display”

Symptoms: a customer compares against a third-party meter and sees a gap of 5 °C or 10 %RH.

Possible causes: placement differences dominate device error — installed on a sun-facing surface, near a cabinet’s hot exhaust, in a dead corner of return air, or beside a door.

Solutions:

  1. Same-location comparison: put the reference meter and our sensor in one place, wait for thermal equilibrium (10–20 minutes), then read simultaneously
  2. State installation requirements in the acceptance document (height above floor, away from air jets and sunlight, unobstructed ventilation) — more useful than promising accuracy figures
  3. When cross-location comparison is unavoidable, use the same part batch and record the model and accuracy class in the table
  • Do: use an I2C digital part (SHT3x class) in products — it removes timing fragility and the missing CRC in one move
  • Do: at PCB layout time, make the DHT and SHT3x footprints compatible (same pull-up, same routing) so a supply interruption does not require a respin
  • Do: pick the sampling period from the physical time constant (room humidity is minutes-scale); 5–30 s is ample, and bus health shows up in retry
  • Do: include sensor_status in the payload so the customer can distinguish “sensor down” from “it really is this damp”
  • Don’t: satisfy a ±3 %RH contractual figure with a DHT11
  • Don’t: mount the bare component against an enclosure wall or a cold bridge — condensation is then inevitable
  • Don’t: keep reporting the previous frame after failure without also changing the status field

Key points of this section:

  1. DHT11 is a trend indicator; DHT22 is what you can put in a report — the gap between ±5 %RH and ±2 %RH is contract risk, not a detail
  2. Custom single-wire timing is inherently fragile: microsecond bit-banging collides with radio interrupts; absorb failures with retries and slower sampling rather than declaring the part dead
  3. Condensation is the primary cause of parked humidity readings — a mechanical design issue that software can only flag, not fix
  4. Validity belongs in the reporting chain: publish sensor_status and retry_count so dashboards distinguish missing data from zero data
  5. For products I recommend I2C SHT3x: CRC checking, bus sharing and far more predictable drivers, with a cost difference that is acceptable at whole-unit level

Next section: gas and smoke (MQ-2) — how the analogue and digital outputs divide the work, and why a raw value is not a concentration.


Building a commercial IoT product?

We provide ESP32 ODM design-to-manufacturing services. From prototype to production — the team behind this tutorial can build it with you.

💡 Mention tutorial.imagrove.com in your Alibaba chat with us — get 10% off your custom project quote.

Talk to us →

First published attutorial.imagrove.com/sensor-module-selection/05-temperature-and-humidity-with-dht/Please credit Imagrove and link back to this page when quoting or republishing.

Questions or issues with this tutorial?

Sign in with GitHub to leave a comment. If a step fails for you, tell us — we verify it and update the tutorial.