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

// Initialize the I2C LCD display (address 0x27)
LiquidCrystal_I2C lcd(0x27, 16, 2);

// Define pin for the sensor and buzzer
const int sensorPin = A0;
const int buzzerPin = 4;
const int threshold1 = 65; // 65% threshold for warning
const int threshold2 = 70; // 70% threshold for landslide alert

void setup() {
  // Initialize the LCD
  lcd.begin();
  lcd.backlight();
  
  // Display the project name
  lcd.setCursor(0, 0);
  lcd.print("Landslide Monit");
  delay(2000);
  lcd.clear();
  
  // Start serial communication for debugging
  Serial.begin(9600);
  
  // Initialize the buzzer pin as output
  pinMode(buzzerPin, OUTPUT);
}

void loop() {
  // Read sensor value (assume 0-1023 values map to 0-100%)
  int sensorValue = analogRead(sensorPin);

  // Map the sensor value to a percentage (0-100%)
  int moisture = map(sensorValue, 0, 1023, 0, 100);
  
  // Display sensor reading on LCD
  lcd.setCursor(0, 0);
  lcd.print("Moisture: ");
  lcd.print(moisture);
  lcd.print("%");

  // Print the reading to the Serial Monitor for debugging
  Serial.print("Moisture: ");
  Serial.println(moisture);

  // Check moisture levels and display alerts
  if (moisture > threshold2) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Landslide Alert!");
    Serial.println("Landslide Alert! Sensor exceeded 70%");
    
    // Trigger the buzzer with a different tone every 2 seconds
    tone(buzzerPin, 1000);  // Play tone at 1000 Hz
    delay(500);
    noTone(buzzerPin);      // Stop tone
    delay(1500);            // Delay before next tone
  } 
  else if (moisture > threshold1) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Warning: High Moist");
    Serial.println("Warning: Moisture above 65%");
    
    // Trigger the buzzer with a different tone every 5 seconds
    tone(buzzerPin, 500);   // Play tone at 500 Hz
    delay(500);
    noTone(buzzerPin);      // Stop tone
    delay(4500);            // Delay before next tone
  }

  // Delay between readings
  delay(1000);
}