#include <ArduinoIoTCloud.h>
#include <Arduino_ConnectionHandler.h>
#include <Keypad.h>
#include <ESP32Servo.h>
// Wi-Fi Credentials
const char SSID[] = "YOUR_WIFI_SSID";
const char PASS[] = "YOUR_WIFI_PASSWORD";
// Arduino IoT Cloud Credentials
const char DEVICE_ID[] = " de2e8e0a-1b18-4b6e-b82c-f2631f01f0dd";
const char SECRET_KEY[] = " e7#uu3xT3tL!1#NUKBA?WnR0J"; // Added Secret Key
WiFiConnectionHandler ArduinoIoTCloud(SSID, PASS);
// Keypad setup
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 Setup
Servo lockServo;
const int servoPin = 4;
const int LOCK_POS = 90;
const int UNLOCK_POS = 0;
// Lock System Variables
String correctPIN = "2042";
String enteredPIN = "";
bool isUnlocked = false;
unsigned long unlockTime = 0;
const unsigned long LOCK_DELAY = 5000;
// Cloud variable
bool lockState = false;
void onLockStateChange() {
if (lockState) {
lockServo.write(UNLOCK_POS);
Serial.println("🔓 Unlocked from Cloud!");
} else {
lockServo.write(LOCK_POS);
Serial.println("🔒 Locked from Cloud!");
}
}
void setup() {
Serial.begin(115200);
lockServo.attach(servoPin, 500, 2500);
lockServo.write(LOCK_POS);
Serial.println("🔒 System Locked.");
// Connect to Arduino IoT Cloud
ArduinoCloud.begin(SSID, PASS);
setDebugMessageLevel(2);
ArduinoCloud.addProperty(lockState, READWRITE, ON_CHANGE, onLockStateChange);
}
void loop() {
ArduinoCloud.update(); // Keep Cloud connection active
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();
}
void checkPIN() {
if (enteredPIN == correctPIN) {
Serial.println("\n✅ Correct PIN! Unlocking...");
lockServo.write(UNLOCK_POS);
lockState = true; // Sync with Cloud
isUnlocked = true;
unlockTime = millis();
} else {
Serial.println("\n❌ Incorrect PIN!");
}
enteredPIN = "";
}
void resetPIN() {
enteredPIN = "";
Serial.println("\nPIN Reset");
}
void autoLock() {
Serial.println("🔒 Auto-locking...");
lockServo.write(LOCK_POS);
lockState = false; // Sync with Cloud
isUnlocked = false;
}