ESP8266 - Reloj en tiempo real

Este tutorial te enseña cómo usar ESP8266 para leer la fecha y la hora desde el módulo RTC. En detalle, aprenderemos:

Hardware Requerido

1×ESP8266 NodeMCU
1×Cable USB Tipo-A a Tipo-C (para PC USB-A)
1×Cable USB Tipo-C a Tipo-C (para PC USB-C)
1×Módulo Reloj de Tiempo Real (RTC) DS3231
1×Batería CR2032
1×Cables Puente
1×(Recomendado) Placa de Expansión de Terminales de Tornillo para ESP8266
1×(Recomendado) Divisor de Alimentación para ESP8266 Tipo-C

Or you can buy the following kits:

1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
Divulgación: Algunos de los enlaces proporcionados en esta sección son enlaces de afiliado de Amazon. Podemos recibir una comisión por las compras realizadas a través de estos enlaces sin costo adicional para usted. Apreciamos su apoyo.

Acerca del Módulo DS3231 de Reloj en Tiempo Real

El ESP8266 tiene ciertas funciones relacionadas con el tiempo, como millis() y micros(). Sin embargo, no proporcionan la fecha y la hora (segundos, minutos, horas, día, fecha, mes y año). Para obtener esta información, necesitamos usar un módulo de reloj en tiempo real (RTC), como DS3231 o DS1370. El módulo DS3231 tiene mayor precisión que el DS1370. Para obtener más información, por favor vea DS3231 vs DS1307.

El pinout del módulo RTC

El módulo de reloj en tiempo real DS3231 tiene 10 pines:

  • 32K: Este pin proporciona un reloj de referencia estable y preciso.
  • SQW: Este pin produce una onda cuadrada a 1 Hz, 4 kHz, 8 kHz o 32 kHz y puede configurarse mediante programación. También puede utilizarse como una interrupción de alarma en diversas aplicaciones dependientes del tiempo.
  • SCL: Este es el pin de reloj serial para la interfaz I2C.
  • SDA: Este es el pin de datos seriales para la interfaz I2C.
  • VCC: Este pin suministra energía al módulo. Puede estar entre 3,3 V y 5,5 V.
  • GND: Este es el pin de tierra.

Para el funcionamiento normal, se requieren cuatro pines: VCC, GND, SDA y SCL.

Pinout del módulo DS3231 RTC

El módulo DS3231 tiene un soporte para batería que, cuando se inserta una batería CR2032, mantiene la hora del módulo en funcionamiento incluso cuando la alimentación principal está apagada. Sin la batería, la información de la hora se perderá si se desconecta la alimentación principal y deberá restablecerse.

Diagrama de Cableado

Diagrama de cableado ESP8266 NodeMCU para reloj en tiempo real DS3231

This image is created using Fritzing. Click to enlarge image

Para obtener m\u00e1s informaci\u00f3n, consulte Pines del ESP8266 y c\u00f3mo alimentar ESP8266 y otros componentes.

ESP8266 - Módulo RTC DS3231

DS3231 RTC Module ESP8266
Vin 3.3V
GND GND
SDA GPIO4
SCL GPIO5

Cómo Programar para el Módulo RTC DS3231

  • Incluir la biblioteca.
#include <RTClib.h>
  • Crear un objeto RTC:
RTC_DS3231 rtc;
  • Iniciar el proceso de configuración de la RTC.
if (! rtc.begin()) { Serial.println("Couldn't find RTC"); while (1); }
  • Configura el RTC con la fecha y hora de la computadora desde la que se compiló el sketch para la hora inicial.
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  • Obtiene datos de fecha y hora del módulo RTC.
DateTime now = rtc.now(); Serial.print("Date & Time: "); Serial.print(now.year(), DEC); Serial.print('/'); Serial.print(now.month(), DEC); Serial.print('/'); Serial.print(now.day(), DEC); Serial.print(" ("); Serial.print(now.dayOfTheWeek()); Serial.print(") "); Serial.print(now.hour(), DEC); Serial.print(':'); Serial.print(now.minute(), DEC); Serial.print(':'); Serial.println(now.second(), DEC);

Código ESP8266 – Cómo obtener la fecha y la hora

/* * Este código de ESP8266 NodeMCU fue desarrollado por es.newbiely.com * Este código de ESP8266 NodeMCU se proporciona al público sin ninguna restricción. * Para tutoriales completos y diagramas de cableado, visite: * https://es.newbiely.com/tutorials/esp8266/esp8266-rtc */ #include <RTClib.h> RTC_DS3231 rtc; char daysOfTheWeek[7][12] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; void setup () { Serial.begin(9600); // SETUP RTC MODULE if (! rtc.begin()) { Serial.println("Couldn't find RTC"); Serial.flush(); while (1); } // automatically sets the RTC to the date & time on PC this sketch was compiled rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); // manually sets the RTC with an explicit date & time, for example to set // January 21, 2021 at 3am you would call: // rtc.adjust(DateTime(2021, 1, 21, 3, 0, 0)); } void loop () { DateTime now = rtc.now(); Serial.print("Date & Time: "); Serial.print(now.year(), DEC); Serial.print('/'); Serial.print(now.month(), DEC); Serial.print('/'); Serial.print(now.day(), DEC); Serial.print(" ("); Serial.print(daysOfTheWeek[now.dayOfTheWeek()]); Serial.print(") "); Serial.print(now.hour(), DEC); Serial.print(':'); Serial.print(now.minute(), DEC); Serial.print(':'); Serial.println(now.second(), DEC); delay(1000); // delay 1 seconds }

