> [!TLDR] Using [[Sensor DHT22|DHT22]] sensor on [[ESP32]] > This document explains how to connect and use a [[Sensor DHT22|DHT22]] temperature and humidity sensor with an [[ESP32]] microcontroller. Two code examples are provided: one using the `DHTesp.h` library and the other using the `DHT.h` library. Both examples read temperature and humidity, but the `DHT.h` example also calculates and displays the heat index and includes error handling. # Introduction Using the [[Sensor DHT22]] with an [[ESP32]] involves controlling GPIO pins (General Purpose Input/Output). Here's a breakdown of how to do it! ## Requisites - Hardware - [[ESP32]] - [ESP32](app://obsidian.md/ESP32) is a series of low cost and low power consumption microcontrollers. It is also a system-in-one-chip with integrated microcontroller, Wi-Fi and Bluetooth - [[Sensor DHT22]] - Sensor to collect Temperature and Humidity data. - [[Resistores]] - Used to limit the current thought the data pin of the [[Sensor DHT22]]. - Software - [[Arduino IDE]] or [[Wokwi]] for programming/simulating the code to run on the [[ESP32]]. - Make sure to [[Instalando o driver da ESP32 no Windows|install the ESP32 driver]] to be able to upload the code to the [[ESP32]]. # Hardware Connections * **[[Sensor DHT22]]:** * **Pin 1:** Connect to the VCC on the [[ESP32]] * **Pin2:** Connect to a GPIO analog pin of the [[ESP32]] * **Pin3:** Connect to GND of the [[ESP32]] ![[DHT22 with ESP32.png]] # Example Code 1 - Using the `DHT sensor library for ESPx` ```cpp /** ESP32 + DHT22 Example for Wokwi https://wokwi.com/arduino/projects/322410731508073042 */ #include "DHTesp.h" const int DHT_PIN = 15; DHTesp dhtSensor; void setup() { Serial.begin(115200); dhtSensor.setup(DHT_PIN, DHTesp::DHT22); } void loop() { TempAndHumidity data = dhtSensor.getTempAndHumidity(); Serial.println("Temp: " + String(data.temperature, 2) + "°C"); Serial.println("Humidity: " + String(data.humidity, 1) + "%"); Serial.println("---"); delay(2000); // Wait for a new reading from the sensor (DHT22 has ~0.5Hz sample rate) } ``` **Explanation:** - **`const int DHT_PIN = 15;`**: This indicates that the [[Sensor DHT22]]'s data pin is connected to digital pin 15 on the [[ESP32]]. - **`DHTesp dhtSensor;`**: This line creates an object named `dhtSensor` of the `DHTesp` class. This object will be used to interact with the [[Sensor DHT22]]. - **`dhtSensor.setup(DHT_PIN, DHTesp::DHT22);`**: This line initializes the `dhtSensor` object with the specified pin and sensor type ([[Sensor DHT22|DHT22]]). - **`TempAndHumidity data = dhtSensor.getTempAndHumidity();`**: This line reads the temperature and humidity data from the [[Sensor DHT22|DHT22]] sensor using the `getTempAndHumidity()` method of the `dhtSensor` object. The returned data is stored in a `TempAndHumidity` struct named `data`. - **`Serial.println("Temp: " + String(data.temperature, 2) + "°C");`**: This line prints the temperature value to the serial monitor. `String(data.temperature, 2)` converts the temperature value to a string with two decimal places. - **`Serial.println("Humidity: " + String(data.humidity, 1) + "%");`**: This line prints the humidity value to the serial monitor. `String(data.humidity, 1)` converts the humidity value to a string with one decimal place. In summary, this code initializes the [[Sensor DHT22|DHT22]] sensor, reads temperature and humidity data every 2 seconds, and prints the readings to the serial monitor. # Example 2 - Using the `DHT sensor library` ```cpp #include "DHT.h" #define DHTPIN 15 // Digital pin connected to the DHT sensor #define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321 DHT dht(DHTPIN, DHTTYPE); void setup() { Serial.begin(9600); Serial.println(F("DHTxx test!")); dht.begin(); } void loop() { // Wait a few seconds between measurements. delay(2000); // Reading temperature or humidity takes about 250 milliseconds! // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) float h = dht.readHumidity(); // Read temperature as Celsius (the default) float t = dht.readTemperature(); // Read temperature as Fahrenheit (isFahrenheit = true) float f = dht.readTemperature(true); // Check if any reads failed and exit early (to try again). if (isnan(h) || isnan(t) || isnan(f)) { Serial.println(F("Failed to read from DHT sensor!")); return; } // Compute heat index in Fahrenheit (the default) float hif = dht.computeHeatIndex(f, h); // Compute heat index in Celsius (isFahreheit = false) float hic = dht.computeHeatIndex(t, h, false); Serial.print(F("Humidity: ")); Serial.print(h); Serial.print(F("% Temperature: ")); Serial.print(t); Serial.print(F("°C ")); Serial.print(f); Serial.print(F("°F Heat index: ")); Serial.print(hic); Serial.print(F("°C ")); Serial.print(hif); Serial.println(F("°F")); } ``` **Explanation:** 1. **`#include "DHT.h"`**: Includes the DHT sensor library, providing functions to interact with the sensor. 2. **`#define DHTPIN 15`**: Defines the digital pin connected to the DHT sensor's data pin as 15. 3. **`#define DHTTYPE DHT22`**: Specifies the sensor type as [[Sensor DHT22|DHT22]]. 4. **`DHT dht(DHTPIN, DHTTYPE);`**: Creates a DHT object named `dht` using the specified pin and sensor type. - **`Serial.println(F("DHTxx test!"));`**: Prints a startup message to the serial monitor. The `F()` macro stores the string in flash memory, saving RAM. - **`dht.begin();`**: Initializes the DHT sensor. - **`float h = dht.readHumidity();`**: Reads the humidity and stores it in the `h` variable. - **`float t = dht.readTemperature();`**: Reads the temperature in Celsius and stores it in the `t` variable. - **`float f = dht.readTemperature(true);`**: Reads the temperature in Fahrenheit and stores it in the `f` variable. - **`if (isnan(h) || isnan(t) || isnan(f)) { … }`**: Checks if any of the readings are "Not a Number" (NaN), indicating an error. If so, it prints an error message and returns, restarting the loop. - **`float hif = dht.computeHeatIndex(f, h);`**: Calculates the heat index in Fahrenheit using the temperature in Fahrenheit and humidity. - **`float hic = dht.computeHeatIndex(t, h, false);`**: Calculates the heat index in Celsius using the temperature in Celsius and humidity. The `false` parameter specifies Celsius. Key differences from the previous code: * **Different Library:** This code uses the `DHT.h` library, while the previous one used `DHTesp.h`. They have slightly different functions and usage. * **Heat Index Calculation:** This code calculates and displays the heat index, a measure of how hot it feels when relative humidity is factored in with the air temperature. * **Error Handling:** This code includes a check for invalid readings (`isnan`), providing more robust error handling. * **Fahrenheit Conversion:** This code explicitly reads and displays the temperature in both Celsius and Fahrenheit.