#define BLYNK_TEMPLATE_ID "TMPL3SveEzQ9p"
#define BLYNK_TEMPLATE_NAME "Servo Control"

#define BLYNK_PRINT Serial
#include <WiFi.h>
#include <BlynkSimpleEsp32.h>
#include <ESP32Servo.h>

// WiFi & Blynk Credentials
char auth[] = "uPZuwmbVxGOSyPeFzCpjzuIg0WiRoVhI";  // Your Blynk Auth Token
char ssid[] = "Wokwi-GUEST";  
char pass[] = "";  

// Pin Definitions
#define POT1_PIN 34   // First Potentiometer
#define POT2_PIN 35   // Second Potentiometer
#define SERVO1_PIN 26 // First Servo
#define SERVO2_PIN 27 // Second Servo

// Virtual Pins
#define CONTROL_PIN V0   // Mode Selection Switch
#define BLYNK_SERVO1 V1  // Servo 1 Control from Blynk
#define BLYNK_SERVO2 V2  // Servo 2 Control from Blynk
#define POT1_DISPLAY V3  // Potentiometer 1 Value Display
#define POT2_DISPLAY V4  // Potentiometer 2 Value Display

ESP32Servo servo1, servo2;
bool useBlynk = false; // Default mode: Potentiometer control

// Blynk Mode Selection
BLYNK_WRITE(CONTROL_PIN) {
    useBlynk = param.asInt(); // Read switch state (0 = Pot, 1 = Blynk)
}

// Blynk Servo 1 Control
BLYNK_WRITE(BLYNK_SERVO1) {
    if (useBlynk) {
        int angle1 = param.asInt();
        servo1.write(angle1);
    }
}

// Blynk Servo 2 Control
BLYNK_WRITE(BLYNK_SERVO2) {
    if (useBlynk) {
        int angle2 = param.asInt();
        servo2.write(angle2);
    }
}

void setup() {
    Serial.begin(115200);
    Blynk.begin(auth, ssid, pass);

    servo1.attach(SERVO1_PIN, 500, 2400);
    servo2.attach(SERVO2_PIN, 500, 2400);
}

void loop() {
    Blynk.run();
    
    int potValue1 = analogRead(POT1_PIN);
    int potValue2 = analogRead(POT2_PIN);
    
    int angle1 = map(potValue1, 0, 4095, 0, 180);
    int angle2 = map(potValue2, 0, 4095, 0, 180);

    Blynk.virtualWrite(POT1_DISPLAY, angle1);
    Blynk.virtualWrite(POT2_DISPLAY, angle2);

    if (!useBlynk) {  // Potentiometer Mode
        servo1.write(angle1);
        servo2.write(angle2);
    }
}
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