/* * MECRO KIT - PROYECTO 08: CONTROL DE ACCESO (CAJA FUERTE)
* Objetivo: Lectura de Matrices (Keypad) y Control de Relé
* Hardware: ESP32, Keypad 4x4, Relé, Buzzer
* Librería requerida: Keypad
*/
#include <Keypad.h>
// --- 1. DEFINICIONES DE HARDWARE ---
const int PIN_RELE = 4; // Activa la cerradura
const int PIN_BUZZER = 2; // Feedback sonoro
// --- 2. CONFIGURACIÓN DEL KEYPAD ---
const byte FILAS = 4;
const byte COLUMNAS = 4;
// Mapa de caracteres del teclado
char teclas[FILAS][COLUMNAS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
// Pines conectados a las filas y columnas
// Nota: Evitamos GPIO 0, 1, 3 (Boot/UART)
byte pinesFilas[FILAS] = {13, 12, 14, 27};
byte pinesColumnas[COLUMNAS] = {26, 25, 33, 32};
// Crear objeto Keypad
Keypad teclado = Keypad(makeKeymap(teclas), pinesFilas, pinesColumnas, FILAS, COLUMNAS);
// --- 3. SISTEMA DE SEGURIDAD ---
const String CLAVE_MAESTRA = "1234"; // Clave correcta
String claveIngresada = ""; // Buffer de entrada
void setup() {
Serial.begin(115200);
pinMode(PIN_RELE, OUTPUT);
pinMode(PIN_BUZZER, OUTPUT);
// Estado inicial: Cerrado
digitalWrite(PIN_RELE, LOW);
Serial.println("--- SISTEMA DE SEGURIDAD MECRO: BLOQUEADO ---");
Serial.println("Ingrese Clave y presione '#'");
}
void loop() {
char tecla = teclado.getKey(); // Escaneo no bloqueante
if (tecla) {
// Feedback sonoro corto al presionar
tone(PIN_BUZZER, 2000, 50);
Serial.print("*"); // Ocultar clave en monitor serial
if (tecla == '#') {
// '#' actúa como ENTER
verificarClave();
}
else if (tecla == '*') {
// '*' actúa como BORRAR / RESET
claveIngresada = "";
Serial.println("\n[!] Entrada borrada.");
}
else {
// Acumular caracteres
claveIngresada += tecla;
}
}
}
void verificarClave() {
Serial.println(""); // Salto de línea
if (claveIngresada == CLAVE_MAESTRA) {
Serial.println(">>> ACCESO CONCEDIDO <<<");
accesoPermitido();
} else {
Serial.println(">>> ACCESO DENEGADO <<<");
accesoDenegado();
}
// Limpiar buffer para el siguiente intento
claveIngresada = "";
}
void accesoPermitido() {
// Sonido de éxito (Doble beep agudo)
tone(PIN_BUZZER, 3000, 100); delay(150);
tone(PIN_BUZZER, 3000, 200);
// Abrir cerradura (Activar Relé)
digitalWrite(PIN_RELE, HIGH);
delay(3000); // Mantener abierto 3 segundos
// Cerrar
digitalWrite(PIN_RELE, LOW);
Serial.println("Sistema Bloqueado nuevamente.");
}
void accesoDenegado() {
// Sonido de error (Tono grave largo)
tone(PIN_BUZZER, 500, 1000);
delay(1000);
}