Arduino Nano - Reloj de Tiempo Real

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

Hardware Requerido

1×Official Arduino Nano
1×Alternatively, DIYables ATMEGA328P Nano Development Board
1×Cable USB A a Mini-B
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 Arduino Nano
1×(Recomendado) Placa de Expansión Breakout para Arduino Nano
1×(Recomendado) Divisor de Alimentación para Arduino Nano

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

Arduino Nano ofrece algunas funciones relacionadas con el tiempo, como millis() y micros(). Sin embargo, estas no proporcionan la fecha y la hora (segundos, minutos, horas, día, fecha, mes y año). Para obtener esta información, debemos usar un módulo Reloj de Tiempo Real (RTC), como el DS3231 o el DS1370. El módulo DS3231 tiene mayor precisión que el DS1370. Para más información, consulte DS3231 vs DS1307.

Disposición de pines del módulo RTC

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

  • 32K: produce un reloj de referencia estable en temperatura y preciso.
  • SQW: emite una onda cuadrada a 1 Hz, 4 kHz, 8 kHz o 32 kHz, que puede gestionarse programáticamente. Esto también puede usarse como disparador de alarma en muchos proyectos que dependen del tiempo.
  • SCL: es el pin de reloj serial para la interfaz I2C.
  • SDA: es el pin de datos serial para la interfaz I2C.
  • VCC: suministra energía al módulo, con un rango de voltaje de 3.3 V a 5.5 V.
  • GND: es el pin de tierra.

Para uso regular, se requieren cuatro pines: VCC, GND, SDA y SCL.

Pinout del módulo DS3231 de reloj en tiempo real

El módulo DS3231 tiene un portabatería, que, cuando se inserta una batería CR2032, mantendrá la hora en el módulo incluso cuando se desconecte la alimentación principal. Si no se inserta ninguna batería, la información de la hora se perderá si se desconecta la alimentación principal y deberá volver a configurarse.

Diagrama de Cableado

Diagrama de cableado de Arduino Nano para el reloj en tiempo real DS3231

This image is created using Fritzing. Click to enlarge image

Ver La mejor forma de alimentar Arduino Nano y otros componentes.

Arduino Nano - Módulo DS3231 RTC

DS3231 RTC Module Arduino Nano
Vin 3.3V
GND GND
SDA A4
SCL A5

Cómo programar para el módulo RTC DS3231

  • Incorpora la biblioteca:
#include <RTClib.h>
  • Crear un objeto RTC:
RTC_DS3231 rtc;
  • Configurar el reloj en tiempo real (RTC)
if (! rtc.begin()) { Serial.println("Couldn't find RTC"); while (1); }
  • Configura el RTC con la fecha y hora de la PC cuando el sketch se compiló 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 de Arduino Nano – Cómo obtener la fecha y la hora

/* * Este código de Arduino Nano fue desarrollado por es.newbiely.com * Este código de Arduino Nano se proporciona al público sin ninguna restricción. * Para tutoriales completos y diagramas de cableado, visite: * https://es.newbiely.com/tutorials/arduino-nano/arduino-nano-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

  • Haz clic en el icono de Bibliotecas en la barra izquierda del IDE de Arduino.
  • Busca “RTClib” y localiza la biblioteca RTC de Adafruit.
  • Haz clic en el botón Instalar para añadir la biblioteca RTC.
Biblioteca RTC para Arduino Nano
  • Copia el código y ábrelo con el Arduino IDE.
  • Haz clic en el botón Subir en el Arduino IDE para compilar y subir el código al Arduino Nano.
  • Abre el Monitor de serie.
  • Verifica el resultado en el Monitor de serie.
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 de Arduino Nano – Cómo hacer un horario diario

/* * Este código de Arduino Nano fue desarrollado por es.newbiely.com * Este código de Arduino Nano se proporciona al público sin ninguna restricción. * Para tutoriales completos y diagramas de cableado, visite: * https://es.newbiely.com/tutorials/arduino-nano/arduino-nano-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 de Arduino Nano – Cómo hacer un horario semanal

/* * Este código de Arduino Nano fue desarrollado por es.newbiely.com * Este código de Arduino Nano se proporciona al público sin ninguna restricción. * Para tutoriales completos y diagramas de cableado, visite: * https://es.newbiely.com/tutorials/arduino-nano/arduino-nano-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 de Arduino Nano – Cómo programar una tarea para una fecha específica

/* * Este código de Arduino Nano fue desarrollado por es.newbiely.com * Este código de Arduino Nano se proporciona al público sin ninguna restricción. * Para tutoriales completos y diagramas de cableado, visite: * https://es.newbiely.com/tutorials/arduino-nano/arduino-nano-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!