What is a DHT11 Sensor?
The DHT11 is a basic, low-cost digital sensor that can measure both temperature and humidity. It has a capacitive humidity sensor and a thermistor to measure the surrounding air, providing data via a digital signal on a single data pin. It is widely used in weather stations, smart home systems, and environmental monitoring systems.
Components:
- Arduino (any model, like Uno)
- DHT11 Sensor module
- Jumper wires
- Breadboard (optional)
DHT11 Pin Description:
1. VCC → 5V power supply
2. GND → Ground
3. DATA → Digital Pin on Arduino (requires a pull-up resistor)
Wiring the DHT11 Sensor to Arduino:
1. VCC → 5V pin on Arduino
2. GND → GND pin on Arduino
3. DATA→ Digital Pin (e.g., D2) on Arduino
### Libraries:
To work with the DHT11, you’ll need to install the **DHT library** in your Arduino IDE. Follow these steps:
1. Open Arduino IDE.
2. Go to Sketch → nclude Library → Manage Libraries
3. In the Library Manager, search for DHT sensor library and install it.
You also need the Adafruit Unified Sensor Library
1. Open the Library Manager and search for "Adafruit Unified Sensor" and install it.
Code Example:
#include "DHT.h"
#define DHTPIN 2 // Pin where the DHT11 is connected
#define DHTTYPE DHT11 // DHT11 sensor type
DHT dht(DHTPIN, DHTTYPE); // Initialize the DHT sensor
void setup() {
Serial.begin(9600);
dht.begin(); // Start reading data from the DHT sensor
}
void loop() {
// Wait a few seconds between measurements
delay(2000);
// Reading temperature and humidity
float humidity = dht.readHumidity();
float temperature = dht.readTemperature(); // Read in Celsius
// Check if any reading failed and exit early (to try again).
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Print the results
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" °C");
}
How the Code Works:
- dht.begin(): Initializes the DHT11 sensor.
- dht.readHumidity(): Reads the humidity level from the sensor.
- dht.readTemperature(): Reads the temperature in Celsius.
- isnan(): Checks if the sensor reading failed (due to wiring issues or other faults).
Testing:
1. Upload the code to your Arduino using the Arduino IDE.
2. Open the Serial Monitor, and every 2 seconds, you'll see the humidity (%) and temperature (°C) readings from the DHT11 sensor.
This setup allows you to measure both temperature and humidity, ideal for environmental monitoring projects.
תגובות