✅ ESP32 + DHT11 Serial Monitor Code (Copy–Paste)
"DHT.h"
// -------------------- DHT Pin & Type --------------------
DHTPIN 4 // ESP32 GPIO4 (D4 pin)
DHTTYPE DHT11 // DHT11 sensor type
// Create DHT object
DHT dht(DHTPIN, DHTTYPE);
void setup() {
// Start Serial Communication
Serial.begin(115200);
// Print a message once when ESP32 starts
Serial.println("DHT11 Sensor Reading..."); // Start DHT sensor
dht.begin();
}
void loop() {
// DHT11 sensor needs minimum 2 seconds delay between readings
delay(2000);
// Read Humidity (%)
float humidity = dht.readHumidity();
// Read Temperature (°C)
float temperature = dht.readTemperature();
// If sensor reading fails, humidity/temperature becomes NAN
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Print Temperature
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C | ");
// Print Humidity
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
}📌 Wiring (DHT11 3-pin module → ESP32)
| DHT11 Pin | ESP32 |
|---|---|
| VCC | 3.3V |
| GND | GND |
| DATA | GPIO4 (D4) |
🧠 Detailed Code Explanation (Line by Line)
✅ 1) Library Include
This line adds the DHT sensor library.
Without this library, ESP32 cannot understand:
-
readHumidity() -
readTemperature() -
begin()
✅ 2) Define Pin and Sensor Type
🔹 DHTPIN 4
This means the DHT11 data pin is connected to GPIO 4 of ESP32.
🔹 DHTTYPE DHT11
This tells the library which sensor you are using:
-
DHT11 (low cost, low accuracy)
-
DHT22 (better accuracy)
✅ 3) Create DHT Sensor Object
This creates an object named dht.
Now you can use:
-
dht.begin() -
dht.readHumidity() -
dht.readTemperature()
✅ 4) Setup Function
This runs only one time when ESP32 starts.
🔹 Start Serial Communication
This starts serial communication between:
-
ESP32 ↔ Laptop/PC
Speed = 115200 baud.
🔹 Print message
This prints a message once, to confirm code started.
🔹 Start DHT sensor
This initializes the sensor.
If you don’t call this, DHT11 will not work.
✅ 5) Loop Function
This runs again and again forever.
🔹 Delay 2 seconds
⚠️ DHT11 needs minimum 2 seconds between readings.
If you read too fast:
-
sensor gives wrong values
-
or returns NAN
🔹 Read humidity
This reads humidity and stores it in a float variable.
Example:
-
60.00 %
🔹 Read temperature
This reads temperature in Celsius.
Example:
-
28.00 °C
✅ 6) Check for Error
If sensor is not connected properly, or sensor fails, the library returns:
❌ NAN = Not A Number
So we check it.
🔹 Print error
This prints the error and stops this loop cycle.
✅ 7) Print Output on Serial Monitor
This prints values like:
🖥 Serial Monitor Settings
In Arduino IDE:
✅ Tools → Serial Monitor
-
Baud rate: 115200