57. User Define RTC Function For Time Reading

Let's understand the RTC first,

  • A Real-Time Clock (RTC) monitors time and maintains a calendar.
  • We are going to use the DS1307 RTC module, which works on the I2C protocol at 100KHz speed with a 7-bit slave address of 0x68, typically.
RTC-DS1307-Module

                                                                    RTC Module(DS1307)

 

Pinout of DS1037 RTC module

Pinout-of-RTC-DS1307-Module

 

  • The breakout board of this module has pins on both sides for ease of use. We will only use the 5 pins shown on the left side of the image.
  • When powered ON for the first time, we might read random date and time values from the RTC module. So we must first program it with the current date and time.
  • The data stored in the RTC module is in BCD format.
  • Shown in the image below are the contents of the Timekeeper registers. There are eight registers in total. Once we set their values, they will keep updating themselves. 

 

Timekeeper-Register-DS1307

 

Datasheet: EW Skill Attachment DS1307-3421066 datasheet 

 To know more about the DS1307 module, please read the  RTC (Real Time Clock ) DS1307 Module 

Now we will interface this module with a microcontroller

Interfacing Steps

  1. Hardware Connections
    • Connect the SDA and SCL pins of DS1307 to the corresponding I2C pins on the microcontroller.
    • Add 4.7kΩ pull-up resistors between SDA/SCL and VCC.
    • Also, we can use internal pull-up resistors.
    • Connect VCC 3.3V or 5V, depending on the MCU voltage level, and GND appropriately.

Note: When interfacing I²C devices operating at different voltages (e.g., 5 V ↔ 3.3 V), always use a voltage level shifter to ensure safe logic levels and reliable communication.

  1. I2C Initialization
    • Configure the I2C peripheral of the microcontroller for 100 kHz Standard Mode.
    • Set the microcontroller as an I2C Master and DS1307 as an I2C Slave (0x68).
  2. Reading Time from DS1307
    • Send the starting register address (0x00 for seconds).
    • Read 3 consecutive bytes (Seconds, Minutes, Hours).
    • Convert the BCD values to decimal.
  3. Displaying Time on Serial Terminal
    • Format the time as HH:MM:SS.
    • Print via UART to PuTTY/Arduino IDE.

 

So, by connecting and configuring the master and slave devices and the I2C communication, we can implement the task.

Below are the solutions to the given task using different microcontrollers

  1. STM32
  2. ESP32
  3. Arduino UNO

Submit Your Solution

Note: Once submitted, your solution goes public, helping others learn from your approach!