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

// Pin definitions
#define DHTPIN 2
#define DHTTYPE DHT22
#define RELAY_PIN 7
#define TFT_CS 10
#define TFT_RST 9
#define TFT_DC 8
#define RELAY_A 6

// Initialize DHT sensor
DHT dht(DHTPIN, DHTTYPE);

// Initialize TFT screen
Adafruit_ILI9341 tft(TFT_CS, TFT_DC, TFT_RST);

// Temperature and Humidity thresholds
const float TEMP_THRESHOLD = 28.0; // Temperature threshold in Celsius
const float HUMIDITY_THRESHOLD = 85.0; // Humidity threshold in percentage

void setup() {
  Serial.begin(9600);

  // Initialize DHT sensor
  dht.begin();
  
  // Initialize TFT display
  tft.begin();
  tft.setRotation(3); // Adjust based on your display orientation
  tft.fillScreen(ILI9341_BLACK);
  
  // Initialize relay
  pinMode(RELAY_PIN, OUTPUT);
  digitalWrite(RELAY_PIN, LOW); // Ensure relay is off initially

  // Display welcome message
  tft.setTextSize(3);
  tft.setTextColor(ILI9341_WHITE);
  tft.setCursor(5, 110);
  tft.println("SAGAR VERMA      M.TECH (PSPE)    SANGAM UNIVERSITY");
  delay(8000); 
  tft.fillScreen(ILI9341_BLACK);
}

void loop() {
  // Read temperature and humidity
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();
  
  // Check if reading failed
  if (isnan(temperature) || isnan(humidity)) {
    tft.setCursor(10, 10);
    tft.setTextColor(ILI9341_RED);
    tft.println("Failed to read from DHT sensor");
    return;
  }

  // Display temperature and humidity on the LCD
  tft.setCursor(10, 10);
  tft.setTextColor(ILI9341_WHITE);
  tft.setTextSize(3);
  tft.print("Temp: ");
  tft.print(temperature);
  tft.println(" C");
  tft.print("Humidity: ");
  tft.print(humidity);
  tft.println(" %");

  // Control relay based on temperature and humidity
  if (temperature > TEMP_THRESHOLD ) {
    digitalWrite(RELAY_PIN, HIGH); // Turn on relay
    tft.setCursor(5, 60);
    tft.setTextColor(ILI9341_RED);
    tft.println("Temp.Relay ON");
  } else {
    digitalWrite(RELAY_PIN, LOW); // Turn off relay
    tft.setCursor(5, 60);
    tft.setTextColor(ILI9341_GREEN);
    tft.println("Temp.Relay OFF");
  }
  // Control relay based on temperature and humidity
  if (humidity > HUMIDITY_THRESHOLD) {
    digitalWrite(RELAY_A, HIGH); // Turn on relay
    tft.setCursor(5, 90);
    tft.setTextColor(ILI9341_RED);
    tft.println("RH Relay ON");
  } else {
    digitalWrite(RELAY_A, LOW); // Turn off relay
    tft.setCursor(5, 90);
    tft.setTextColor(ILI9341_GREEN);
    tft.println("RH Relay OFF");
  }

  delay(2000); // Update every 2 seconds
}
NOCOMNCVCCGNDINLED1PWRRelay Module
NOCOMNCVCCGNDINLED1PWRRelay Module