#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
#include <ESP32Servo.h>

#define DHTPIN 19   // DHT22 data pin
#define DHTTYPE DHT22  // DHT type

DHT dht(DHTPIN, DHTTYPE);

LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C address 0x27, 16 columns and 2 rows

const int blueLED = 13;
const int yellowLED = 12;
const int redLED = 14;
const int buzzerPin = 15;
const int servoPin = 27;

Servo myservo;

void setup() {
  Serial.begin(115200);
  dht.begin();
  Wire.begin();
  lcd.init();
  lcd.backlight();
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("TEMP MONITOR");

  pinMode(blueLED, OUTPUT);
  pinMode(yellowLED, OUTPUT);
  pinMode(redLED, OUTPUT);
  pinMode(buzzerPin, OUTPUT);

  myservo.attach(servoPin);
}

void loop() {
  delay(2000);  // Delay between readings

  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Temp: " + String(temperature) + " C'");
  lcd.setCursor(0, 1);
  lcd.print("Humi: " + String(humidity) + " %");

  // Check comfort levels and control LEDs, buzzer, and servo
  checkComfort(temperature);
}

void checkComfort(float temperature) {
  if (temperature <= 34.0) { // Cold
    digitalWrite(blueLED, HIGH);
    digitalWrite(yellowLED, LOW);
    digitalWrite(redLED, LOW);
    myservo.write(22.5); // Move servo to the left
  } else if (temperature > 34.0 && temperature <= 60.0) { // Warm
    digitalWrite(blueLED, LOW);
    digitalWrite(yellowLED, HIGH);
    digitalWrite(redLED, LOW);
    myservo.write(90); // Center position
  } else { // Hot
    digitalWrite(blueLED, LOW);
    digitalWrite(yellowLED, LOW);
    digitalWrite(redLED, HIGH);
    myservo.write(157.5); // Move servo to the right
    activateBuzzer(); // Activate buzzer for higher temperatures
  }
}

void activateBuzzer() {
  digitalWrite(buzzerPin, HIGH); // Activate buzzer
  delay(2000); // Buzzer active for 2 seconds
  digitalWrite(buzzerPin, LOW); // Turn off buzzer
}