#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include <SPI.h>
#include <DHT.h>

#define TFT_CS    5
#define TFT_RST   4
#define TFT_DC    16

Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST);

#define DHTPIN 4
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(115200);
  Serial.println("DHT22 Temperature and Humidity Sensor with ILI9341 Display");

  // Initialize DHT sensor
  dht.begin();

  // Initialize ILI9341 display
  tft.begin();
  tft.setRotation(3);  // Adjust rotation if needed
  tft.fillScreen(ILI9341_BLACK);  // Clear screen

  // Display initial message
  tft.setCursor(10, 10);
  tft.setTextColor(ILI9341_WHITE);
  tft.setTextSize(2);
  tft.println("DHT22 Sensor Data");
}

void loop() {
  // Wait a few seconds between measurements
  delay(2000);

  // Read temperature and humidity
  float humidity = dht.readHumidity();
  float temperatureC = dht.readTemperature();

  // Check if any reads failed
  if (isnan(humidity) || isnan(temperatureC)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Clear previous data on display
  tft.fillRect(0, 40, 320, 120, ILI9341_BLACK);

  // Print temperature and humidity values on display
  tft.setCursor(10, 40);
  tft.setTextColor(ILI9341_GREEN);
  tft.setTextSize(2);
  tft.print("Temperature: ");
  tft.print(temperatureC);
  tft.println(" C");

  tft.setCursor(10, 70);
  tft.print("Humidity: ");
  tft.print(humidity);
  tft.println(" %");
}