Tất cả dự án mẫu
Trung cấpESP32 DevKitC V4DHT22OLEDI2C

Trạm thời tiết DHT22 + OLED

Đọc nhiệt độ và độ ẩm từ DHT22, hiện lên màn hình OLED SSD1306 qua I2C và in ra Serial.

Linh kiện

  • ESP32 DevKitC V4
  • OLED SSD1306
  • Cảm biến nhiệt độ, độ ẩm DHT22/AM2302

Thư viện

DHT sensor library, Adafruit SSD1306 — được cài sẵn khi bạn mở dự án.

Thử ngay khi mô phỏng chạy

  • Kéo thanh trượt nhiệt độ, độ ẩm dưới cảm biến khi đang chạy.
  • Đổi cỡ chữ bằng setTextSize(2).

main.cpp

// Trạm thời tiết: DHT22 trên GPIO32, OLED SSD1306 qua I2C (SDA 21, SCL 22)#include <Adafruit_GFX.h>#include <Adafruit_SSD1306.h>#include <DHT.h>#include <Wire.h> Adafruit_SSD1306 display(128, 64, &Wire, -1);DHT dht(32, DHT22); void setup() {  Serial.begin(115200);  dht.begin();  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  display.setTextColor(SSD1306_WHITE);} void loop() {  float t = dht.readTemperature();  float h = dht.readHumidity();  display.clearDisplay();  display.setTextSize(1);  display.setCursor(0, 0);  display.print("TRAM THOI TIET");  display.setTextSize(2);  display.setCursor(0, 20);  if (isnan(t) || isnan(h)) {    display.print("Loi DHT");    Serial.println("Loi DHT");  } else {    display.print(t, 1);    display.print(" C");    display.setCursor(0, 44);    display.print(h, 1);    display.print(" %");    Serial.printf("T=%.1f H=%.1f\n", t, h);  }  display.display();  delay(2000);}