#include <Keypad.h>
#include <ESP32Servo.h>
const int servoPin = 4; // Pin del servo
const int buzzerPin = 13;
// ÁNGULOS
const int openAngle = 90;
const int closeAngle = 0; // Cerrar a 0°
const int openTime = 5000; // Tiempo de apertura
// Teclado
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[ROWS] = {19, 18, 5, 17};
byte colPins[COLS] = {16, 21, 22, 23};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
String inputPassword;
const String correctPassword = "1702";
bool isOpen = false;
unsigned long closeTime = 0;
Servo myServo;
void setup() {
Serial.begin(115200);
myServo.attach(servoPin);
pinMode(buzzerPin, OUTPUT);
// INICIAR EN POSICIÓN CERRADA (0°)
myServo.write(closeAngle);
delay(2000); // Espera para asegurar que el servo se mueva
Serial.println("✅ SISTEMA LISTO - Clave: 1702");
Serial.println("🔧 Ángulo CERRADO: 0° (corregido)");
}
void loop() {
// Verificar cierre automático
if (isOpen && millis() > closeTime) {
Serial.println("🕒 CIERRE AUTOMÁTICO - Moviendo a 0°");
closeSafe();
}
char key = keypad.getKey();
if (key) {
processKey(key);
}
delay(50);
}
void processKey(char key) {
Serial.print("Tecla: ");
Serial.println(key);
if (key == '#') {
checkPassword();
} else if (key == '*') {
inputPassword = "";
Serial.println("Entrada borrada");
} else if (inputPassword.length() < 4) {
inputPassword += key;
Serial.print("Password: ");
for (int i = 0; i < inputPassword.length(); i++) Serial.print('*');
Serial.println();
}
}
void checkPassword() {
Serial.print("🔐 Verificando: ");
Serial.println(inputPassword);
if (inputPassword == correctPassword) {
Serial.println("🎉 CLAVE CORRECTA");
if (!isOpen) {
openSafe();
}
} else {
Serial.println("❌ CLAVE INCORRECTA");
errorSound();
}
inputPassword = "";
}
void openSafe() {
Serial.println("🚀 ABRIENDO - Moviendo a 90°");
myServo.write(openAngle);
delay(1500); // Espera para permitir que el servo se mueva
tone(buzzerPin, 1500, 300);
delay(400);
isOpen = true;
closeTime = millis() + openTime;
Serial.println("✅ ABIERTO - Cierre en 5 segundos");
}
void closeSafe() {
Serial.println("🔒 CERRANDO - Moviendo a 0°");
myServo.write(closeAngle); // Mover el servo a 0°
delay(2000); // Espera para permitir que el servo se mueva completamente
// Verifica si el servo se movió a 0°
int currentAngle = myServo.read(); // Lee el ángulo actual del servo
Serial.print("Ángulo actual del servo: ");
Serial.println(currentAngle);
tone(buzzerPin, 1000, 300);
delay(400);
isOpen = false;
Serial.println("✅ CERRADO en posición 0°");
}
void errorSound() {
tone(buzzerPin, 800, 200);
delay(300);
tone(buzzerPin, 600, 200);
delay(300);
}