The DHT11 is a basic, low-cost digital temperature and humidity sensor. It's perfect for beginners learning about environmental sensing with Arduino.
Key Features:
Inside the sensor:
The sensor communicates using a proprietary single-wire protocol, sending 40 bits of data (humidity + temperature + checksum).
The DHT11 sensor has 3 or 4 pins (depending on the module):
Connection Steps:
Safety Check:
To communicate with the DHT11, we need to install a library that handles the complex timing protocol.
Installation Steps:
Once installed, you can include it in your sketch with: #include <DHT.h>
First, we include the library and define our sensor configuration.
Key elements:
// Include the DHT library
#include <DHT.h>
// Define the pin connected to DATA
#define DHTPIN 2
// Define the sensor type
#define DHTTYPE DHT11
// Create DHT object
DHT dht(DHTPIN, DHTTYPE);
In setup(), we initialize serial communication and start the sensor.
In loop(), we read and display the sensor data.
Note: DHT11 has a 2-second sampling rate, so we add a delay between readings.
void setup() {
// Initialize serial communication
Serial.begin(9600);
Serial.println("DHT11 Test!");
// Start the sensor
dht.begin();
}
void loop() {
// Wait 2 seconds between readings
delay(2000);
// Read sensor data
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// Display the results
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print(" % Temperature: ");
Serial.print(temperature);
Serial.println(" °C");
}
Sometimes sensors fail to read. It's good practice to check for errors using isnan() function.
Why add error checking?
void loop() {
delay(2000);
float h = dht.readHumidity();
float t = dht.readTemperature();
// Check if readings failed
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Display valid readings
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" % Temperature: ");
Serial.print(t);
Serial.println(" °C");
}
Upload and Test:
Common Issues:
Challenge: Try breathing on the sensor to see humidity increase!