Pasos R\u00e1pidos

Para empezar con ESP8266 en el IDE de Arduino, siga estos pasos:

  • Consulta el tutorial cómo configurar el entorno para ESP8266 en Arduino IDE si es la primera vez que usas ESP8266.
  • Conecta los componentes como se muestra en el diagrama.
  • Conecta la placa ESP8266 a tu computadora con un cable USB.
  • Abre Arduino IDE en tu computadora.
  • Elige la placa ESP8266 correcta, como (p. ej. NodeMCU 1.0 (ESP-12E Module)), y su puerto COM respectivo.
  • Haz clic en el icono Libraries en la barra izquierda del Arduino IDE.
  • Busca “RTClib” y localiza la biblioteca RTC de Adafruit.
  • Presiona el botón Install para instalar la biblioteca RTC.
Biblioteca RTC para ESP8266 NodeMCU
  • Copie el código y ábralo con el IDE de Arduino.
  • Haga clic en el botón Cargar en el IDE para enviarlo al ESP8266.
  • Abra el Monitor Serial.
  • Verifique la salida en el Monitor Serial.
COM6
Send
Date & Time: 2021/10/6 (Wednesday) 11:27:35 Date & Time: 2021/10/6 (Wednesday) 11:27:36 Date & Time: 2021/10/6 (Wednesday) 11:27:37 Date & Time: 2021/10/6 (Wednesday) 11:27:38 Date & Time: 2021/10/6 (Wednesday) 11:27:39 Date & Time: 2021/10/6 (Wednesday) 11:27:40 Date & Time: 2021/10/6 (Wednesday) 11:27:41 Date & Time: 2021/10/6 (Wednesday) 11:27:42 Date & Time: 2021/10/6 (Wednesday) 11:27:43 Date & Time: 2021/10/6 (Wednesday) 11:27:44
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

Código ESP8266 – Cómo hacer un horario diario

/* * Este código de ESP8266 NodeMCU fue desarrollado por es.newbiely.com * Este código de ESP8266 NodeMCU se proporciona al público sin ninguna restricción. * Para tutoriales completos y diagramas de cableado, visite: * https://es.newbiely.com/tutorials/esp8266/esp8266-rtc */ // Date and time functions using a DS3231 RTC connected via I2C and Wire lib #include <RTClib.h> // event from 13:50 to 14:10 uint8_t DAILY_EVENT_START_HH = 13; // event start time: hour uint8_t DAILY_EVENT_START_MM = 50; // event start time: minute uint8_t DAILY_EVENT_END_HH = 14; // event end time: hour uint8_t DAILY_EVENT_END_MM = 10; // event end time: minute RTC_DS3231 rtc; char daysOfTheWeek[7][12] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; void setup () { Serial.begin(9600); // SETUP RTC MODULE if (! rtc.begin()) { Serial.println("Couldn't find RTC"); while (1); } // sets the RTC to the date & time on PC this sketch was compiled rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); // sets the RTC with an explicit date & time, for example to set // January 21, 2021 at 3am you would call: // rtc.adjust(DateTime(2021, 1, 21, 3, 0, 0)); } void loop () { DateTime now = rtc.now(); if (now.hour() >= DAILY_EVENT_START_HH && now.minute() >= DAILY_EVENT_START_MM && now.hour() < DAILY_EVENT_END_HH && now.minute() < DAILY_EVENT_END_MM) { Serial.println("It is on scheduled time"); // TODO: write your code" } else { Serial.println("It is NOT on scheduled time"); } printTime(now); } void printTime(DateTime time) { Serial.print("TIME: "); Serial.print(time.year(), DEC); Serial.print('/'); Serial.print(time.month(), DEC); Serial.print('/'); Serial.print(time.day(), DEC); Serial.print(" ("); Serial.print(daysOfTheWeek[time.dayOfTheWeek()]); Serial.print(") "); Serial.print(time.hour(), DEC); Serial.print(':'); Serial.print(time.minute(), DEC); Serial.print(':'); Serial.println(time.second(), DEC); }

Código ESP8266 – Cómo hacer un horario semanal

