> [!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. > [!RESUMO] Usando o sensor [[Sensor DHT22|DHT22]] no [[ESP32]] > Este documento explica como conectar e usar um sensor de temperatura e umidade [[Sensor DHT22|DHT22]] com um microcontrolador [[ESP32]]. Dois exemplos de código são fornecidos: um usando a biblioteca `DHTesp.h` e o outro usando a biblioteca `DHT.h`. Ambos os exemplos leem temperatura e umidade, mas o exemplo `DHT.h` também calcula e exibe o índice de calor e inclui tratamento de erros. # Introdução Usar o [[Sensor DHT22]] com um [[ESP32]] envolve o controle de pinos GPIO (General Purpose Input/Output). Aqui está um detalhamento de como fazer isso! ## Requisitos - Hardware - [[ESP32]] - [ESP32](app://obsidian.md/ESP32) é uma série de microcontroladores de baixo custo e baixo consumo de energia. É também um sistema em um chip com microcontrolador, Wi-Fi e Bluetooth integrados. - [[Sensor DHT22]] - Sensor para coletar dados de Temperatura e Umidade. - [[Resistores]] - Usados para limitar a corrente através do pino de dados do [[Sensor DHT22]]. - Software - [[Arduino IDE]] ou [[Wokwi]] para programar/simular o código a ser executado no [[ESP32]]. - Certifique-se de [[Instalando o driver da ESP32 no Windows|instalar o driver do ESP32]] para poder carregar o código para o [[ESP32]]. # Conexões de Hardware * **[[Sensor DHT22]]:** * **Pino 1:** Conectar ao VCC no [[ESP32]] * **Pino 2:** Conectar a um pino analógico GPIO do [[ESP32]] * **Pino 3:** Conectar ao GND do [[ESP32]] ![[DHT22 with ESP32.png]] # Exemplo de Código 1 - Usando a `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) } ``` **Explicação:** - **`const int DHT_PIN = 15;`**: Isso indica que o pino de dados do [[Sensor DHT22]] está conectado ao pino digital 15 no [[ESP32]]. - **`DHTesp dhtSensor;`**: Esta linha cria um objeto chamado `dhtSensor` da classe `DHTesp`. Este objeto será usado para interagir com o [[Sensor DHT22]]. - **`dhtSensor.setup(DHT_PIN, DHTesp::DHT22);`**: Esta linha inicializa o objeto `dhtSensor` com o pino e o tipo de sensor especificados ([[Sensor DHT22|DHT22]]). - **`TempAndHumidity data = dhtSensor.getTempAndHumidity();`**: Esta linha lê os dados de temperatura e umidade do sensor [[Sensor DHT22|DHT22]] usando o método `getTempAndHumidity()` do objeto `dhtSensor`. Os dados retornados são armazenados em uma estrutura `TempAndHumidity` chamada `data`. - **`Serial.println("Temp: " + String(data.temperature, 2) + "°C");`**: Esta linha imprime o valor da temperatura no monitor serial. `String(data.temperature, 2)` converte o valor da temperatura para uma string com duas casas decimais. - **`Serial.println("Humidity: " + String(data.humidity, 1) + "%");`**: Esta linha imprime o valor da umidade no monitor serial. `String(data.humidity, 1)` converte o valor da umidade para uma string com uma casa decimal. Em resumo, este código inicializa o sensor [[Sensor DHT22|DHT22]], lê os dados de temperatura e umidade a cada 2 segundos e imprime as leituras no monitor serial. # Exemplo 2 - Usando a `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")); } ``` **Explicação:** 1. **`#include "DHT.h"`**: Inclui a biblioteca do sensor DHT, fornecendo funções para interagir com o sensor. 2. **`#define DHTPIN 15`**: Define o pino digital conectado ao pino de dados do sensor DHT como 15. 3. **`#define DHTTYPE DHT22`**: Especifica o tipo de sensor como [[Sensor DHT22|DHT22]]. 4. **`DHT dht(DHTPIN, DHTTYPE);`**: Cria um objeto DHT chamado `dht` usando o pino e o tipo de sensor especificados. - **`Serial.println(F("DHTxx test!"));`**: Imprime uma mensagem de inicialização no monitor serial. A macro `F()` armazena a string na memória flash, economizando RAM. - **`dht.begin();`**: Inicializa o sensor DHT. - **`float h = dht.readHumidity();`**: Lê a umidade e a armazena na variável `h`. - **`float t = dht.readTemperature();`**: Lê a temperatura em Celsius e a armazena na variável `t`. - **`float f = dht.readTemperature(true);`**: Lê a temperatura em Fahrenheit e a armazena na variável `f`. - **`if (isnan(h) || isnan(t) || isnan(f)) { … }`**: Verifica se alguma das leituras é "Não é um Número" (NaN), indicando um erro. Se sim, imprime uma mensagem de erro e retorna, reiniciando o loop. - **`float hif = dht.computeHeatIndex(f, h);`**: Calcula o índice de calor em Fahrenheit usando a temperatura em Fahrenheit e a umidade. - **`float hic = dht.computeHeatIndex(t, h, false);`**: Calcula o índice de calor em Celsius usando a temperatura em Celsius e a umidade. O parâmetro `false` especifica Celsius. Principais diferenças em relação ao código anterior: * **Biblioteca Diferente:** Este código usa a biblioteca `DHT.h`, enquanto o anterior usava `DHTesp.h`. Elas têm funções e uso ligeiramente diferentes. * **Cálculo do Índice de Calor:** Este código calcula e exibe o índice de calor, uma medida de quão quente se sente quando a umidade relativa é levada em consideração com a temperatura do ar. * **Tratamento de Erros:** Este código inclui uma verificação para leituras inválidas (`isnan`), fornecendo um tratamento de erros mais robusto. * **Conversão para Fahrenheit:** Este código lê e exibe explicitamente a temperatura em Celsius e Fahrenheit.