#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
#define I2C_ADDR 0x27
#define LCD_COLUMNS 16
#define LCD_ROWS 2
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_ROWS);
// Pines
const int pinServo = 9; // D9 servo
const int pinLed = 8; // D8 LED
const int minPulseWidth = 500;
const int maxPulseWidth = 2400;
bool puertaAbierta = false;
// Keypad pines (tus originales)
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] = {2, 3, 4, 5}; // R1-R4
byte colPins[COLS] = {6, 7, 10, 11}; // C1-C4
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// Contraseñas
const String passwordAbrir = "1706";
const String passwordCerrar = "0000";
String input = "";
void setup() {
Serial.begin(115200); // Opcional, solo debug final
pinMode(pinServo, OUTPUT);
pinMode(pinLed, OUTPUT);
lcd.init();
lcd.backlight();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Puerta cerrada");
moverServo(0);
digitalWrite(pinLed, LOW);
}
void loop() {
char key = keypad.getKey();
if (key != NO_KEY) {
// MOSTRAR TECLA EN LCD (¡esto faltaba!)
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Tecla: ");
lcd.print(key);
delay(300); // Muestra 300ms
if (key == '*') { // Borrar
input = "";
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Clave borrada");
delay(800);
mostrarEstado();
}
else if (key == '#') { // Confirmar
lcd.clear();
lcd.setCursor(0, 0);
if (input == passwordAbrir) {
puertaAbierta = true;
moverServo(90);
digitalWrite(pinLed, HIGH);
lcd.print("Puerta ABIERTA");
}
else if (input == passwordCerrar) {
puertaAbierta = false;
moverServo(0);
digitalWrite(pinLed, LOW);
lcd.print("Puerta CERRADA");
}
else {
lcd.print("CLAVE INCORRECTA");
delay(1500);
mostrarEstado();
}
delay(2000);
input = "";
mostrarEstado();
}
else { // Agregar dígito
if (input.length() < 4) {
input += key;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Clave: ");
lcd.setCursor(0, 1);
for (int i = 0; i < input.length(); i++) {
lcd.print('*');
}
}
}
}
}
void mostrarEstado() {
lcd.clear();
lcd.setCursor(0, 0);
if (puertaAbierta) {
lcd.print("Puerta ABIERTA");
lcd.setCursor(0, 1);
lcd.print("0000= Cerrar");
} else {
lcd.print("Puerta CERRADA");
lcd.setCursor(0, 1);
lcd.print("9856= Abrir");
}
}
void moverServo(int angulo) {
int pulseWidth = map(angulo, 0, 180, minPulseWidth, maxPulseWidth);
for (int i = 0; i < 50; i++) {
digitalWrite(pinServo, HIGH);
delayMicroseconds(pulseWidth);
digitalWrite(pinServo, LOW);
delay(20 - pulseWidth / 1000);
}
}