#define BLYNK_TEMPLATE_ID "TMPL6mgffu1tv"
#define BLYNK_TEMPLATE_NAME "Smart Door Lock"
#define BLYNK_AUTH_TOKEN "KIhQ1ZyWaKd50DA0gsnLAm-Ip796nHnh"
#include <WiFi.h>
#include <BlynkSimpleEsp32.h>
#include <ESP32Servo.h>
// Blynk settings
char auth[] = BLYNK_AUTH_TOKEN;
// WiFi credentials
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
// Define servo settings
Servo myServo;
const int servoPin = 22;
const int unlockPosition = -90; // Set servo position to -90 degrees
const int lockPosition = 90; // Set servo position to +90 degrees
// Define buzzer pin
const int buzzerPin = 21;
// Variables
bool locked = true;
// Blynk virtual pin handler
BLYNK_WRITE(V0) {
int switchState = param.asInt();
if (switchState == 1) { // Jika switch ON
unlockDoor();
} else { // Jika switch OFF
lockDoor();
}
}
void setup() {
Serial.begin(9600);
// Initialize Blynk
Blynk.begin(auth, ssid, pass);
// Initialize servo
myServo.attach(servoPin);
// Initialize buzzer
pinMode(buzzerPin, OUTPUT);
// Set initial lock state
lockDoor();
}
void loop() {
Blynk.run();
}
void unlockDoor() {
locked = false;
myServo.write(unlockPosition);
Serial.println("Door Unlocked");
Blynk.virtualWrite(V0, 1); // Update Blynk switch to ON
playBuzzer(2); // Buzzer berbunyi dua kali
}
void lockDoor() {
locked = true;
myServo.write(lockPosition);
Serial.println("Door Locked");
Blynk.virtualWrite(V0, 0); // Update Blynk switch to OFF
playBuzzer(1); // Buzzer berbunyi sekali
}
// Function to play buzzer sound
void playBuzzer(int times) {
for (int i = 0; i < times; i++) {
digitalWrite(buzzerPin, HIGH);
delay(200); // Durasi bunyi 200 ms
digitalWrite(buzzerPin, LOW);
delay(200); // Jeda antar bunyi 200 ms
}
}