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

#define RED_LED_PIN 15
#define GREEN_LED_PIN 0
#define MOTION_SENSOR_PIN 34
#define BUZZER_PIN 13

int msensor_state = LOW;
bool motion_detected = false;

LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup() {
  pinMode(RED_LED_PIN, OUTPUT);
  pinMode(GREEN_LED_PIN, OUTPUT);
  pinMode(MOTION_SENSOR_PIN, INPUT);
  pinMode(BUZZER_PIN, OUTPUT);

  ledcSetup(0, 1000, 10);
  lcd.init();
  lcd.backlight();

  digitalWrite(GREEN_LED_PIN, HIGH);
  lcd.setCursor(0, 0);
  lcd.print("HomeAlert System");
  lcd.setCursor(0, 1);
  lcd.print("Status: CLEAR!");
}

void loop() {
  msensor_state = digitalRead(MOTION_SENSOR_PIN);

  if (msensor_state == HIGH && !motion_detected) {
    motion_detected = true;
    updateSystemStatus(true);
  } 
  else if (msensor_state == LOW && motion_detected) {
    motion_detected = false;
    updateSystemStatus(false);
  }
}

void updateSystemStatus(bool warning) {
  digitalWrite(GREEN_LED_PIN, !warning);
  digitalWrite(RED_LED_PIN, warning);
  digitalWrite(BUZZER_PIN, warning);
  tone(BUZZER_PIN, warning ? 1000 : 0);

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("HomeAlert System");

  lcd.setCursor(0, 1);
  lcd.print("Status: ");
  lcd.print(warning ? "WARNING!" : "CLEAR!");

  if (warning) {
    delay(5000);
  }
}