Trung cấpESP32 DevKitC V4TFTILI9341DHT22SPI
Màn hình TFT hiển thị nhiệt độ
Vẽ giao diện màu trên TFT ILI9341 240×320: tiêu đề, nhiệt độ và độ ẩm từ DHT22, kèm thanh mức đổi màu theo nhiệt độ.
Linh kiện
- ESP32 DevKitC V4
- Màn hình TFT 2.8" ILI9341 (240×320)
- Cảm biến nhiệt độ, độ ẩm DHT22/AM2302
Thư viện
Adafruit ILI9341, DHT sensor library — đượ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 độ lên trên 30 °C: thanh mức chuyển sang đỏ.
- Thử tft.setRotation(1) để xoay ngang.
main.cpp
// TFT ILI9341 trên SPI phần cứng (SCK 18, MOSI 23), CS 5, DC 2, RST 4; DHT22 trên GPIO32#include <Adafruit_GFX.h>#include <Adafruit_ILI9341.h>#include <DHT.h>#include <SPI.h> Adafruit_ILI9341 tft(5, 2, 4); // CS, DC, RSTDHT dht(32, DHT22); void drawFrame() { tft.fillScreen(ILI9341_BLACK); tft.fillRect(0, 0, 240, 40, ILI9341_NAVY); tft.setTextColor(ILI9341_WHITE); tft.setTextSize(2); tft.setCursor(20, 12); tft.print("TRAM THOI TIET"); tft.setTextColor(ILI9341_LIGHTGREY); tft.setCursor(20, 70); tft.print("Nhiet do"); tft.setCursor(20, 170); tft.print("Do am"); tft.drawRect(20, 270, 200, 24, ILI9341_WHITE);} void drawValues(float t, float h) { tft.setTextSize(4); tft.setTextColor(ILI9341_YELLOW, ILI9341_BLACK); // nền đen xoá số cũ tft.setCursor(20, 100); tft.print(t, 1); tft.print(" C "); tft.setTextColor(ILI9341_CYAN, ILI9341_BLACK); tft.setCursor(20, 200); tft.print(h, 1); tft.print(" % "); // Thanh mức 0…50 °C, đỏ khi trên 30 °C int width = constrain((int)(t * 196 / 50), 0, 196); tft.fillRect(22, 272, width, 20, t > 30 ? ILI9341_RED : ILI9341_GREEN); tft.fillRect(22 + width, 272, 196 - width, 20, ILI9341_BLACK);} void setup() { Serial.begin(115200); dht.begin(); tft.begin(); drawFrame();} void loop() { float t = dht.readTemperature(); float h = dht.readHumidity(); if (!isnan(t) && !isnan(h)) { drawValues(t, h); Serial.printf("T=%.1f H=%.1f\n", t, h); } delay(2000);}