ESP8266 - RTC

Este tutorial ensina como usar o ESP8266 para ler data e hora de um módulo RTC. Em detalhe, vamos aprender:

Hardware Necessário

1×ESP8266 NodeMCU ESP-12F
1×Alternatively, ESP8266 D1 Mini NodeMCU ESP-12F
1×Alternatively, ESP8266 NodeMCU ESP-12E (Uno-form)
1×Micro USB Cable
1×Alternatively, ESP8266 NodeMCU ESP-12F (SMD-form)
1×Cabo USB Tipo-A para Tipo-C (para PC com USB-A)
1×Cabo USB Tipo-C para Tipo-C (para PC com USB-C)
1×Módulo Relógio de Tempo Real (RTC) DS3231
1×Bateria CR2032
1×Fios Jumper
1×(Recomendado) Placa de Expansão com Bornes de Parafuso para ESP8266

Or you can buy the following kits:

1×DIYables Sensor Kit (18 sensors/displays)
Divulgação: Alguns dos links desta seção são links de afiliado da Amazon. Podemos receber uma comissão pelas compras feitas por meio desses links, sem custo adicional para você. Agradecemos o seu apoio.

Sobre o Módulo Relógio de Tempo Real DS3231

O ESP8266 tem algumas funções relacionadas ao tempo, como millis() e micros(). No entanto, elas não fornecem a data e a hora (segundos, minutos, horas, dia, data, mês e ano). Para obter essas informações, precisamos usar um módulo Relógio de Tempo Real (RTC), como o DS3231 ou o DS1307. O Módulo DS3231 tem maior precisão que o DS1307. Para mais informações, veja DS3231 vs DS1307.

Pinagem do Módulo RTC

O Módulo Relógio de Tempo Real DS3231 tem 10 pinos:

  • 32K: Este pino fornece um relógio de referência estável e preciso.
  • SQW: Este pino produz uma onda quadrada de 1Hz, 4kHz, 8kHz ou 32kHz e pode ser gerenciado por programação. Ele também pode ser usado como interrupção de alarme em várias aplicações dependentes de tempo.
  • SCL: Este é o pino de clock serial da interface I2C.
  • SDA: Este é o pino de dados seriais da interface I2C.
  • VCC: Este pino fornece energia ao módulo. Ele pode ficar entre 3.3V e 5.5V.
  • GND: Este é o pino de terra.

Para a operação normal, são necessários quatro pinos: VCC, GND, SDA e SCL.

pinagem do Módulo Relógio de Tempo Real DS3231

O Módulo DS3231 tem um suporte de bateria que, quando uma bateria CR2032 é inserida, mantém a hora do módulo funcionando mesmo quando a alimentação principal está desligada. Sem a bateria, a informação de hora será perdida se a alimentação principal for desconectada e será necessário reiniciá-la.

Diagrama de Ligação

diagrama de ligação do Relógio de Tempo Real DS3231 com ESP8266 NodeMCU

This image is created using Fritzing. Click to enlarge image

Para mais informações, veja Pinagem do ESP8266 e como alimentar o ESP8266 e outros componentes.

ESP8266 - Módulo RTC DS3231

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

Como Programar para o Módulo RTC DS3231

  • Inclua a biblioteca.
#include <RTClib.h>
  • Crie um objeto RTC:
RTC_DS3231 rtc;
  • Inicie o processo de configuração do RTC.
if (! rtc.begin()) { Serial.println("Couldn't find RTC"); while (1); }
  • Ajuste o RTC para a data e hora do computador de quando o sketch foi compilado, como hora inicial.
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  • Obtém os dados de data e hora do 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 – Como obter data e hora

/* * Este código de ESP8266 NodeMCU foi desenvolvido por pt.newbiely.com * Este código de ESP8266 NodeMCU é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.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 }

Passos Rápidos

Para começar com o ESP8266 na Arduino IDE, siga estes passos:

  • Confira o tutorial como configurar o ambiente para ESP8266 na Arduino IDE se esta for a sua primeira vez usando o ESP8266.
  • Ligue os componentes como mostrado no diagrama.
  • Conecte a placa ESP8266 ao seu computador usando um cabo USB.
  • Abra a Arduino IDE no seu computador.
  • Escolha a placa ESP8266 correta, como (por exemplo, NodeMCU 1.0 (ESP-12E Module)), e a respectiva porta COM.
  • Clique no ícone Libraries na barra esquerda da Arduino IDE.
  • Pesquise por “RTClib” e localize a biblioteca RTC da Adafruit.
  • Pressione o botão Install para instalar a biblioteca RTC.
biblioteca RTC para ESP8266 NodeMCU
  • Copie o código e abra-o com a Arduino IDE.
  • Clique no botão Upload da IDE para enviá-lo ao ESP8266.
  • Abra o Serial Monitor.
  • Verifique a saída no Serial Monitor.
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Nodemcu 1.0 (ESP-12E Module)
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Nodemcu 1.0 (ESP-12E Module)' on 'COM15')
New Line
9600 baud
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
Ln 11, Col 1
Nodemcu 1.0 (ESP-12E Module) on COM15
2

Código ESP8266 – Como criar um agendamento diário

/* * Este código de ESP8266 NodeMCU foi desenvolvido por pt.newbiely.com * Este código de ESP8266 NodeMCU é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.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 – Como criar um agendamento semanal

/* * Este código de ESP8266 NodeMCU foi desenvolvido por pt.newbiely.com * Este código de ESP8266 NodeMCU é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.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 – Como criar um agendamento em uma data específica

/* * Este código de ESP8266 NodeMCU foi desenvolvido por pt.newbiely.com * Este código de ESP8266 NodeMCU é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.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); }

Vídeo

※ NOSSAS MENSAGENS

  • Fique à vontade para compartilhar o link deste tutorial. Porém, por favor, não use nosso conteúdo em outros sites. Investimos muito esforço e tempo para criar este conteúdo, por favor respeite nosso trabalho!