ESP8266 - Módulo RTC DS1307

Este tutorial te enseña cómo usar el ESP8266 para leer la fecha y la hora desde el módulo RTC DS1307. 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) DS1307
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 DS1307 de Reloj en Tiempo Real

ESP8266 tiene ciertas funciones relacionadas con el tiempo, por ejemplo millis(), micros(). Sin embargo, estas no pueden proporcionar la fecha y la hora (segundos, minutos, horas, día, fecha, mes y año). Para obtener la fecha y la hora, se debe usar un módulo de Reloj en Tiempo Real (RTC) como DS3231 o DS1370. El módulo DS3231 tiene una mayor precisión que el DS1370. Para obtener más información, consulte DS3231 vs DS1307.

Diagrama de pines del módulo DS1307 RTC

El módulo DS1307 de reloj en tiempo real tiene 12 pines, pero para uso normal requiere 4 pines: VCC, GND, SDA y SCL.

  • El pin SCL: es un pin de reloj serial para la interfaz I2C.
  • El pin SDA: es un pin de datos seriales para la interfaz I2C.
  • El pin VCC: suministra energía al módulo. Puede ir desde 3.3V hasta 5.5V.
  • El pin GND: es el pin de tierra.
Pinout del módulo DS1307 de reloj en tiempo real

El módulo DS1307 tiene un soporte para la batería que, al insertar una batería CR2032, mantiene la hora en el módulo 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 será necesario restablecerla.

Diagrama de Cableado

Diagrama de cableado de ESP8266 NodeMCU para reloj en tiempo real DS1307

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 DS1307 RTC

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

Cómo programar para el módulo RTC DS1307

  • Incluir la biblioteca.
#include <RTClib.h>
  • Crear un objeto RTC:
RTC_DS1307 rtc;
  • Iniciar el reloj en tiempo real (RTC).
if (! rtc.begin()) { Serial.println("Couldn't find RTC"); while (1); }
  • Configurar el Reloj de Tiempo Real (RTC) a la fecha y hora de la computadora en el momento en que se compiló el sketch por primera vez.
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-ds1307-rtc-module */ #include <RTClib.h> RTC_DS1307 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, sigue 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 usando un cable USB.
  • Abre el Arduino IDE en tu computadora.
  • Selecciona la placa ESP8266 correcta, como (p. ej. NodeMCU 1.0 (ESP-12E Module)), y su puerto COM correspondiente.
  • Haz clic en el icono Bibliotecas en la barra izquierda del Arduino IDE.
  • Busca “RTClib” y localiza la biblioteca RTC de Adafruit.
  • Presiona el botón Instalar para agregar la biblioteca RTC.
Biblioteca RTC para ESP8266 NodeMCU
  • Copia el código y ábrelo en el IDE de Arduino.
  • Haz clic en el botón Subir en el IDE de Arduino para compilar y subir el código al ESP8266.
  • Abre el Monitor serie.
  • Consulta el resultado en el Monitor serie.
COM6
Send
Date & Time: 2021/10/6 (Wednesday) 9:9:35 Date & Time: 2021/10/6 (Wednesday) 9:9:36 Date & Time: 2021/10/6 (Wednesday) 9:9:37 Date & Time: 2021/10/6 (Wednesday) 9:9:38 Date & Time: 2021/10/6 (Wednesday) 9:9:39 Date & Time: 2021/10/6 (Wednesday) 9:9:40 Date & Time: 2021/10/6 (Wednesday) 9:9:41 Date & Time: 2021/10/6 (Wednesday) 9:9:42 Date & Time: 2021/10/6 (Wednesday) 9:9:43 Date & Time: 2021/10/6 (Wednesday) 9:9: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-ds1307-rtc-module */ // Date and time functions using a DS1307 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_DS1307 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-ds1307-rtc-module */ // Date and time functions using a DS1307 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_DS1307 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 para 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-ds1307-rtc-module */ // Date and time functions using a DS1307 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_DS1307 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.

Tutoriales Relacionados

※ 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!