int boton1 = 2;
int boton2 = 3;
int boton3 = 4;
int boton4 = 5;
int ledR = 7;
int ledV = 8;
int rele = 9;
String clave = "12334";
String entrada = "";
unsigned long tiempoUltimaPulsacion = 0;
const unsigned long tiempoEspera = 3000;
int intentos = 0;
bool bloqueado = false;
unsigned long tiempoBloqueo = 0;
void setup() {
pinMode(boton1, INPUT);
pinMode(boton2, INPUT);
pinMode(boton3, INPUT);
pinMode(boton4, INPUT);
pinMode(ledR, OUTPUT);
pinMode(ledV, OUTPUT);
pinMode(rele, OUTPUT);
Serial.begin(9600);
delay(500);
Serial.println("Sistema iniciado. Esperando clave...");
}
void loop() {
if (bloqueado) {
if (millis() - tiempoBloqueo >= 60000) {
bloqueado = false;
intentos = 0;
entrada = "";
Serial.println("Sistema desbloqueado. Intenta de nuevo.");
}
return;
}
leerBotones();
if (entrada.length() > 0 && millis() - tiempoUltimaPulsacion >= tiempoEspera) {
verificarClave();
}
}
void leerBotones() {
if (botonPresionado(boton1)) registrarPulsacion("1", boton1);
if (botonPresionado(boton2)) registrarPulsacion("2", boton2);
if (botonPresionado(boton3)) registrarPulsacion("3", boton3);
if (botonPresionado(boton4)) registrarPulsacion("4", boton4);
}
bool botonPresionado(int pin) {
if (digitalRead(pin) == LOW) {
delay(50); // Pequeña pausa para evitar falsos positivos por ruido
if (digitalRead(pin) == LOW) { // Doble verificación
while (digitalRead(pin) == LOW); // Espera liberación del botón
return true;
}
}
return false;
}
void registrarPulsacion(String numero, int pin) {
entrada += numero;
Serial.println("Botón " + numero + " presionado.");
tiempoUltimaPulsacion = millis();
}
void verificarClave() {
Serial.println("\nClave ingresada:");
for (char c : entrada) Serial.println(c);
if (entrada == clave) {
activarLedYRele(ledV, true);
Serial.println("Clave correcta. Relé activado.");
delay(5000);
activarLedYRele(ledV, false);
intentos = 0;
} else {
intentos++;
activarLedYRele(ledR, true);
Serial.println("Clave incorrecta.");
delay(2000);
activarLedYRele(ledR, false);
if (intentos >= 3) {
bloqueado = true;
tiempoBloqueo = millis();
Serial.println("Demasiados intentos. Sistema bloqueado por 1 minuto.");
}
}
entrada = "";
}
void activarLedYRele(int led, bool estado) {
digitalWrite(led, estado);
digitalWrite(rele, estado);
}