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

#define DHTPIN 2      // Digital pin where the DHT22 is connected
#define DHTTYPE DHT22 // Type of DHT sensor
#define PHOTO_PIN A1  // Analog pin where the photoresistor is connected
#define MOISTURE_PIN A0 // Analog pin where the moisture sensor is connected

DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C lcd(0x27, 20, 4); // I2C address 0x27, 20 columns, 4 rows
RTC_DS1307 rtc;  // Create an RTC object

unsigned long startTime;  // Variable to store the start time

void setup() {
  Serial.begin(9600);
  lcd.begin(20, 4);
  dht.begin();
  Wire.begin();
  if (!rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
  if (!rtc.isrunning()) {
    Serial.println("RTC is NOT running, let's set the time!");
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }

  // Store the start time
  startTime = millis();
}

void loop() {
  // Read humidity and temperature from DHT22 sensor
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();

  // Read soil moisture sensor
  int moistureValue = analogRead(MOISTURE_PIN);

  // Read light intensity from the photoresistor
  int lightValue = analogRead(PHOTO_PIN);

  // Get the current time from the RTC
  DateTime now = rtc.now();

  // Calculate elapsed time
  unsigned long elapsedTime = millis() - startTime;
  unsigned long elapsedSeconds = elapsedTime / 1000;
  unsigned long elapsedMinutes = elapsedSeconds / 60;
  unsigned long elapsedHours = elapsedMinutes / 60;
  unsigned long elapsedDays = elapsedHours / 24;

  // Display on LCD 20x4
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Temperature: ");
  lcd.print(temperature);
  lcd.print("C");
  lcd.setCursor(0, 1);
  lcd.print("Moisture: ");
  lcd.print(moistureValue);
  lcd.print("  ");
  lcd.setCursor(0, 2);
  lcd.print("Elapsed Time: ");
  lcd.print(elapsedDays);
  lcd.print("d ");
  lcd.print(elapsedHours % 24);
  lcd.print("h ");
  lcd.print(elapsedMinutes % 60);
  lcd.print("m");
  lcd.setCursor(0, 3);
  lcd.print("Light: ");
  lcd.print(lightValue);

  // Print to Serial Monitor for verification
  Serial.print("Temperature: ");
  Serial.print(temperature);
  Serial.print("°C, Moisture: ");
  Serial.print(moistureValue);
  Serial.print(", Elapsed: ");
  Serial.print(elapsedDays);
  Serial.print("d ");
  Serial.print(elapsedHours % 24);
  Serial.print("h ");
  Serial.print(elapsedMinutes % 60);
  Serial.print("m, Light: ");
  Serial.println(lightValue);

  delay(2000); // Wait for 2 seconds before the next reading
}
GND5VSDASCLSQWRTCDS1307+