#define BLYNK_PRINT Serial
#define SERVO A18 //D18
#define BUTTON T2 //D2
#define BLYNK_TEMPLATE_ID "TMPL6iXWti0to"
#define BLYNK_TEMPLATE_NAME "Door Lock System"
#define BLYNK_AUTH_TOKEN "F7t-Pca7uYLf9ExwJg-J2khcGMTdptYt"

#include <WiFi.h>
#include <ESP32Servo.h>
#include <BlynkSimpleEsp32.h>
#include <ezButton.h>
#include <Blynk.h>

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "F7t-Pca7uYLf9ExwJg-J2khcGMTdptYt";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "Wokwi-GUEST";
char pass[] = "";

ezButton button(BUTTON);
Servo servo;

bool door;
int pos;

BLYNK_WRITE(V3) {
  int pinValue=param.asInt();
  if(pinValue==1) {
      for (pos = 90; pos <= 180; pos += 5) { 
        servo.write(pos);              
        delay(15);
      }
      digitalWrite(SERVO,HIGH);      //INVERTED STATUS OF LED PINS:HIGH means LOW
      door=true;
  }
  else {
    for (pos = 180; pos >= 90; pos -= 5) { 
      servo.write(pos);              
      delay(15);
    }
    digitalWrite(SERVO,LOW);                                                          //LOW-->HIGH
    door=false;
  }
}

void IntCallback() {
  if(door==false) {
      for (pos = 90; pos <= 180; pos += 5) { 
        servo.write(pos);              
        delay(15);
      }
      digitalWrite(SERVO,HIGH);                                                           //INVERTED STATUS OF LED PINS:HIGH means LOW
      door=true;
  }
  else {
      for (pos = 180; pos >= 90; pos -= 5) { 
        servo.write(pos);              
        delay(15);
      }
      digitalWrite(SERVO,LOW);                                                           //INVERTED STATUS OF LED PINS:HIGH means LOW
      door=false;
  }
}

void setup() {
  // Debug console
  Serial.begin(9600);
  Blynk.begin(auth, ssid, pass);
  // You can also specify server:
  //Blynk.begin(auth, ssid, pass, "blynk-cloud.com", 80);
  //Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080);
  servo.attach(18);     
  pinMode(SERVO,OUTPUT);
  attachInterrupt(digitalPinToInterrupt(BUTTON),IntCallback,RISING);
}

void loop() {
  Blynk.run();
}