#include <WiFi.h>
#include <BlynkSimpleEsp32.h>
#include <Keypad.h>
#include <ESP32Servo.h>
#define BLYNK_TEMPLATE_ID "TMPL3gQuGFaeN"
#define BLYNK_TEMPLATE_NAME "lock"
#define BLYNK_AUTH_TOKEN "qA0a6XMMTnM4A3Pi29Rh3k09ZCAwLEeJ"
char auth[] = "qA0a6XMMTnM4A3Pi29Rh3k09ZCAwLEeJ"; // Replace with your Blynk auth token
char ssid[] = ""; // Replace with your WiFi name
char pass[] = ""; // Replace with your WiFi password
// Keypad Configuration
const byte ROWS = 4, COLS = 4;
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}};
byte rowPins[ROWS] = {25, 26, 27, 14};
byte colPins[COLS] = {32, 33, 12, 13};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// Servo Motor
Servo lockServo;
const int servoPin = 4;
const int LOCK_POS = 90; // Locked position
const int UNLOCK_POS = 0; // Unlocked position
// PIN Code Configuration
String correctPIN = "1234";
String enteredPIN = "";
bool isUnlocked = false;
unsigned long unlockTime = 0;
const unsigned long LOCK_DELAY = 5000; // Auto-lock after 5 seconds
void setup() {
Serial.begin(115200);
Blynk.begin(auth, ssid, pass); // Connect to Blynk
lockServo.attach(servoPin, 500, 2500); // Servo PWM range
lockServo.write(LOCK_POS); // Start locked
Serial.println("🔒 System Locked.");
}
void loop() {
Blynk.run();
char key = keypad.getKey();
if (key) {
Serial.print(key);
if (key == '#') checkPIN();
else if (key == '*') resetPIN();
else enteredPIN += key;
}
if (isUnlocked && millis() - unlockTime > LOCK_DELAY) autoLock();
}
// Keypad Unlock
void checkPIN() {
if (enteredPIN == correctPIN) {
Serial.println("\n✅ Correct PIN! Unlocking...");
lockServo.write(UNLOCK_POS);
Serial.println("🔄 Servo moved to: UNLOCK_POS");
Blynk.notify("🔓 Lock Opened!"); // Blynk notification
isUnlocked = true;
unlockTime = millis();
} else {
Serial.println("\n❌ Incorrect PIN!");
}
enteredPIN = "";
}
// Reset PIN Entry
void resetPIN() {
enteredPIN = "";
Serial.println("\nPIN Reset");
}
// Auto-Lock after Delay
void autoLock() {
Serial.println("Auto-locking...");
lockServo.write(LOCK_POS);
Blynk.virtualWrite(V0, 0); // Update Blynk switch
isUnlocked = false;
}
// Blynk App Control (Virtual Pin V0)
BLYNK_WRITE(V0) {
int lockState = param.asInt();
if (lockState == 1) {
lockServo.write(UNLOCK_POS);
Serial.println("🔓 Unlocked via Blynk");
Blynk.notify("🔓 Lock Opened!");
isUnlocked = true;
unlockTime = millis();
} else {
autoLock();
}
}