#include <TimerOne.h>
#define LUZ_ROJA_PIN 2
#define LUZ_VERDE_PIN 3
#define SIRENA_PIN 4
#define SENSOR_BOTON_PIN 5 // Pulsador de sensor
#define REINICIAR_BOTON_PIN 6
#define MOTOR_BOTON_PIN 7 // Pulsador para encender/apagar el motor
int contador_presiones = 0;
int tiempo_presion = 0;
int estado_motor = 0; // 0: apagado, 1: encendido
int temporizador_expirado = 0;
int estado_anterior_sensor = HIGH;
int estado_anterior_reiniciar = HIGH;
int estado_anterior_motor = HIGH;
void setup() {
pinMode(LUZ_ROJA_PIN, OUTPUT);
pinMode(LUZ_VERDE_PIN, OUTPUT);
pinMode(SIRENA_PIN, OUTPUT);
pinMode(SENSOR_BOTON_PIN, INPUT_PULLUP);
pinMode(REINICIAR_BOTON_PIN, INPUT_PULLUP);
pinMode(MOTOR_BOTON_PIN, INPUT_PULLUP);
Timer1.initialize(1000); // Inicializa el timer 1 con una cuenta de 1 segundo (1,000,000 microsegundos)
Timer1.attachInterrupt(interrupcionTimer); // Activa la interrupción y la asocia a interrupcionTimer
// Enciende la luz roja al inicio
digitalWrite(LUZ_ROJA_PIN, HIGH);
}
void interrupcionTimer() {
if (estado_motor == 1) {
tiempo_presion++;
if (tiempo_presion >= 120) {
temporizador_expirado = 1;
}
}
}
void loop() {
// Manejo del botón del motor
int estado_motor_boton = digitalRead(MOTOR_BOTON_PIN);
if (estado_motor_boton == LOW && estado_anterior_motor == HIGH) {
estado_motor = !estado_motor; // Alterna el estado del motor
if (estado_motor == 1) {
tiempo_presion = 0;
temporizador_expirado = 0;
contador_presiones = 0;
digitalWrite(LUZ_ROJA_PIN, HIGH);
digitalWrite(LUZ_VERDE_PIN, LOW);
}
}
estado_anterior_motor = estado_motor_boton;
// Solo ejecuta el resto del código si el motor está encendido
if (estado_motor == 1) {
// Manejo del pulsador del sensor
int estado_sensor_boton = digitalRead(SENSOR_BOTON_PIN);
if (estado_sensor_boton == LOW && estado_anterior_sensor == HIGH) {
contador_presiones++;
if (contador_presiones >= 8) {
digitalWrite(LUZ_ROJA_PIN, LOW); // Apaga la luz roja
digitalWrite(LUZ_VERDE_PIN, HIGH); // Enciende la luz verde
}
}
estado_anterior_sensor = estado_sensor_boton;
// Si el temporizador ha expirado y la presión es insuficiente
if (temporizador_expirado && contador_presiones < 8) {
digitalWrite(SIRENA_PIN, HIGH); // Enciende la sirena
} else {
digitalWrite(SIRENA_PIN, LOW); // Apaga la sirena
}
// Verifica si el botón de reinicio está presionado
int estado_reiniciar_boton = digitalRead(REINICIAR_BOTON_PIN);
if (estado_reiniciar_boton == LOW && estado_anterior_reiniciar == HIGH) {
temporizador_expirado = 0;
contador_presiones = 0;
tiempo_presion = 0;
digitalWrite(LUZ_ROJA_PIN, HIGH); // Enciende la luz roja
digitalWrite(LUZ_VERDE_PIN, LOW); // Apaga la luz verde
digitalWrite(SIRENA_PIN, LOW); // Apaga la sirena
}
estado_anterior_reiniciar = estado_reiniciar_boton;
}
}