// Code by Gunti Balakrishna 
#include <WiFi.h>
#include "ThingSpeak.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "DHT.h"
#include "RTClib.h"

LiquidCrystal_I2C LCD = LiquidCrystal_I2C(0x27, 16, 2);
DHT dht(25, DHT22);
RTC_DS1307 rtc;
WiFiClient client;

int soilMoisturePercentage=0;
const int SOIL_MOISTURE_PIN = 34;
const int SPRINKLER_CONTROL_PIN = 19;
int ledPin = 13;                // choose the pin for the LED
int inputPin = 12;               // choose the input pin (for PIR sensor)
int pirState = LOW;             // we start, assuming no motion detected
int val = 0;                    // variable for reading the pin status

int MOISTURE_THRESHOLD_LOW = 30;            // Set Activation threshold in percentage
int MOISTURE_THRESHOLD_HIGH = 85;           // Set Deactivation threshold in percentage
bool SPRINKLER_ACTIVATION_STATUS = false;
float temperature=0;
float humidity=0;
String timeStampDate;
String timeStampTime;
int last_localhour;
unsigned long localhour;
unsigned long localmin;
unsigned long localsec;

char* WIFI_NAME = "Wokwi-GUEST";
char* WIFI_PASSWORD = "";
int myChannelNumber = 2890496;              // ThingSpeak channel ID
char* myApiKey = "E9IS9T5RL3NOQ83F";        // ThingSpeak channel write API key

void setup() 
{
  Serial.begin(115200);
  rtc.begin();
  ThingSpeak.begin(client);
  dht.begin();
  LCD.init();
  LCD.backlight();
  LCD.setCursor(0, 0);
  LCD.print("Connecting to ");
  LCD.setCursor(0, 1);
  LCD.print("WiFi ");
  WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
  WiFi.mode(WIFI_STA);
  Serial.println("Connecting...");
  Serial.println("Wi-Fi connected");
  Serial.println("Local IP: " + String(WiFi.localIP()));
  Serial.println("-------------");

  LCD.clear();
  LCD.setCursor(0, 0);
  LCD.println("Wifi Connected");
  
  pinMode(SPRINKLER_CONTROL_PIN, OUTPUT);
  pinMode(ledPin, OUTPUT);      // declare LED as output
  pinMode(inputPin, INPUT);     // declare sensor as input
   LCD.clear();
   delay(5000); 
}

void loop()
{ 
  if (localsec % 10 ==0){
    ThingspeakDataPush();
  }
  if (localsec % 5 ==0){
  SoilMoistureRead();
  DhtRead(); 
  Serial.print("Soil Moisture Percentage: ");
  Serial.print(soilMoisturePercentage);
  Serial.println("%");
  Serial.print("Sprinkler: ");
  Serial.println(SPRINKLER_ACTIVATION_STATUS ? "on" : "off");
  Serial.print(F("Humidity: "));
  Serial.print(humidity);
  Serial.print(F("%  Temperature: "));
  Serial.print(temperature);
  Serial.println(F("°C "));
  }
  motionRead();
  timeRead();


  Serial.print(localhour);
  Serial.print(":");
  Serial.print(localmin);
  Serial.print(":");
  Serial.println(localsec); 
  Serial.println(timeStampDate);


 
  LCD.setCursor(0, 0);
  LCD.print("Soil moisture:");
  LCD.println(soilMoisturePercentage);
  LCD.setCursor(0, 1);
  LCD.print("Sprinkler:");
  LCD.println(SPRINKLER_ACTIVATION_STATUS ? "on" : "off");
  delay(500);
  LCD.clear();
  LCD.setCursor(0, 0);
  LCD.print("Temperature:");
  LCD.println(temperature);
  LCD.setCursor(0, 1);
  LCD.print("Humidity:");
  LCD.println(humidity);
   // Thingspeak allows for an update every 15 seconds
   delay(500);
}

void SoilMoistureRead() {
  soilMoisturePercentage = map(analogRead(SOIL_MOISTURE_PIN), 0, 4095, 0, 100);
  // Sprinkler activation threshold check
  if (soilMoisturePercentage < MOISTURE_THRESHOLD_LOW)
  {
    SPRINKLER_ACTIVATION_STATUS = true;
    digitalWrite(SPRINKLER_CONTROL_PIN, HIGH);// Turn on sprinkler and LED
  }
  else if (soilMoisturePercentage > MOISTURE_THRESHOLD_HIGH)
  {
    SPRINKLER_ACTIVATION_STATUS = false;
    digitalWrite(SPRINKLER_CONTROL_PIN, LOW); // Turn off sprinkler and LED
  }

}

void DhtRead(){
  temperature = dht.readTemperature();
  humidity = dht.readHumidity();
}
    
void motionRead(){
   val = digitalRead(inputPin);  // read input value
  if (val == HIGH) {            // check if the input is HIGH
    digitalWrite(ledPin, HIGH);  // turn LED ON
    if (pirState == LOW) {
      // we have just turned on
      Serial.println("Motion detected!");
      // We only want to print on the output change, not state
      pirState = HIGH;
    }
  } else {
    digitalWrite(ledPin, LOW); // turn LED OFF
    if (pirState == HIGH) {
      // we have just turned of
      Serial.println("Motion ended!");
      // We only want to print on the output change, not state
      pirState = LOW;
    }
  }
}

void timeRead(){
  DateTime time = rtc.now();
  localhour = time.hour();
  localmin = time.minute();
  localsec = time.second();
  timeStampDate=(time.timestamp(DateTime::TIMESTAMP_DATE));
  timeStampTime=(time.timestamp(DateTime::TIMESTAMP_TIME));
}
void ThingspeakDataPush()
{
  ThingSpeak.setField(1, temperature);
  ThingSpeak.setField(2, humidity);
  ThingSpeak.setField(3, soilMoisturePercentage);
  ThingSpeak.setField(4, val);
  int x = ThingSpeak.writeFields(myChannelNumber,myApiKey);
  if(x == 200){
    Serial.println("Data pushed successfull");
  }else{
    Serial.println("Push error" + String(x));
  }
} 
esp:0
esp:2
esp:4
esp:5
esp:12
esp:13
esp:14
esp:15
esp:16
esp:17
esp:18
esp:19
esp:21
esp:22
esp:23
esp:25
esp:26
esp:27
esp:32
esp:33
esp:34
esp:35
esp:3V3
esp:EN
esp:VP
esp:VN
esp:GND.1
esp:D2
esp:D3
esp:CMD
esp:5V
esp:GND.2
esp:TX
esp:RX
esp:GND.3
esp:D1
esp:D0
esp:CLK
soil-moisture-sensorBreakout
lcd1:GND
lcd1:VCC
lcd1:SDA
lcd1:SCL
dht1:VCC
dht1:SDA
dht1:NC
dht1:GND
pir1:VCC
pir1:OUT
pir1:GND
led1:A
led1:C
led2:A
led2:C
GND5VSDASCLSQWRTCDS1307+
rtc1:GND
rtc1:5V
rtc1:SDA
rtc1:SCL
rtc1:SQW
led3:A
led3:C