/* * Este código de ESP8266 NodeMCU fue desarrollado por es.newbiely.com * Este código de ESP8266 NodeMCU se proporciona al público sin ninguna restricción. * Para tutoriales completos y diagramas de cableado, visite: * https://es.newbiely.com/tutorials/esp8266/esp8266-rtc */ // Date and time functions using a DS3231 RTC connected via I2C and Wire lib #include <RTClib.h> // UNCHANGABLE PARAMATERS #define SUNDAY 0 #define MONDAY 1 #define TUESDAY 2 #define WEDNESDAY 3 #define THURSDAY 4 #define FRIDAY 5 #define SATURDAY 6 // event on Monday, from 13:50 to 14:10 uint8_t WEEKLY_EVENT_DAY = MONDAY; uint8_t WEEKLY_EVENT_START_HH = 13; // event start time: hour uint8_t WEEKLY_EVENT_START_MM = 50; // event start time: minute uint8_t WEEKLY_EVENT_END_HH = 14; // event end time: hour uint8_t WEEKLY_EVENT_END_MM = 10; // event end time: minute RTC_DS3231 rtc; char daysOfTheWeek[7][12] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; void setup () { Serial.begin(9600); // SETUP RTC MODULE if (! rtc.begin()) { Serial.println("Couldn't find RTC"); while (1); } // sets the RTC to the date & time on PC this sketch was compiled rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); // sets the RTC with an explicit date & time, for example to set // January 21, 2021 at 3am you would call: // rtc.adjust(DateTime(2021, 1, 21, 3, 0, 0)); } void loop () { DateTime now = rtc.now(); if (now.dayOfTheWeek() == WEEKLY_EVENT_DAY && now.hour() >= WEEKLY_EVENT_START_HH && now.minute() >= WEEKLY_EVENT_START_MM && now.hour() < WEEKLY_EVENT_END_HH && now.minute() < WEEKLY_EVENT_END_MM) { Serial.println("It is on scheduled time"); // TODO: write your code" } else { Serial.println("It is NOT on scheduled time"); } printTime(now); } void printTime(DateTime time) { Serial.print("TIME: "); Serial.print(time.year(), DEC); Serial.print('/'); Serial.print(time.month(), DEC); Serial.print('/'); Serial.print(time.day(), DEC); Serial.print(" ("); Serial.print(daysOfTheWeek[time.dayOfTheWeek()]); Serial.print(") "); Serial.print(time.hour(), DEC); Serial.print(':'); Serial.print(time.minute(), DEC); Serial.print(':'); Serial.println(time.second(), DEC); }

Código ESP8266 – Cómo programar en una fecha específica

/* * Este código de ESP8266 NodeMCU fue desarrollado por es.newbiely.com * Este código de ESP8266 NodeMCU se proporciona al público sin ninguna restricción. * Para tutoriales completos y diagramas de cableado, visite: * https://es.newbiely.com/tutorials/esp8266/esp8266-rtc */ // Date and time functions using a DS3231 RTC connected via I2C and Wire lib #include <RTClib.h> // UNCHANGABLE PARAMATERS #define SUNDAY 0 #define MONDAY 1 #define TUESDAY 2 #define WEDNESDAY 3 #define THURSDAY 4 #define FRIDAY 5 #define SATURDAY 6 #define JANUARY 1 #define FEBRUARY 2 #define MARCH 3 #define APRIL 4 #define MAY 5 #define JUNE 6 #define JULY 7 #define AUGUST 8 #define SEPTEMBER 9 #define OCTOBER 10 #define NOVEMBER 11 #define DECEMBER 12 // event from 13:50 August 15, 2021 to 14:10 September 29, 2021 DateTime EVENT_START(2021, AUGUST, 15, 13, 50); DateTime EVENT_END(2021, SEPTEMBER, 29, 14, 10); RTC_DS3231 rtc; char daysOfTheWeek[7][12] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; void setup () { Serial.begin(9600); // SETUP RTC MODULE if (! rtc.begin()) { Serial.println("Couldn't find RTC"); Serial.flush(); while (1); } // sets the RTC to the date & time on PC this sketch was compiled rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); // sets the RTC with an explicit date & time, for example to set // January 21, 2021 at 3am you would call: // rtc.adjust(DateTime(2021, 1, 21, 3, 0, 0)); } void loop () { DateTime now = rtc.now(); if (now.secondstime() >= EVENT_START.secondstime() && now.secondstime() < EVENT_END.secondstime()) { Serial.println("It is on scheduled time"); // TODO: write your code" } else { Serial.println("It is NOT on scheduled time"); } printTime(now); } void printTime(DateTime time) { Serial.print("TIME: "); Serial.print(time.year(), DEC); Serial.print('/'); Serial.print(time.month(), DEC); Serial.print('/'); Serial.print(time.day(), DEC); Serial.print(" ("); Serial.print(daysOfTheWeek[time.dayOfTheWeek()]); Serial.print(") "); Serial.print(time.hour(), DEC); Serial.print(':'); Serial.print(time.minute(), DEC); Serial.print(':'); Serial.println(time.second(), DEC); }

Video Tutorial

Estamos considerando crear tutoriales en video. Si considera que los tutoriales en video son importantes, suscríbase a nuestro canal de YouTube para motivarnos a crear los videos.

※ NUESTROS MENSAJES

  • No dude en compartir el enlace de este tutorial. Sin embargo, por favor no use nuestro contenido en otros sitios web. Hemos invertido mucho esfuerzo y tiempo en crear el contenido, ¡por favor respete nuestro trabajo!