What You Will Build
A DHT22 room-temperature controller that commands a low-voltage fan ON at 27.0 C and OFF at 25.5 C. It holds its prior command between thresholds, starts OFF and resets OFF after failed readings. Serial Monitor provides feedback. The OLED remains an optional extension; the complete example does not use one.
Before You Start
Classic ESP32-WROOM-32/32E DevKit with the named GPIOs exposed and unused. Select its exact board profile, or ESP32 Dev Module for an otherwise undocumented generic WROOM board. Arduino IDE 2.x and Arduino-ESP32 3.x; API review baseline 3.3.2, not a claim that it is the latest release. Other ESP32 families need their own pin/USB settings. Serial Monitor: 115200 baud. Examples are reviewed against documentation, not compiled or hardware tested in this content review.
DHT22/AM2302 uses 3.3 V and GPIO4 with a DATA pull-up to 3.3 V. The relay example assumes a documented driver module with built-in coil protection, a 3.3 V-compatible input and active-HIGH operation (one flag selects active-LOW). No exact relay model is provided: confirm supply, input thresholds/pull-ups and reset behavior first. Never connect a bare relay coil to GPIO26.
Parts
- ESP32 DevKit boardDHT22 and relay thermostat controller
- DHT22 sensor moduleDHT22 at 3.3 V; bare sensor needs a 10 kΩ DATA pull-up
- Relay moduleVerified 3.3 V-compatible driver-module input; supply and polarity per documentation
- SSD1306 OLED displayOptional extension only; not required or driven by this sketch
- Breadboard and wiresPrototype wiring
- 10 kΩ resistorDATA pull-up for bare DHT22; verify any onboard pull-up
- Low-voltage fan or indicator and rated supplyTest unloaded first; allow for fan starting current
Wiring
GPIO4 reads DHT22; GPIO26 drives only a verified relay-module input. COM/NO contacts switch a separate low-voltage load, disconnected when released. The diagram is a logical map, not module pin order.
-
1
Unplug USB and every supply; leave load disconnected for initial checks.
-
2
Wire a verified 3.3 V DHT22 breakout by labels: VCC to 3.3 V, GND to GND, DATA/OUT to GPIO4.
-
3
For a standard bare DHT22, vented front facing you with leads down: pins1–4 are VCC, DATA, NC, GND. Add 10 kΩ from DATA to 3.3 V; leave NC open.
-
4
Confirm relay IN accepts 3.3 V and cannot feed 5 V into GPIO26. Connect IN to GPIO26 and signal GND to ESP32 GND for the shared-ground driver module assumed here; use a suitable interface if incompatible.
-
5
Supply relay VCC/coil as documented; do not assume ESP32 5 V/VIN capacity. Follow exact JD-VCC/jumper/isolation instructions if present.
-
6
With contacts unloaded verify released at startup and on failed readings. Change RELAY_ACTIVE_LOW only when module documentation and unloaded checks require it.
-
7
After checks connect rated low-voltage supply positive to COM, NO to load positive, load negative to supply negative. Follow load switching/transient-protection requirements. Never route load current through GPIO.
Wiring Reference
| Signal | ESP32 Pin | Direction | Notes |
|---|---|---|---|
| DHT22 DATA | GPIO4 | Input | Bare sensor: 10 kΩ to 3.3 V |
| DHT22 VCC / GND | 3.3 V / GND | Power | Verify breakout compatibility |
| Relay IN | GPIO26 | Output | Default active-HIGH; flag selects active-LOW; verify input thresholds |
| Relay supply / signal GND | Module-rated supply / GND | Power | Shared-ground driver assumed; not bare coil |
| Relay COM / NO | No ESP32 GPIO | Contacts | Separate low-voltage load; normally open |
| Optional OLED SDA/SCL | GPIO21 / GPIO22 | Extension | Not initialized by this example |
Libraries and Setup
- DHT sensor library by AdafruitInstall in Library Manager with Adafruit Unified Sensor. Sketch uses DHT22, not DHT11.
- esp32 by Espressif Systems 3.xSelect WROOM board/port; verify IDE guide Serial-only sketch first.
Configure the Example
FAN_ON_C=27.0 and FAN_OFF_C=25.5 describe cooling, not heating. Keep OFF below ON. RELAY_ACTIVE_LOW defaults false for active-HIGH. Set true only for a verified active-LOW module; ON/OFF levels change together.
Wait 2.5 seconds before the first sample and between reads. DHT22 refreshes slowly and data can be roughly one sample old. Keep it away from regulator/relay heat, fan exhaust and sunlight. Serial reports commands, not feedback proving the fan works.
Control and Recovery Behavior
| Condition | Result |
|---|---|
| Startup / first sample wait | fanOn=false; relay OFF command begins in setup, not throughout reset/boot. |
| Valid temperature ≥27.0 C | Command ON. |
| Valid temperature ≤25.5 C | Command OFF. |
| Valid sample strictly between thresholds | Keep prior state; after startup/fault that state is OFF. |
| Invalid read / NaN | Clear fanOn and command OFF at that sample; print fault and retry in 2.5 seconds. |
| Valid readings return | Resume from OFF; restart only at/above 27.0 C. |
Code
Install the libraries above and match the configuration and wiring before uploading.
#include <DHT.h>
#include <math.h>
constexpr uint8_t DHT_PIN = 4, RELAY_PIN = 26;
constexpr bool RELAY_ACTIVE_LOW = false; // Verify with contacts unloaded.
constexpr uint8_t RELAY_ON = RELAY_ACTIVE_LOW ? LOW : HIGH;
constexpr uint8_t RELAY_OFF = RELAY_ACTIVE_LOW ? HIGH : LOW;
constexpr float FAN_ON_C = 27.0F, FAN_OFF_C = 25.5F;
constexpr uint32_t SAMPLE_MS = 2500;
static_assert(FAN_OFF_C < FAN_ON_C, "OFF threshold must be below ON");
DHT dht(DHT_PIN, DHT22);
bool fanOn = false;
void setup() {
Serial.begin(115200);
// Configure GPIO before digitalWrite on Arduino-ESP32 3.x.
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, RELAY_OFF);
dht.begin();
Serial.println("Thermostat demo: OFF; waiting for first DHT22 sample");
delay(SAMPLE_MS);
}
void loop() {
const float tempC = dht.readTemperature();
if (!isfinite(tempC)) {
fanOn = false; // Reset hysteresis memory as well as output.
digitalWrite(RELAY_PIN, RELAY_OFF);
Serial.println("DHT22 fault: fan command OFF; retry in 2.5 s");
} else {
if (!fanOn && tempC >= FAN_ON_C) fanOn = true;
else if (fanOn && tempC <= FAN_OFF_C) fanOn = false;
digitalWrite(RELAY_PIN, fanOn ? RELAY_ON : RELAY_OFF);
Serial.print("Temp C: "); Serial.print(tempC, 1);
Serial.print(" | Fan command: "); Serial.println(fanOn ? "ON" : "OFF");
}
delay(SAMPLE_MS);
}
How the Code Works
One flag sets both electrical levels. setup configures GPIO26, immediately writes OFF and waits for DHT22. Arduino-ESP32 3.x requires GPIO configuration before digitalWrite. This cannot guarantee a quiet relay while GPIO floats during reset: module-specific hardware bias may be needed.
A failed sample clears both fanOn and output, so recovery in the middle band does not restore a previous ON state. Serial reports commands, not measured contacts or motor operation.
Expected Output
Startup reports OFF. Valid readings command ON at/above 27.0 C, OFF at/below 25.5 C and hold state between. Invalid readings print a fault, clear state and command OFF. Recovery in the middle band stays OFF; an ON-threshold sample can restart. These are expected states to verify with contacts unloaded before adding the load.
Troubleshooting
- DHT22 fault / NaN Check DATA4, 3.3 V, GND, DHT22 type, pin orientation and pull-up. Keep 2.5-second timing; remove power before correcting wires.
- Relay reversed Verify polarity with contacts unloaded, then change RELAY_ACTIVE_LOW. COM/NO, not COM/NC, is assumed.
- Relay clicks at boot GPIO26 is not actively driven throughout reset. Verify an external OFF bias or interface; setup alone cannot promise glitch-free boot.
- Relay LED changes but fan does not Check separate supply, COM/NO, starting current and ratings. LED/Serial command is not contact feedback.
- Unexpected sensor-fault recovery This sketch clears fanOn. Middle-band recovery stays OFF; only ON threshold restarts. Check uploaded code/thresholds.
- Chatter or resets Retain hysteresis, move sensor away from airflow/heat and verify coil/load supply and suppression. Never put load current through GPIO.
Checks to Perform on Your Build
- Verify Serial-only upload before sensor wiring.
- Check startup OFF and polarity with contacts unloaded.
- Verify DHT22 readings about every 2.5 seconds away from heat.
- Check both thresholds and middle-band hold in controlled low-voltage conditions.
- Power off, remove DATA and restart: verify fault/OFF. Restore wiring powered off and check recovery.
- Check actual contacts/load separately from Serial commands.
Practical Design Notes
Hysteresis prevents switching around one setpoint. Output changes at the next valid sample, not immediately after a temperature change. This is a learning controller, not precision/fail-safe HVAC equipment.
Coil supply, logic input and contact load have separate ratings. A 5 V coil does not prove 3.3 V input compatibility or safe pull-ups. Use the actual schematic. Shared signal ground does not establish optoisolation; motor transients matter even at low voltage.
Upgrade Ideas
- Add buttons to adjust setpoint.
- Show temperature and fan state on OLED.
- Add Wi-Fi dashboard control.
- Log heating and cooling cycles.
FAQs
What happens if the sensor fails?
The next invalid sample clears fanOn and commands OFF; retry interval is 2.5 seconds. This is not fail-safe cooling protection.
Can I use an active-LOW relay?
Verify input compatibility/supply first, set RELAY_ACTIVE_LOW=true and check with contacts unloaded. Reset behavior needs separate hardware review.
Can I connect mains or household HVAC?
No. Only a low-voltage prototype is covered; mains wiring and HVAC safety behavior are not covered or verified.
Review, Testing, and References
Author: Abdul Mubeen and the ESP32 Engine editorial team. Last updated: 2026-10-08. Reviewed: wiring logic, Arduino code structure, beginner safety, and learning sequence.
Educational level: Intermediate. Estimated completion time: 90-120 min. This project is for learning and prototyping; production or unattended hardware needs additional engineering review.

