#define BLYNK_PRINT Serial
#define BLYNK_TEMPLATE_ID "TMPL341emGodb"
#define BLYNK_TEMPLATE_NAME "DUSID"
#define BLYNK_AUTH_TOKEN "dPf3tku919wewUPxFu4Ics9YSSgv_dtQ"
#include <WiFi.h>
#include <ArduinoJson.h>
#include <ESP32Servo.h>
#include <BlynkSimpleEsp32.h>
char auth[] = BLYNK_AUTH_TOKEN;
const char ssid[] = "Wokwi-GUEST";
const char pass[] = "";
BlynkTimer timer;
const int doorSensorPin = 13; // D13 Connect MC-38 Magnectic Door sensor
const int ledPin = 12; // D12 Connect with Piezo Buffer
const int servoPin = 2; // Just used for user closed door Action
Servo doorServo;
bool doorLocked = true;
bool unlockRequested = false;
// Support For Blynk IOT Platform
BLYNK_WRITE(V0)
{
int unlockButtonState = param.asInt();
if (unlockButtonState == 1) {
unlockRequested = true;
Blynk.virtualWrite(V1, HIGH);// turn on a vitual led
}
}
void setup() {
pinMode(doorSensorPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
// Connect to Wi-Fi
Serial.begin(115200);
Serial.println("Connecting to WiFi...");
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi");
}
Serial.println("\nConnected to WiFi");
// Attach the servo to the control pin
doorServo.attach(servoPin);
lockDoor(); //Lock the door initilly
// Initialize Blynk
Blynk.begin(auth, ssid, pass);
}
void loop() {
Blynk.run();
bool doorState = digitalRead(doorSensorPin);
//Serial.println(doorState); print 1
if (unlockRequested && doorState == HIGH) {
digitalWrite(doorSensorPin, HIGH);
Serial.println("Door closed, unlocking door...");
unlockDoor();
unlockRequested = false; // Reset the unlock request
}
if (doorLocked) {
// The door is locked, turn off the LED
digitalWrite(ledPin, LOW);
} else {
// The door is unlocked, turn on the LED for 5 seconds
Serial.println("LED(buzzer) is off -- wait for 5 second");
digitalWrite(ledPin, LOW);
delay(5000); // wait for 5 seconds
Serial.println("LED(buzzer) is ON---User not closed door( 5 second )");
digitalWrite(ledPin, HIGH); // Turn of the LED
// After 10 seconds , close the door
delay(5000); // wait for another 5 seconds
Serial.println("LED(buzzer) is OFF--- once User closed door");
lockDoor(); // Lock the door
}
}
void unlockDoor() {
Serial.println("unlocking door...");
doorServo.write(90);
doorLocked = false;
}
void lockDoor() {
Serial.println("Locking door...");
doorServo.write(0);
doorLocked = true;
// You can implement this function to lock the door if needed
// This is a placeholder, and the actual implementation depends on your hardware.
}