The NodeMCU is still the cheapest Wi-Fi board in many Indian shops, and a DHT22 on it makes a classic room monitor.
The trap is the pin naming: D2 on the board is GPIO4. Use D1/D2 for sensors and keep D3, D4 and D8 free, because they decide how the ESP8266 boots.
Wiring
| NodeMCU ESP8266 | DHT22 (AM2302) | Wire | Notes |
|---|---|---|---|
| 3V3 | 1 VCC | red | |
| D2 | 2 DATA | yellow | |
| 3V3 | 2 DATA | red | Via 10 kΩ — Pull-up for the bare 4-pin sensor. 3-pin breakouts already have it — skip this wire. |
| GND | 4 GND | black |
3.3–6 V part, 3.3 V board. Works at 3.3 V and 5 V. Power it from the same voltage as your board (3.3 V on ESP32 and Pico, 5 V on Uno), so the data line never exceeds the GPIO limit.
Board quirks
- NodeMCU labels (D0–D8) are not GPIO numbers: D2 is GPIO4. The core defines the D-names, so the sketch uses
D2directly. - D3, D4 and D8 are boot pins on the ESP8266 — a sensor that pulls them the wrong way at reset stops the board booting. D1 and D2 are the safe ones.
- The ESP8266 is 3.3 V-only, so the DHT22 runs from 3V3.
Code
// DHT22 / AM2302 on a NodeMCU (ESP8266).
// VCC → 3V3, DATA → D2 (GPIO4, 10 kΩ pull-up to 3V3 for the bare sensor), GND → GND.
#include <DHT.h>
const uint8_t DHT_PIN = D2; // GPIO4 — free at boot, unlike D3/D4/D8
DHT dht(DHT_PIN, DHT22);
void setup() {
Serial.begin(115200);
dht.begin();
Serial.println();
Serial.println("DHT22 on D2 (GPIO4) - first reading in 2 s");
}
void loop() {
delay(2000);
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor - check wiring and pull-up");
return;
}
Serial.printf("Temp %.1f C Humidity %.1f %%\n", t, h);
}// DHT22 / AM2302 on a NodeMCU (ESP8266).
// VCC → 3V3, DATA → D2 (GPIO4, 10 kΩ pull-up to 3V3 for the bare sensor), GND → GND.
#include <DHT.h>
const uint8_t DHT_PIN = D2; // GPIO4 — free at boot, unlike D3/D4/D8
DHT dht(DHT_PIN, DHT22);
void setup() {
Serial.begin(115200);
dht.begin();
Serial.println();
Serial.println("DHT22 on D2 (GPIO4) - first reading in 2 s");
}
void loop() {
delay(2000);
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor - check wiring and pull-up");
return;
}
Serial.printf("Temp %.1f C Humidity %.1f %%\n", t, h);
}Library: DHT sensor library (Adafruit (also install Adafruit Unified Sensor)) — compiled with DHT sensor library 1.4.7.
Expected serial output
DHT22 on D2 (GPIO4) - first reading in 2 s
Temp 28.4 C Humidity 60.7 %
Temp 28.4 C Humidity 60.6 %DHT22 on D2 (GPIO4) - first reading in 2 s Temp 28.4 C Humidity 60.7 % Temp 28.4 C Humidity 60.6 %
Common errors
Garbage characters in the Serial Monitor at start-up
That is the ESP8266 boot log at 74880 baud. It is harmless; the sketch output at 115200 follows.
“Failed to read from DHT sensor”
Check the pull-up and that DATA is on D2. Full fix.