ESP32 - DHT22 - OLED
Este tutorial ensina como ler a temperatura e a umidade do módulo DHT22 e mostrá-las em um OLED.
Hardware Necessário
Or you can buy the following kits:
| 1 | × | DIYables ESP32 Starter Kit (ESP32 included) | |
| 1 | × | DIYables ESP32 S3 Starter Kit (ESP32 S3 included) | |
| 1 | × | DIYables Sensor Kit (18 sensors/displays) |
Divulgação: Alguns dos links desta seção são links de afiliado da Amazon. Podemos receber uma comissão pelas compras feitas por meio desses links, sem custo adicional para você. Agradecemos o seu apoio.
Buy Note: If you want a bigger OLED display, use the 2.42 inch OLED Display 128x64 .
Sobre o Display OLED e o Sensor de Temperatura e Umidade DHT22
Se você não conhece o display OLED e o sensor de temperatura e umidade DHT22 (pinagem, como funciona, como programar...), aprenda sobre eles nos tutoriais a seguir:
- Tutorial ESP32 - OLED
- Tutorial ESP32 - DHT22
Diagrama de Ligação

This image is created using Fritzing. Click to enlarge image
Se você não sabe como alimentar o ESP32 e outros componentes, veja as instruções no tutorial a seguir: Como alimentar o ESP32.
Código ESP32 - Sensor DHT22 - OLED
/*
* Este código de ESP32 foi desenvolvido por pt.newbiely.com
* Este código de ESP32 é disponibilizado ao público sem nenhuma restrição.
* Para tutoriais completos e diagramas de ligação, visite:
* https://pt.newbiely.com/tutorials/esp32/esp32-dht22-oled
*/
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <DHT.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define DHT22_PIN 2 // The ESP32 pin GPIO23 connected to DHT22 sensor
Adafruit_SSD1306 oled(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1); // create SSD1306 display object connected to I2C
DHT dht22(DHT22_PIN, DHT22);
String temperature;
String humidity;
void setup() {
Serial.begin(9600);
// initialize OLED display with address 0x3C for 128x64
if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
while (true);
}
delay(2000); // wait for initializing
oled.clearDisplay(); // clear display
oled.setTextSize(3); // text size
oled.setTextColor(WHITE); // text color
oled.setCursor(0, 10); // position to display
dht22.begin(); // initialize DHT22 the temperature and humidity sensor
temperature.reserve(10); // to avoid fragmenting memory when using String
humidity.reserve(10); // to avoid fragmenting memory when using String
}
void loop() {
float humi = dht22.readHumidity(); // read humidity
float tempC = dht22.readTemperature(); // read temperature
// check if any reads failed
if (isnan(humi) || isnan(tempC)) {
temperature = "Failed";
humidity = "Failed";
} else {
temperature = String(tempC, 1); // one decimal places
temperature += char (247); // degree character
temperature += "C";
humidity = String(humi, 1); // one decimal places
humidity += "%";
Serial.print(tempC); // print to Serial Monitor
Serial.print("°C | " ); // print to Serial Monitor
Serial.print(humi); // print to Serial Monitor
Serial.println("%"); // print to Serial Monitor
}
oledDisplayCenter(temperature, humidity); // display temperature and humidity on OLED
}
void oledDisplayCenter(String temperature, String humidity) {
int16_t x1;
int16_t y1;
uint16_t width_T;
uint16_t height_T;
uint16_t width_H;
uint16_t height_H;
oled.getTextBounds(temperature, 0, 0, &x1, &y1, &width_T, &height_T);
oled.getTextBounds(temperature, 0, 0, &x1, &y1, &width_H, &height_H);
// display on horizontal and vertical center
oled.clearDisplay(); // clear display
oled.setCursor((SCREEN_WIDTH - width_T) / 2, SCREEN_HEIGHT/2 - height_T - 5);
oled.println(temperature); // text to display
oled.setCursor((SCREEN_WIDTH - width_H) / 2, SCREEN_HEIGHT/2 + 5);
oled.println(humidity); // text to display
oled.display();
}
Passos Rápidos
- Se esta é a primeira vez que você usa o ESP32, veja como configurar o ambiente para o ESP32 no Arduino IDE.
- Faça a ligação conforme a imagem acima.
- Conecte a placa ESP32 ao seu PC por meio de um cabo USB Type-C
- Abra o Arduino IDE no seu PC.
- Selecione a placa ESP32 correta (por exemplo, ESP32 Dev Module) e a porta COM.
- Clique no ícone Libraries na barra esquerda do Arduino IDE.
- Pesquise “SSD1306” e encontre a biblioteca SSD1306 da Adafruit
- Clique no botão Install para instalar a biblioteca.

- Será solicitado que você instale algumas outras dependências da biblioteca
- Clique no botão Install All para instalar todas as dependências da biblioteca.

- Pesquise “DHT” e encontre a biblioteca DHT sensor library da Adafruit
- Clique no botão Install para instalar a biblioteca.

- Será solicitado que você instale algumas outras dependências da biblioteca
- Clique no botão Install All para instalar todas as dependências da biblioteca.

- Copie o código acima e abra-o no Arduino IDE
- Clique no botão Upload no Arduino IDE para fazer upload do código para o ESP32
- Coloque o sensor em água quente e fria, ou segure o sensor com a mão
- Veja o resultado no OLED e no Serial Monitor
※ Nota:
O código acima centraliza automaticamente o texto na horizontal e na vertical no display OLED