About Lesson
To interface the DHT22 sensor with the ESP32 using the Arduino IDE, you can use the DHT sensor library by Adafruit. Below is a detailed guide and the complete code.
Step-by-Step Guide:
Install the Required Libraries:
- Open the Arduino IDE.
- Go to
Sketch
>Include Library
>Manage Libraries...
- Search for and install DHT sensor library by Adafruit and Adafruit Unified Sensor
ESP32 with DHT22 Code:
C++
#include "DHT.h"
// Set the GPIO pin for the DHT22 sensor
#define DHTPIN 4 // GPIO pin where the DATA pin of the DHT22 is connected
// Set the DHT sensor type
#define DHTTYPE DHT22
// Initialize the DHT sensor
DHT dht(DHTPIN, DHTTYPE);
void setup() {
// Start the serial communication
Serial.begin(115200);
// Start the DHT sensor
dht.begin();
}
void loop() {
// Wait a few seconds between measurements
delay(2000);
// Read humidity and temperature from the sensor
float humidity = dht.readHumidity();
float temperature = dht.readTemperature(); // Celsius
// Check if any reading failed
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Print the values to the Serial Monitor
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" *C");
}
Key Code Details:
- DHTPIN: This defines the ESP32 GPIO pin connected to the DATA pin of the DHT22. Change this to whatever pin you’re using.
- DHTTYPE: Defines the type of DHT sensor you’re using (DHT22 in this case).
- dht.begin(): Initializes the DHT sensor.
- dht.readHumidity(): Reads the humidity value from the sensor.
- dht.readTemperature(): Reads the temperature value in Celsius.
Serial Monitor Output Example:
YAML
Humidity: 55.20 % Temperature: 23.40 *C
Humidity: 55.30 % Temperature: 23.45 *C
Notes:
- The delay(2000) ensures a 2-second pause between readings, as the DHT22 takes around 2 seconds to complete a reading.
- If the readings return NAN (not a number), there could be a wiring issue, or the sensor might be faulty.
With this setup, you should be able to read temperature and humidity from the DHT22 sensor using the ESP32 and Arduino IDE.