ESP32 DS1302 Real-Time Clock (RTC)
The DS1302 is a cost-effective real-time clock module designed for accurate timekeeping. It operates on a 3-wire serial protocol and supports dual power supplies with a programmable trickle charger, making it suitable for embedded systems, IoT devices, and battery-backed applications.
Jump to Code Examples
Quick Links
DS1302 Price
About DS1302 Real-Time Clock (RTC)
The DS1302 is a real-time clock (RTC) chip capable of maintaining seconds, minutes, hours, day, date, month, and year with leap year compensation up to the year 2100. It features a 3-wire serial interface for communication and includes 31 bytes of static RAM for general-purpose data storage. The DS1302 supports dual power supplies with a trickle charger, making it ideal for low-power, time-sensitive applications.DS1302 Sensor Technical Specifications
Below you can see the DS1302 Real-Time Clock (RTC) Technical Specifications. The sensor is compatible with the ESP32, operating within a voltage range suitable for microcontrollers. For precise details about its features, specifications, and usage, refer to the sensor’s datasheet.
- Protocol: 3-wire serial
- Timekeeping Range: Seconds to Year (up to 2100)
- Power Supply Voltage: 2.0V to 5.5V
- Backup Battery Voltage: 2.0V to 5.5V
- Power Consumption: <300 nA at 2.5V (battery backup mode)
- Interface: 3-wire serial
- Clock Accuracy: Determined by external crystal
- Data Storage: 31 bytes of static RAM
- Operating Temperature: 0°C to +70°C (Commercial), -40°C to +85°C (Industrial)
DS1302 Sensor Pinout
Below you can see the pinout for the DS1302 Real-Time Clock (RTC). The VCC
pin is used to supply power to the sensor, and it typically requires 3.3V or 5V (refer to the datasheet for specific voltage requirements). The GND
pin is the ground connection and must be connected to the ground of your ESP32!
The DS1302 pinout is as follows:
- VCC1: Primary power supply input.
- VCC2: Backup power supply input.
- SCLK: Serial clock input for communication.
- I/O: Data input/output pin.
- RST: Reset input to enable communication.
- GND: Ground connection.
- X1: Connection for 32.768 kHz crystal oscillator.
- X2: Connection for 32.768 kHz crystal oscillator.
DS1302 Wiring with ESP32
Below you can see the wiring for the DS1302 Real-Time Clock (RTC) with the ESP32. Connect the VCC pin of the sensor to the 3.3V pin on the ESP32 or external power supply for power and the GND pin of the sensor to the GND pin of the ESP32. Depending on the communication protocol of the sensor (e.g., I2C, SPI, UART, or analog), connect the appropriate data and clock or signal pins to compatible GPIO pins on the ESP32, as shown below in the wiring diagram.
VCC1
to a 5V power supply, VCC2
to a backup battery or capacitor, GND
to ground, SCLK
to a GPIO pin for serial clock, I/O
to a GPIO pin for data communication, and RST
to another GPIO pin for enabling the chip. Ensure proper initialization in the microcontroller firmware.Code Examples
Below you can find code examples of DS1302 Real-Time Clock (RTC) with ESP32 in several frameworks:
If you encounter issues while using the DS1302 Real-Time Clock (RTC), check the Common Issues Troubleshooting Guide.
ESP32 DS1302 Arduino IDE Code Example
Fill in your main
Arduino IDE sketch file with the following code to use the DS1302 Real-Time Clock (RTC):
#include <DS1302.h>
DS1302 rtc(19, 21, 22); // RST, I/O, SCLK
void setup() {
Serial.begin(9600);
rtc.halt(false);
rtc.writeProtect(false);
rtc.setDateTime(2023, 12, 4, 14, 30, 0); // Set initial date/time: YYYY, MM, DD, HH, MM, SS
}
void loop() {
DS1302::DateTime now = rtc.getDateTime();
Serial.print("Time: ");
Serial.print(now.hour);
Serial.print(":");
Serial.print(now.minute);
Serial.print(":");
Serial.println(now.second);
Serial.print("Date: ");
Serial.print(now.year);
Serial.print("/");
Serial.print(now.month);
Serial.print("/");
Serial.println(now.day);
delay(1000);
}
This Arduino sketch demonstrates how to use the DS1302 RTC module for timekeeping with updated pins (RST: GPIO19, DAT: GPIO21, CLK: GPIO22). The DS1302
library simplifies communication with the RTC. The setDateTime()
function initializes the RTC with a specific date and time. In the loop()
, the current date and time are fetched and displayed on the Serial Monitor.
Connect your ESP32 to your computer via a USB cable, Ensure the correct Board and Port are selected under Tools, Click the "Upload" button in the Arduino IDE to compile and upload the code to your ESP32.
ESP32 DS1302 ESP-IDF Code ExampleExample in Espressif IoT Framework (ESP-IDF)
If you're using ESP-IDF to work with the DS1302 Real-Time Clock (RTC), here's how you can set it up and read data from the sensor. Fill in this code in the main
ESP-IDF file:
#include <stdio.h>
#include "driver/gpio.h"
#include "ds1302.h"
void app_main(void) {
ds1302_config_t config = {
.rst_pin = GPIO_NUM_19,
.io_pin = GPIO_NUM_21,
.sclk_pin = GPIO_NUM_22
};
ds1302_init(&config);
ds1302_set_datetime(2023, 12, 4, 14, 30, 0);
while (1) {
ds1302_datetime_t now;
ds1302_get_datetime(&now);
printf("Time: %02d:%02d:%02d\n", now.hour, now.minute, now.second);
printf("Date: %04d/%02d/%02d\n", now.year, now.month, now.day);
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
This ESP-IDF example initializes the DS1302 RTC with updated pins (RST: GPIO19, DAT: GPIO21, CLK: GPIO22). The RTC is set to an initial date and time, and in a loop, the current time is retrieved and printed every second using the ds1302_get_datetime()
function.
Update the I2C pins (I2C_MASTER_SDA_IO
and I2C_MASTER_SCL_IO
) to match your ESP32 hardware setup, Use idf.py build to compile the project, Use idf.py flash to upload the code to your ESP32.
ESP32 DS1302 ESPHome Code Example
Fill in this configuration in your ESPHome YAML configuration file (example.yml
) to integrate the DS1302 Real-Time Clock (RTC)
uart:
tx_pin: GPIO21
rx_pin: GPIO22
baud_rate: 9600
time:
- platform: ds1302
id: ds1302_time
update_interval: 1s
sensor:
- platform: custom
lambda: |-
auto my_sensor = new DS1302Sensor(id(ds1302_time));
return {my_sensor};
sensors:
- name: "DS1302 Date and Time"
The ESPHome configuration for the DS1302 RTC defines the updated pins for UART communication (DAT: GPIO21, CLK: GPIO22). The time
platform is used to interact with the RTC, and a custom sensor is defined to periodically retrieve and display the date and time. The update interval is set to 1 second for regular updates.
Upload this code to your ESP32 using the ESPHome dashboard or the esphome run
command.
ESP32 DS1302 PlatformIO Code Example
For PlatformIO, make sure to configure the platformio.ini
file with the appropriate environment and libraries, and then proceed with the code.
Configure platformio.ini
First, your platformio.ini
should look like below. You might need to include some libraries as shown. Make sure to change the board to your ESP32:
[env:arduino_uno]
platform = atmelavr
board = uno
framework = arduino
monitor_speed = 9600
ESP32 DS1302 PlatformIO Example Code
Write this code in your PlatformIO project under the src/main.cpp
file to use the DS1302 Real-Time Clock (RTC):
#include <DS1302.h>
DS1302 rtc(19, 21, 22); // RST, I/O, SCLK
void setup() {
Serial.begin(9600);
rtc.halt(false);
rtc.writeProtect(false);
rtc.setDateTime(2023, 12, 4, 14, 30, 0);
}
void loop() {
DS1302::DateTime now = rtc.getDateTime();
Serial.print("Time: ");
Serial.print(now.hour);
Serial.print(":");
Serial.print(now.minute);
Serial.print(":");
Serial.println(now.second);
Serial.print("Date: ");
Serial.print(now.year);
Serial.print("/");
Serial.print(now.month);
Serial.print("/");
Serial.println(now.day);
delay(1000);
}
The PlatformIO code has been updated for the DS1302 RTC with the new pin configuration (RST: GPIO19, DAT: GPIO21, CLK: GPIO22). The RTC is initialized with these pins, and the current time is fetched and displayed every second.
Upload the code to your ESP32 using the PlatformIO "Upload" button in your IDE or the pio run --target upload
command.
ESP32 DS1302 MicroPython Code Example
Fill in this script in your MicroPython main.py file (main.py
) to integrate the DS1302 Real-Time Clock (RTC) with your ESP32.
from machine import Pin
import time
# Pin definitions
CLK = Pin(22, Pin.OUT) # Clock pin
DAT = Pin(21, Pin.INOUT) # Data pin
RST = Pin(19, Pin.OUT) # Reset pin
# DS1302 commands
READ_TIME = 0x81
WRITE_TIME = 0x80
def write_byte(byte):
for i in range(8):
CLK.value(0)
DAT.value((byte >> i) & 1)
CLK.value(1)
def read_byte():
result = 0
for i in range(8):
CLK.value(0)
if DAT.value():
result |= (1 << i)
CLK.value(1)
return result
def set_time(year, month, day, hour, minute, second):
RST.value(1)
write_byte(WRITE_TIME)
write_byte(second)
write_byte(minute)
write_byte(hour)
write_byte(day)
write_byte(month)
write_byte(year - 2000)
RST.value(0)
def get_time():
RST.value(1)
write_byte(READ_TIME)
second = read_byte()
minute = read_byte()
hour = read_byte()
day = read_byte()
month = read_byte()
year = read_byte() + 2000
RST.value(0)
return year, month, day, hour, minute, second
# Initialize DS1302
RST.value(0)
CLK.value(0)
# Set initial time
set_time(2023, 12, 4, 14, 30, 0)
# Loop to read time
while True:
year, month, day, hour, minute, second = get_time()
print(f"Time: {hour:02}:{minute:02}:{second:02}, Date: {year:04}/{month:02}/{day:02}")
time.sleep(1)
This MicroPython script communicates with the DS1302 RTC using a 3-wire serial protocol with CLK (GPIO22), DAT (GPIO21), and RST (GPIO19). The set_time()
function initializes the DS1302 with the provided date and time by writing data byte-by-byte. The get_time()
function reads the current date and time by issuing the appropriate commands and parsing the returned bytes. The main loop continuously fetches and prints the time and date every second.
Upload this code to your ESP32 using a MicroPython-compatible IDE, such as Thonny, uPyCraft, or tools like ampy
.
DS1302 Real-Time Clock (RTC) Troubleshooting
This guide outlines a systematic approach to troubleshoot and resolve common problems with the . Start by confirming that the hardware connections are correct, as wiring mistakes are the most frequent cause of issues. If you are sure the connections are correct, follow the below steps to debug common issues.
RTC Not Advancing Time Correctly
Issue: The DS1302 RTC module displays a constant time or advances time incorrectly.
Possible causes include insufficient power supply, incorrect wiring, or a defective module.
Solution: Ensure that the module is connected to a stable power source, with VCC connected to 5V and GND to ground. Verify that the CE, I/O, and SCLK pins are correctly connected to the appropriate digital pins on the microcontroller. If the problem persists, consider replacing the DS1302 module, as some units, especially from unreliable sources, may be faulty.
Incorrect or Corrupted Date and Time Display
Issue: The DS1302 module displays incorrect or corrupted date and time information.
Possible causes include improper initialization, incorrect data retrieval methods, or communication errors.
Solution: Ensure that the RTC is properly initialized in your code, disabling write protection and setting the clock to run mode. Use reliable libraries and functions to set and retrieve time data. Verify that the communication between the microcontroller and the RTC is functioning correctly, and consider implementing error-checking mechanisms to detect and handle communication issues.
RTC Module Overheating
Issue: The DS1302 module becomes excessively hot during operation.
Possible causes include incorrect power connections, short circuits, or defective components.
Solution: Double-check all power connections to ensure they are correct, with VCC connected to the appropriate voltage and GND to ground. Inspect the module and wiring for any signs of short circuits or solder bridges. If the module continues to overheat, it may be defective and should be replaced.
Time Resets After Power Loss
Issue: The DS1302 RTC loses track of time after a power cycle.
Possible causes include a missing or depleted backup battery, or incorrect wiring of the backup power supply.
Solution: Install a backup battery (e.g., a CR2032 coin cell) to the VCC1 pin to maintain timekeeping during power loss. Ensure that the battery is fresh and properly connected. Verify that the VCC2 pin is connected to the main power supply, and that the module is configured to switch to the backup battery when the main power is unavailable.
Conclusion
We went through technical specifications of DS1302 Real-Time Clock (RTC), its pinout, connection with ESP32 and DS1302 Real-Time Clock (RTC) code examples with Arduino IDE, ESP-IDF, ESPHome and PlatformIO.