Note

Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.

Why Join?

  • Expert Support: Solve post-sale issues and technical challenges with help from our community and team.

  • Learn & Share: Exchange tips and tutorials to enhance your skills.

  • Exclusive Previews: Get early access to new product announcements and sneak peeks.

  • Special Discounts: Enjoy exclusive discounts on our newest products.

  • Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.

👉 Ready to explore and create with us? Click [here] and join today!

Lesson 16: Real Time Clock Module (DS1302)

In this lesson, you will learn how to set up and use a Real Time Clock (RTC) module with an ESP32 development board. We’ll cover integrating the DS1302 RTC module, understanding its functions, and programming the ESP32 to display the current date and time. You’ll also learn how to handle situations where the RTC has lost its date and time settings and automatically set it to the compile time of your sketch. This project is ideal for those seeking to enhance their comprehension of time-related functions in microcontroller projects.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

Universal Maker Sensor Kit

94

Universal Maker Sensor Kit

You can also buy them separately from the links below.

Component Introduction

Purchase Link

ESP32 & Development Board (ESP32 Board)

BUY

Real Time Clock Module (DS1302)

BUY

Breadboard

BUY

Wiring

../_images/Lesson_16_DS1302_esp32_bb.png

Code

Note

To install the library, use the Arduino Library Manager and search for “Rtc by Makuna” and install it.

Code Analysis

  1. Initialization and library inclusion

    Note

    To install the library, use the Arduino Library Manager and search for “Rtc by Makuna” and install it.

    Here, necessary libraries are included for the DS1302 RTC module.

    #include <ThreeWire.h>
    #include <RtcDS1302.h>
    
  2. Define pins and create RTC instance

    Pins for communication are defined and an instance of the RTC is created.

    const int IO = 27;    // DAT
    const int SCLK = 14;  // CLK
    const int CE = 26;    // RST
    
    ThreeWire myWire(IO, SCLK, CE));
    RtcDS1302<ThreeWire> Rtc(myWire);
    
  3. setup() function

    This function initializes the serial communication and sets up the RTC module. Various checks are made to ensure the RTC is running correctly.

    void setup() {
      Serial.begin(9600);
    
      Serial.print("compiled: ");
      Serial.print(__DATE__);
      Serial.println(__TIME__);
    
      Rtc.Begin();
    
      RtcDateTime compiled = RtcDateTime(__DATE__, __TIME__);
      printDateTime(compiled);
      Serial.println();
    
      if (!Rtc.IsDateTimeValid()) {
        // Common Causes:
        //    1) first time you ran and the device wasn't running yet
        //    2) the battery on the device is low or even missing
    
        Serial.println("RTC lost confidence in the DateTime!");
        Rtc.SetDateTime(compiled);
      }
    
      if (Rtc.GetIsWriteProtected()) {
        Serial.println("RTC was write protected, enabling writing now");
        Rtc.SetIsWriteProtected(false);
      }
    
      if (!Rtc.GetIsRunning()) {
        Serial.println("RTC was not actively running, starting now");
        Rtc.SetIsRunning(true);
      }
    
      RtcDateTime now = Rtc.GetDateTime();
      if (now < compiled) {
        Serial.println("RTC is older than compile time!  (Updating DateTime)");
        Rtc.SetDateTime(compiled);
      } else if (now > compiled) {
        Serial.println("RTC is newer than compile time. (this is expected)");
      } else if (now == compiled) {
        Serial.println("RTC is the same as compile time! (not expected but all is fine)");
      }
    }
    
  4. loop() function

    This function periodically fetches the current date and time from the RTC and prints it on the serial monitor. It also checks if the RTC is still maintaining a valid date and time.

    void loop() {
      RtcDateTime now = Rtc.GetDateTime();
    
      printDateTime(now);
      Serial.println();
    
      if (!now.IsValid()) {
        // Common Causes:
        //    1) the battery on the device is low or even missing and the power line was disconnected
        Serial.println("RTC lost confidence in the DateTime!");
      }
    
      delay(5000);  // five seconds
    }
    
  5. Date and time printing function

    A helper function that takes a RtcDateTime object and prints the formatted date and time to the serial monitor.

    void printDateTime(const RtcDateTime& dt) {
      char datestring[20];
    
      snprintf_P(datestring,
                 countof(datestring),
                 PSTR("%02u/%02u/%04u %02u:%02u:%02u"),
                 dt.Month(),
                 dt.Day(),
                 dt.Year(),
                 dt.Hour(),
                 dt.Minute(),
                 dt.Second());
      Serial.print(datestring);
    }