ESP8266 - Módulo RTC DS1307

Este tutorial ensina como usar o ESP8266 para ler data e hora de um módulo RTC DS1307. 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) DS1307
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 DS1307

O ESP8266 tem algumas funções relacionadas ao tempo, por exemplo millis() e micros(). No entanto, elas não conseguem fornecer a data e a hora (segundos, minutos, horas, dia, data, mês e ano). Para obter data e hora, deve-se 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 DS1307

O Módulo Relógio de Tempo Real DS1307 tem 12 pinos, mas para uso normal ele requer 4 pinos: VCC, GND, SDA e SCL.

  • O pino SCL: é um pino de clock serial da interface I2C.
  • O pino SDA: é um pino de dados seriais da interface I2C.
  • O pino VCC: fornece energia ao módulo. Ele pode variar de 3.3V a 5.5V.
  • O pino GND: é o pino de terra.
pinagem do Módulo Relógio de Tempo Real DS1307

O Módulo DS1307 tem um suporte de bateria que, quando uma bateria CR2032 é inserida, mantém a hora no módulo 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 DS1307 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 DS1307

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

Como Programar para o Módulo RTC DS1307

  • Inclua a biblioteca.
#include <RTClib.h>
  • Crie um objeto RTC:
RTC_DS1307 rtc;
  • Inicie o Relógio de Tempo Real (RTC).
if (! rtc.begin()) { Serial.println("Couldn't find RTC"); while (1); }
  • Ajuste o Relógio de Tempo Real (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-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 }

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.
  • Procure por “RTClib” e localize a biblioteca RTC da Adafruit.
  • Pressione o botão Install para adicionar a biblioteca RTC.
biblioteca RTC para ESP8266 NodeMCU
  • Copie o código e abra-o na Arduino IDE.
  • Clique no botão Upload da Arduino IDE para compilar e fazer upload do código para o ESP8266.
  • Abra o Serial Monitor.
  • Confira o resultado 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) 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
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-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 – 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-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 – 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-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); }

Vídeo

Tutoriais Relacionados

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