A key element in many Arduino projects is time management. Whether to create an alarm clock, a data logger, or any other system requiring precise time management, the use of an RTC (Real Time Clock) module proves to be the perfect solution.
In this tutorial, we will learn about the RTC module for ESP32 and see how it can optimize the accuracy and reliability of your projects.
Here is the diagram associated with the project:
Read time from clock module
To use the DS1307 clock module, you will need to install the RTClib library in Arduino IDE. To do this, click on Library Manager then RTClib:
#include <Wire.h>
#include <RTClib.h>// Create an instance of the RTC_DS1307 objectRTC_DS1307 rtc;voidsetup(){// Initialize serial communication for displaying valuesSerial.begin(115200);// Initialize I2C communication with specific pinsWire.begin(21,22);//SDA on GPIO21, SCL on GPIO22// Check if the DS1307 is connectedif(!rtc.begin()){Serial.println("Unable to find an RTC DS1307!");while(1);}// Check if the RTC watch is configured correctlyif(!rtc.isrunning()){Serial.println("RTC is not running, it will be configured.");
rtc.adjust(DateTime(F(__DATE__),F(__TIME__)));// Automatic setting to code compilation date and time}}voidloop(){// Read time and date from DS1307DateTime now = rtc.now();// Afficher les valeurs sur le moniteur sérieSerial.print("Current date and 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.hour(),DEC);Serial.print(':');Serial.print(now.minute(),DEC);Serial.print(':');Serial.print(now.second(),DEC);Serial.println();// Wait a second before the next readingdelay(1000);}