RTC interface with ESP32 controller

RTC is a computer clock that maintains a track of current time.RTC present in most electronic devices which are needed to keep an accurate time. The notable merit of RTC is it has an arrangement of battery backup SRAM. The RTC counts seconds, minutes, hour, dates, month and year with leap year of absolute data.
Here this example “RTC interface with ESP32” shows how to connect ESP32 with a DS1307 real time clock. It also explains how to create a simple program to configure the time and date of the RTC and to measure it periodically(it read from 10 to 10 seconds and print in serial monitor).
RTC interface with ESP32 controller

Code Snippet

The DS1307 is a low power serial real-time clock. Here the RTC DS1307 is an 8 pin IC and uses an I2C interface to interact with the ESP32. The great advantage of RTC is it requires a little current
(ie, less than 500nA)to active. We have the wire library available to handle the I2C protocol in the ESP32 and using the RtcDS1307 library.

#include <Wire.h>
#include <RtcDS1307.h>

If you are using version 2.0.0 of the library or greater, then you need to declare the object as follows:

RtcDS1307<TwoWire> Rtc(Wire);

In the setup function, the I2C library only starts when calling the wire.begin() the default pins for the I2C in the wire library are pins 21(SDA) and 22(SCL).

 Wire.begin(21,22);

To make things simple and the code cleaner, the RTC library uses another class, called RtcDateTime, which allows us to create objects to hold the date and time information. This is easier to maintain than having to define a different variable to hold all the parameters from seconds to years.

RtcDateTime compiled = RtcDateTime(__DATE__, __TIME__);

To get a current time and date, we call the GetDateTime method on our previously defined RtcDS1307 object (which we named “Rtc”). This method will return a RtcDateTime object, as we used before in the setup function.

    RtcDateTime now = Rtc.GetDateTime();

The RtcDateTime class has a method for getting each of the parameters of date and time. We will use those methods to get them and print them to a string (using the snprintf function).

void printDateTime(const RtcDateTime& dt)
{
    char datestring[20];

    snprintf_P(datestring, 
            countof(datestring),
            PSTR("%02u/%02u/%04u %02u:%02u:%02u"),
            dt.Day(),
            dt.Month(),
            dt.Year(),
            dt.Hour(),
            dt.Minute(),
            dt.Second() );
    Serial.print(datestring);
}

rtc_serial