const int LED_VERDE = 5;
const int LED_AMARILLO = 6;
const int LED_ROJO = 7;
const int BOTON_MARCHA = 2;
const int BOTON_FALLA = 3;
const int RELE = 8;
// Estados de la máquina
const int READY = 0;
const int RUNNING = 1;
const int FAULT = 2;
int estado = READY;
// Estados anteriores de los botones
bool marchaAnterior = HIGH;
bool fallaAnterior = HIGH;
// Diagnóstico serial
unsigned long tiempoDiagnostico = 0;
const unsigned long INTERVALO = 500;
// Función para controlar la torre luminosa
void mostrar(int estadoActual) {
digitalWrite(LED_VERDE, estadoActual == READY ? HIGH : LOW);
digitalWrite(LED_AMARILLO, estadoActual == RUNNING ? HIGH : LOW);
digitalWrite(LED_ROJO, estadoActual == FAULT ? HIGH : LOW);
// El relé funciona únicamente en RUNNING
digitalWrite(RELE, estadoActual == RUNNING ? HIGH : LOW);
}
// Función para mostrar el estado por serial
void diagnostico(int estadoActual) {
if (estadoActual == READY) {
Serial.println("TOWER:READY");
}
else if (estadoActual == RUNNING) {
Serial.println("TOWER:RUNNING");
}
else if (estadoActual == FAULT) {
Serial.println("TOWER:FAULT");
}
}
void setup() {
Serial.begin(9600);
pinMode(LED_VERDE, OUTPUT);
pinMode(LED_AMARILLO, OUTPUT);
pinMode(LED_ROJO, OUTPUT);
pinMode(BOTON_MARCHA, INPUT_PULLUP);
pinMode(BOTON_FALLA, INPUT_PULLUP);
pinMode(RELE, OUTPUT);
estado = READY;
mostrar(estado);
Serial.println("TOWER:READY");
}
void loop() {
unsigned long ahora = millis();
// Leer botones
bool marchaActual = digitalRead(BOTON_MARCHA);
bool fallaActual = digitalRead(BOTON_FALLA);
// Detectar pulsación de falla
if (fallaAnterior == HIGH && fallaActual == LOW) {
estado = FAULT;
mostrar(estado);
diagnostico(estado);
}
// Detectar marcha solamente si no existe una falla
else if (estado != FAULT &&
marchaAnterior == HIGH &&
marchaActual == LOW) {
estado = RUNNING;
mostrar(estado);
diagnostico(estado);
}
// Volver de FAULT a READY al presionar marcha
else if (estado == FAULT &&
marchaAnterior == HIGH &&
marchaActual == LOW) {
estado = READY;
mostrar(estado);
diagnostico(estado);
}
marchaAnterior = marchaActual;
fallaAnterior = fallaActual;
// Diagnóstico periódico
if (ahora - tiempoDiagnostico >= INTERVALO) {
tiempoDiagnostico = ahora;
if (estado == READY) {
Serial.println("TOWER:READY");
}
else if (estado == RUNNING) {
Serial.println("TOWER:RUNNING");
}
else {
Serial.println("TOWER:FAULT");
}
}
}