#define BLYNK_TEMPLATE_ID "TMPL6Y32GtecJ"
#define BLYNK_TEMPLATE_NAME "Smart Irrigation System"
#define BLYNK_AUTH_TOKEN "7aIfp688C2szYSfdBAHoFvt7LnM6wN19"

#include <BlynkSimpleEsp32.h>

// Define Pins
#define moistureSensor_PIN 32 // Potentiometer SIG
#define relay_PIN 13 // Relay IN pin
#define LED_PIN 27 // LED pin

// Blynk Setup
char auth[] = BLYNK_AUTH_TOKEN;
char ssid[] = "Wokwi-GUEST";
char pass[] = "";

// Variables
int moistureLevel = 0;             // Store moisture level
int moistureThreshold = 500;       // Threshold for automatic control
bool manualControl = false;        // Mode: Manual or Automatic

// Blynk Virtual Pins
#define V1 1 // Manual Control Switch
#define V2 2 // Moisture Level Display
#define V3 3 // Threshold Control (Slider)

// Blynk Switch for Manual Control
BLYNK_WRITE(V1) {
  manualControl = param.asInt(); // 1 = Manual Mode ON, 0 = Automatic Mode
}

// Blynk Slider for Threshold Adjustment
BLYNK_WRITE(V3) {
  moistureThreshold = param.asInt();
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

    // Blynk Initialization
  Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass);

  // Pin Modes
  pinMode(moistureSensor_PIN, INPUT);
  pinMode(relay_PIN, OUTPUT);
  pinMode(LED_PIN, OUTPUT);

  // Default states
  digitalWrite(relay_PIN, LOW); // Pump OFF
  digitalWrite(LED_PIN, LOW);   // LED OFF
}

void loop() {
// Run Blynk
  Blynk.run();

  // Read moisture level
  moistureLevel = map(analogRead(moistureSensor_PIN), 0, 4095, 0, 1023);
  Serial.print("Moisture Level: ");
  Serial.println(moistureLevel);

  // Send moisture level to Blynk app
  Blynk.virtualWrite(V2, moistureLevel);

  // Automatic Control
  if (!manualControl) {
    if (moistureLevel < moistureThreshold) { 
        // Soil is too dry
        digitalWrite(LED_PIN, HIGH);
    } else {
        // Soil moisture is sufficient
        digitalWrite(LED_PIN, LOW);
    }
  }
}
NOCOMNCVCCGNDINLED1PWRRelay Module