#include "DHT.h"
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED width
#define SCREEN_HEIGHT 64 // OLED height
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#define pinLed 21 // Pin cho LED
#define DHTPIN 4 // Pin ESP32 kết nối với chân Data của DHT22
#define DHTTYPE DHT22 // Loại cảm biến DHT
DHT dht(DHTPIN, DHTTYPE); // Khởi tạo cảm biến DHT
void setup() {
pinMode(pinLed, OUTPUT); // Thiết lập chân LED là OUTPUT
Serial.begin(115200);
Serial.println(F("DHTxx test!"));
// Khởi tạo màn hình OLED
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("khong the khoi tao man OLED"));
for (;;); // Dừng chương trình nếu không thể khởi tạo OLED
}
dht.begin(); // Khởi động cảm biến DHT
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.print(F("khoi tao thanh cong"));
display.display();
delay(2000); // Hiển thị thông báo khởi tạo trong 2 giây
}
void loop() {
delay(2000); // Đợi cảm biến ổn định
float humid = dht.readHumidity();
float temp = dht.readTemperature();
// Kiểm tra lỗi đọc cảm biến
if (isnan(humid) || isnan(temp)) {
Serial.println(F("Khong doc duoc du lieu tu cam bien dht"));
return;
}
// In giá trị lên Serial Monitor
Serial.print(F("do am: "));
Serial.print(humid);
Serial.print(F("% Nhiet do: "));
Serial.print(temp);
Serial.println(F("°C"));
// Hiển thị dữ liệu lên màn hình OLED
display.clearDisplay();
display.setCursor(0, 0);
display.print(F("Do am: "));
display.print(humid, 2);
display.print(F("%"));
display.setCursor(0, 10);
display.print(F("Nhiet do: "));
display.print(temp, 2);
display.print(F(" °C"));
display.display(); // Cập nhật màn hình
delay(1000); // Đọc dữ liệu mỗi giây
}