#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);
// Servo y LED
const int pinServo = 9;
const int pinLed = 8;
const int minPulseWidth = 500;
const int maxPulseWidth = 2400;
// -------- KEYPAD --------
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};
byte colPins[COLS] = {6,10,11,12};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// contraseña
String password = "1234";
String input = "";
bool puertaAbierta = false;
void setup() {
Serial.begin(115200);
pinMode(pinServo, OUTPUT);
pinMode(pinLed, OUTPUT);
lcd.init();
lcd.backlight();
lcd.setCursor(0,0);
lcd.print("Ingrese clave");
moverServo(0);
}
void loop() {
char key = keypad.getKey();
if (key) {
lcd.setCursor(0,1);
lcd.print(" ");
lcd.setCursor(0,1);
input += key;
lcd.print(input);
if (input.length() == 4) {
if (input == password) {
lcd.clear();
lcd.print("Clave correcta");
moverServo(90);
digitalWrite(pinLed, HIGH);
} else {
lcd.clear();
lcd.print("Clave incorrecta");
moverServo(0);
digitalWrite(pinLed, LOW);
}
delay(2000);
input = "";
lcd.clear();
lcd.print("Ingrese clave");
}
}
}
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);
}
}