Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ThreeWire.h>
- #include <RtcDS1302.h>
- // Configuración de pines para DS1302 (DAT, CLK, RST)
- ThreeWire myWire(7, 6, 5); // DAT=pin7, CLK=pin6, RST=pin5
- RtcDS1302<ThreeWire> Rtc(myWire);
- // Configuración del relé y botón
- const int RELE_PIN = 4;
- const int BOTON_PIN = 2;
- // Horarios de control (formato 24 horas)
- const int HORA_ENCENDER = 11; // HORA DE ENCENDIDO DE LA LAMPARA
- const int HORA_APAGAR = 18; // HORA DE APAGADO DE LA LAMPARA
- // Estados del sistema
- bool estadoRele = false; // Estado actual del relé (true=encendido, false=apagado)
- // Variables para control del botón - MEJORADAS
- volatile bool botonPresionado = false;
- volatile unsigned long ultimoTiempoBoton = 0;
- const unsigned long tiempoDebounce = 750; // Aumentado de 200ms a 500ms
- unsigned long tiempoUltimaAccion = 0; // Nueva variable para evitar acciones muy seguidas
- const unsigned long tiempoMinimoEntreAcciones = 2000; // 2 segundos mínimo entre acciones
- // Variables para control de tiempo
- int ultimaHoraVerificada = -1;
- // Variables para estado del botón - NUEVAS
- bool estadoBotonAnterior = HIGH;
- bool botonEstable = HIGH;
- unsigned long tiempoUltimoCambioBoton = 0;
- void setup() {
- Serial.begin(9600);
- Serial.println("=== CONTROL DE RELE - BOTON + HORARIOS (CORREGIDO) ===");
- // Configurar pin del relé (lógica normal: HIGH=encendido, LOW=apagado)
- pinMode(RELE_PIN, OUTPUT);
- digitalWrite(RELE_PIN, LOW); // Empezar apagado
- estadoRele = false;
- // Configurar pin del botón con pull-up interno
- pinMode(BOTON_PIN, INPUT_PULLUP);
- // CAMBIO: No usar interrupción, usar lectura directa para mejor control
- // attachInterrupt(digitalPinToInterrupt(BOTON_PIN), manejarInterrupcionBoton, FALLING);
- // Inicializar RTC
- Rtc.Begin();
- delay(100);
- if (!Rtc.GetIsRunning()) {
- Serial.println("Iniciando RTC...");
- Rtc.SetIsRunning(true);
- }
- if (Rtc.GetIsWriteProtected()) {
- Serial.println("Deshabilitando protección de escritura...");
- Rtc.SetIsWriteProtected(false);
- }
- // CONFIGURACIÓN DE HORA ACTUAL - SOLO LA PRIMERA VEZ
- // ⚠️ DESCOMENTA Y AJUSTA LA HORA, LUEGO COMENTA OTRA VEZ ⚠️
- //Serial.println("Configurando hora actual...");
- //RtcDateTime newTime = RtcDateTime(2025, 9, 21, 18, 52, 0); // Año, Mes, Día, Hora, Minuto, Segundo
- //Rtc.SetDateTime(newTime);
- //Serial.println("Hora configurada correctamente");
- Serial.println("Sistema iniciado");
- Serial.println("LOGICA: HIGH=ENCENDIDO, LOW=APAGADO");
- Serial.println("BOTON: Cambia estado con debounce mejorado");
- Serial.println("HORARIOS: 11:00 AM = ON, 6:00 PM = OFF");
- Serial.println("PROTECCION: 2 segundos mínimo entre acciones");
- Serial.println("========================");
- // Inicializar tiempo de última acción
- tiempoUltimaAccion = millis();
- }
- void loop() {
- // Leer hora actual del RTC
- RtcDateTime now = Rtc.GetDateTime();
- if (!now.IsValid()) {
- Serial.println("ERROR: No se puede leer el RTC");
- digitalWrite(RELE_PIN, LOW); // Apagar por seguridad
- estadoRele = false;
- delay(5000);
- return;
- }
- // PRIMERO: Verificar horarios automáticos
- verificarHorarioAutomatico(now);
- // SEGUNDO: Procesar botón con nuevo método mejorado
- procesarBotonMejorado();
- // Mostrar estado cada minuto
- mostrarEstado(now);
- delay(50); // Reducido para mejor respuesta del botón
- }
- void procesarBotonMejorado() {
- bool estadoBotonActual = digitalRead(BOTON_PIN);
- unsigned long tiempoActual = millis();
- // Detectar cambio de estado del botón
- if (estadoBotonActual != estadoBotonAnterior) {
- tiempoUltimoCambioBoton = tiempoActual;
- estadoBotonAnterior = estadoBotonActual;
- }
- // Verificar si el botón está estable después del debounce
- if ((tiempoActual - tiempoUltimoCambioBoton) > tiempoDebounce) {
- // Si el estado estable cambió (de HIGH a LOW = pulsación)
- if (botonEstable == HIGH && estadoBotonActual == LOW) {
- // Verificar que haya pasado suficiente tiempo desde la última acción
- if ((tiempoActual - tiempoUltimaAccion) > tiempoMinimoEntreAcciones) {
- // Procesar la pulsación del botón
- estadoRele = !estadoRele;
- actualizarRele();
- tiempoUltimaAccion = tiempoActual;
- Serial.print("BOTON PRESIONADO - Relé ahora: ");
- Serial.println(estadoRele ? "ENCENDIDO" : "APAGADO");
- } else {
- Serial.println("BOTON IGNORADO - Muy pronto después de última acción");
- }
- }
- botonEstable = estadoBotonActual;
- }
- }
- void verificarHorarioAutomatico(RtcDateTime now) {
- int horaActual = now.Hour();
- unsigned long tiempoActual = millis();
- // Solo verificar cuando cambia la hora
- if (horaActual != ultimaHoraVerificada) {
- ultimaHoraVerificada = horaActual;
- // Verificar que haya pasado suficiente tiempo desde la última acción
- if ((tiempoActual - tiempoUltimaAccion) > tiempoMinimoEntreAcciones) {
- // A las 12:00 PM - SIEMPRE encender
- if (horaActual == HORA_ENCENDER) {
- estadoRele = true;
- actualizarRele();
- tiempoUltimaAccion = tiempoActual;
- Serial.println("*** HORARIO 12:00 PM: FORZADO A ENCENDIDO ***");
- }
- // A las 6:00 PM - SIEMPRE apagar
- else if (horaActual == HORA_APAGAR) {
- estadoRele = false;
- actualizarRele();
- tiempoUltimaAccion = tiempoActual;
- Serial.println("*** HORARIO 6:00 PM: FORZADO A APAGADO ***");
- }
- }
- }
- }
- void actualizarRele() {
- // Actualizar físicamente el relé con un pequeño delay para estabilidad
- digitalWrite(RELE_PIN, estadoRele ? HIGH : LOW);
- delay(10); // Pequeño delay para estabilizar la señal
- // Verificación adicional
- bool estadoFisico = digitalRead(RELE_PIN);
- if (estadoFisico != estadoRele) {
- Serial.println("WARNING: Estado físico no coincide, reintentando...");
- delay(50);
- digitalWrite(RELE_PIN, estadoRele ? HIGH : LOW);
- }
- }
- void mostrarEstado(RtcDateTime now) {
- static int ultimoMinutoMostrado = -1;
- if (now.Minute() != ultimoMinutoMostrado) {
- ultimoMinutoMostrado = now.Minute();
- Serial.print("Hora: ");
- if (now.Hour() < 10) Serial.print("0");
- Serial.print(now.Hour());
- Serial.print(":");
- if (now.Minute() < 10) Serial.print("0");
- Serial.print(now.Minute());
- Serial.print(" | Relé: ");
- Serial.print(estadoRele ? "ON" : "OFF");
- Serial.print(" | Pin: ");
- Serial.print(digitalRead(RELE_PIN) ? "HIGH" : "LOW");
- Serial.print(" | Botón: ");
- Serial.println(digitalRead(BOTON_PIN) ? "HIGH" : "LOW");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment