How to Use NodeMCU ESP8266 with DHT11 Temperature Humidity Sensor
How to Use NodeMCU ESP8266 with DHT11 Temperature Humidity Sensor
This tutorial shows how to connect a DHT11 temperature and humidity sensor to a NodeMCU ESP8266 board and read values through the Arduino IDE Serial Monitor. Simple setup with minimal components.
Required Components
- NodeMCU ESP8266 V2 with CP2102 chip
- DHT11 sensor with PCB breakout for easier wiring
- Micro USB cable for code upload
- 3x Male-to-Female Jumper wires
Wiring NodeMCU ESP8266 to DHT11
Connection is straightforward:
| NodeMCU ESP8266 | DHT11 (PCB) |
|---|---|
| 5V | + pin |
| GND | - pin |
| D4 (GPIO 2) | OUT pin |
D4 on the board maps to GPIO 2 on the ESP8266 chip. You can change to other pins by editing the code later.
Installing the DHT11 Library
Install a DHT library before using the sensor:
- Download a DHT11-compatible library
- Open Arduino IDE → Sketch → Include Library → Add .ZIP Library
- Select the downloaded library file
Different libraries may have different APIs, so check the example code that comes with your chosen library.
Code to Read Temperature and Humidity
#include <DHT.h>
#define DHTPIN 2 // GPIO 2 is D4 on the board
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
dht.begin();
Serial.println("DHT11 Sensor Ready");
}
void loop() {
delay(2000); // Wait 2 seconds between readings
float h = dht.readHumidity();
float t = dht.readTemperature(); // Celsius
float f = dht.readTemperature(true); // Fahrenheit
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C \t");
Serial.print(f);
Serial.println(" *F");
}
This code reads relative humidity, temperature in Celsius and Fahrenheit, then prints them to Serial Monitor every 2 seconds.
Changing the GPIO Pin
To use D1 (GPIO 5) instead, modify line 3:
#define DHTPIN 5 // Using GPIO 5 which is D1 on the board
Remember to reconnect the data wire to the D1 pin.
How to Upload and View Results
- Select Board: NodeMCU 1.0 (ESP-12E Module)
- Select the correct Port
- Click Upload
- Open Serial Monitor and set Baud Rate to 9600
If everything is correct, you’ll see temperature and humidity readings like 28°C with 65% humidity.
Testing with Heat Source
Try pointing a hair dryer near the sensor. Temperature values should rise, confirming the sensor works properly.
Summary
Using DHT11 with NodeMCU ESP8266 is straightforward. Key points: wire correctly, install a compatible library, and check connections if readings fail. For unstable readings, shorten wire length and ensure proper delay between measurements.
อยากทำโปรเจคแบบนี้?
รับทำโปรเจค Arduino / IoT จบงานไว ส่งงานครบ พร้อมสอน
If you need Arduino project service or urgent IoT development, see full service details on the home page
จ้างทำโปรเจคเลย