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

const int sunlightPin = A0;       // Analog pin for LDR (simulating sunlight sensor)
const int rgbLedRedPin = 9;       // Digital pin for Red component of RGB LED (simulating watering system)
const int rgbLedGreenPin = 10;    // Digital pin for Green component of RGB LED
const int rgbLedBluePin = 11;     // Digital pin for Blue component of RGB LED
const int buzzerPin = 12;         // Digital pin for simulated buzzer
const int LCD_address = 0x27;     // I2C address of the LCD module
const int LCD_columns = 16;       // Number of columns in the LCD
const int LCD_rows = 2;           // Number of rows in the LCD

int sunlightThresholdHigh = 800;  // Adjust this threshold for high sunlight

LiquidCrystal_I2C lcd(LCD_address, LCD_columns, LCD_rows);

void setup() {
  pinMode(sunlightPin, INPUT);
  pinMode(rgbLedRedPin, OUTPUT);
  pinMode(rgbLedGreenPin, OUTPUT);
  pinMode(rgbLedBluePin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);

  lcd.begin(LCD_columns, LCD_rows);
  lcd.print("Automatic Watering");
  lcd.setCursor(0, 1);
  lcd.print("System - Wokwi");

  Serial.begin(9600);
}

void loop() {
  int sunlightLevel = analogRead(sunlightPin);
  Serial.print("Sunlight Level: ");
  Serial.println(sunlightLevel);

  // Display sunlight level on the LCD
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Sunlight: ");
  lcd.print(sunlightLevel);

  if (sunlightLevel > sunlightThresholdHigh) {
    // High sunlight, simulate watering by changing RGB LED color to blue, activate the buzzer, and display a message on the LCD
    simulateWatering();
    alert("High Sunlight! Watering Plants");
  } else {
    // Sunlight within the normal range, stop watering simulation, turn off the buzzer, and turn off the RGB LED
    stopWatering();
  }

  delay(1000);  // Adjust the delay based on your simulation needs
}

void simulateWatering() {
  // Simulate watering by changing RGB LED color to blue, and activate the buzzer
  digitalWrite(rgbLedRedPin, LOW);
  digitalWrite(rgbLedGreenPin, LOW);
  digitalWrite(rgbLedBluePin, HIGH);
  tone(buzzerPin, 1000, 500);
}

void stopWatering() {
  // Turn off simulated watering by turning off the RGB LED, and turning off the buzzer
  digitalWrite(rgbLedRedPin, LOW);
  digitalWrite(rgbLedGreenPin, LOW);
  digitalWrite(rgbLedBluePin, LOW);
  noTone(buzzerPin);
}

void alert(String message) {
  // Display an alert message on the LCD
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("ALERT: ");
  lcd.setCursor(0, 1);
  lcd.print(message);
  delay(2000);
}