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

// 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 with 16 columns and 2 rows
  lcd.begin(16, 2);
  lcd.backlight();
  
  // Display the project name initially
  lcd.setCursor(0, 0);
  lcd.print("Landslide");
  lcd.setCursor(0, 1);
  lcd.print("Monitoring");
  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);

  // Clear the display for fresh output
  lcd.clear();
  
  // Display sensor reading on the first row
  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 or warnings on the second row
  if (moisture > threshold2) {
    // Landslide Alert: Show message in the second row
    lcd.setCursor(0, 1);
    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) {
    // Warning: Show message in the second row
    lcd.setCursor(0, 1);
    lcd.print("War:Hi_Moisture");
    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
  } else {
    // If no alert or warning, just delay for the next reading
    delay(1000);
  }
}