Sensors/ RTC/ DS1302

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.

DS1302 Real-Time Clock (RTC) image
DS1302 · 3-Wire
3-Wire
Interface
8pins
Connections
2.0-5.5V
Supply
$1.50
Typical price
On this page

DS1302 pinout

8 pins · 3-Wire

The DS1302 pinout includes power supply pins (VCC1 for primary, VCC2 for backup), a 3-wire serial interface (SCLK, I/O, RST), ground, and crystal oscillator connections (X1, X2).

View:
DS1302 Real-Time Clock (RTC) pinout
PinTypeDescriptionNotes
VCC1PowerPrimary power supply input (2.0V to 5.5V)Main power source for normal operation
VCC2Backup PowerBackup power supply inputBattery or capacitor for timekeeping during power loss
GNDGroundGround connectionCommon ground
SCLKSerial ClockSerial clock inputClock signal for 3-wire communication
I/ODataBidirectional data input/outputData line for 3-wire communication
RSTControlReset input (Chip Enable)Must be HIGH to enable communication
X1Crystal32.768 kHz crystal oscillator connectionCrystal input
X2Crystal32.768 kHz crystal oscillator connectionCrystal output
  • Real-time clock with seconds, minutes, hours, day, month, year

  • Leap year compensation up to 2100

  • 31 bytes of SRAM for data storage

  • Programmable trickle charger for backup battery/capacitor

  • 3-wire serial interface (simpler than I2C)

  • Operating voltage: 2.0V to 5.5V

  • Low power consumption: <500nA in standby

  • Requires external 32.768 kHz crystal

Wiring the DS1302 to ESP32

6 connections · 1 optional

Connect the DS1302 to your ESP32 using three GPIO pins for the 3-wire serial interface. The module requires a 32.768 kHz crystal and optionally a backup battery (e.g., CR2032) for continuous timekeeping during power loss.

DS1302 Real-Time Clock (RTC) wiring with ESP32
DS1302 pinESP32 pinPurpose
VCC13.3V or 5VPrimary power supply
VCC2CR2032 BatteryBackup power (battery or capacitor) · optional
GNDGNDGround connection
SCLKGPIO18Serial clock input
I/OGPIO23Bidirectional data line
RSTGPIO5Reset/Chip Enable (active HIGH)
  • VCC1 can be 3.3V or 5V (ESP32 uses 3.3V)

  • VCC2 typically connected to CR2032 coin cell battery (3V)

  • RST pin must be HIGH to enable communication

  • 32.768 kHz crystal required (usually included on module)

  • Trickle charger can charge backup battery/supercapacitor

  • Configure trickle charger carefully to avoid battery damage

  • Use DS1302 library (e.g., ThreeWire + RtcDS1302)

  • Disable write protection before setting time

  • Lower cost alternative to I2C RTCs like DS1307/DS3231

DS1302 code examples

5 platforms
Platform:

DS1302 Arduino example

Copy
// Requires library: "Ds1302"
#include <Ds1302.h>

// RST (CE) = GPIO5, CLK = GPIO18, DAT (I/O) = GPIO23 - matches the wiring above
Ds1302 rtc(5, 18, 23); // ENA (RST), CLK, DAT

void setup() {
    Serial.begin(115200);
    rtc.init();

    if (rtc.isHalted()) {
        Serial.println("RTC is halted. Setting the time...");
        Ds1302::DateTime dt = {
            .year = 26, .month = Ds1302::MONTH_SEP, .day = 1,
            .hour = 12, .minute = 0, .second = 0,
            .dow = Ds1302::DOW_TUE
        };
        rtc.setDateTime(&dt);
    }
}

void loop() {
    Ds1302::DateTime now;
    rtc.getDateTime(&now);

    Serial.print("Time: ");
    Serial.print(now.hour);
    Serial.print(":");
    Serial.print(now.minute);
    Serial.print(":");
    Serial.println(now.second);
    Serial.print("Date: 20");
    Serial.print(now.year);
    Serial.print("/");
    Serial.print(now.month);
    Serial.print("/");
    Serial.println(now.day);
    delay(1000);
}

The DS1302 uses its own 3-wire interface, wired here as RST on GPIO5, CLK on GPIO18 and DAT on GPIO23 to match the wiring above. The example uses the Ds1302 library (install it from the Library Manager): isHalted() detects a first run or dead backup battery, in which case the time is set once with setDateTime(); afterwards getDateTime() returns the running clock every second. The library stores the year as two digits.

DS1302 ESP-IDF example

Copy
// Requires the esp-idf-lib DS1302 driver from the ESP Component Registry:
//   idf.py add-dependency "esp-idf-lib/ds1302^1.2.0"

#include <stdio.h>
#include <string.h>
#include <time.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "ds1302.h"

#define CE_GPIO   GPIO_NUM_5  // RST, matches the wiring above
#define IO_GPIO   GPIO_NUM_23 // I/O
#define SCLK_GPIO GPIO_NUM_18 // SCLK

void app_main(void)
{
    ds1302_t dev = {
        .ce_pin = CE_GPIO,
        .io_pin = IO_GPIO,
        .sclk_pin = SCLK_GPIO,
    };
    ESP_ERROR_CHECK(ds1302_init(&dev));
    ESP_ERROR_CHECK(ds1302_set_write_protect(&dev, false));

    while (1) {
        struct tm time;
        if (ds1302_get_time(&dev, &time) == ESP_OK)
            printf("%04d-%02d-%02d %02d:%02d:%02d\n",
                   time.tm_year + 1900, time.tm_mon + 1, time.tm_mday,
                   time.tm_hour, time.tm_min, time.tm_sec);
        else
            printf("Could not read time from RTC\n");
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}

ESP-IDF ships no DS1302 driver of its own, so this example uses the maintained esp-idf-lib DS1302 driver from the ESP Component Registry. Install it into your project first with idf.py add-dependency "esp-idf-lib/ds1302^1.2.0", then build as usual.

The DS1302 uses its own 3-wire interface (CE, I/O and SCLK - not I2C), so the pins are passed directly in the ds1302_t structure. ds1302_set_write_protect(&dev, false) must be called once before the clock can be set, and ds1302_get_time() fills a standard struct tm. To set the time initially, call ds1302_set_time() once with a populated struct tm and then remove that code.

DS1302 ESPHome example

Copy
external_components:
  - source: github://trombik/esphome-component-ds1302
    components: [ds1302]

time:
  - platform: ds1302
    id: rtc_time
    cs_pin: GPIO5    # RST/CE, matches the wiring above
    dio_pin: GPIO23  # I/O
    clk_pin: GPIO18  # SCLK
    update_interval: never

text_sensor:
  - platform: template
    name: "DS1302 Date and Time"
    lambda: |-
      char buf[20];
      auto now = id(rtc_time).now();
      if (!now.is_valid()) return {"unknown"};
      now.strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S");
      return {buf};
    update_interval: 1s

Core ESPHome has no DS1302 platform (the chip uses a 3-wire interface, not I2C), so this example pins the maintained trombik/esphome-component-ds1302 external component. The pins match the wiring above: RST/CE on GPIO5, I/O on GPIO23, SCLK on GPIO18. As with the other RTC pages, a template text_sensor formats the time; use ds1302.write_time after a one-time SNTP/Home Assistant sync to set the clock.

DS1302 PlatformIO example

Copy
[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 115200
lib_deps =
    caligari/Ds1302 @ ^1.1.0
src/main.cppCopy
#include <Arduino.h>
#include <Ds1302.h>

// RST (CE) = GPIO5, CLK = GPIO18, DAT (I/O) = GPIO23 - matches the wiring above
Ds1302 rtc(5, 18, 23); // ENA (RST), CLK, DAT

void setup() {
    Serial.begin(115200);
    rtc.init();

    if (rtc.isHalted()) {
        Serial.println("RTC is halted. Setting the time...");
        Ds1302::DateTime dt = {
            .year = 26, .month = Ds1302::MONTH_SEP, .day = 1,
            .hour = 12, .minute = 0, .second = 0,
            .dow = Ds1302::DOW_TUE
        };
        rtc.setDateTime(&dt);
    }
}

void loop() {
    Ds1302::DateTime now;
    rtc.getDateTime(&now);

    Serial.print("Time: ");
    Serial.print(now.hour);
    Serial.print(":");
    Serial.print(now.minute);
    Serial.print(":");
    Serial.println(now.second);
    Serial.print("Date: 20");
    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.

DS1302 MicroPython example

Copy
# Requires driver: ds1302.py from https://github.com/omarbenhamid/micropython-ds1302-rtc
# Copy it to the board: mpremote cp ds1302.py :
from machine import Pin
from ds1302 import DS1302
import time

# Pins per the wiring above: SCLK=GPIO18, I/O=GPIO23, RST/CE=GPIO5
rtc = DS1302(Pin(18), Pin(23), Pin(5))

# Set the clock once (year, month, day, weekday, hour, minute, second), then comment out
# rtc.date_time([2026, 9, 1, 1, 12, 0, 0])

while True:
    year, month, day, weekday, hour, minute, second = rtc.date_time()
    print("{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(year, month, day, hour, minute, second))
    time.sleep(1)

The example uses omarbenhamid/micropython-ds1302-rtc (copy ds1302.py to the board) with the 3-wire pins from the wiring above: SCLK GPIO18, I/O GPIO23, RST/CE GPIO5. Uncomment the date_time([...]) line once to set the clock, then read it back every second.

DS1302 specifications

From the datasheet
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)

About the DS1302

The DS1302 is the oldest real-time clock on this site, and it shows: instead of I2C it uses a 3-wire serial protocol of its own (RST/CE, I/O, and SCLK), so it needs three dedicated GPIOs rather than sharing the two-wire I2C bus every other RTC here uses. It tracks seconds through year with leap-year compensation to 2100, keeps 31 bytes of static RAM for small application data, and includes a programmable trickle charger for a backup battery or supercapacitor - a feature the newer DS1307 dropped.

What it does not have is any temperature compensation. Accuracy depends entirely on the external tuning-fork crystal, and a typical 32.768kHz crystal is only rated to about 20ppm at room temperature - worse as the temperature swings - which works out to something on the order of a minute or two of drift per month under good conditions. Independent head-to-head testing against a temperature-compensated RTC has shown the gap in practice: over a two-week comparison, a DS1302 lost close to 19 seconds while a DS3231 on the same bench drifted under 2 seconds. That is fine for a project that resyncs from NTP periodically, but not for anything that needs to keep its own time unattended for months.

Given that the DS1307 offers the same basic feature set over a simpler I2C connection, and the DS3231 adds real temperature compensation for a couple of dollars more, the DS1302 is mostly a fit for reproducing an existing 3-wire design or working from an older tutorial - new designs are usually better served by one of the I2C parts.

DS1302 troubleshooting

4 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.

Where to buy the DS1302

DS1302 Real-Time Clock (RTC)
DS1302 Real-Time Clock (RTC)
$1.50per unit, typical
Amazon and AliExpress links are affiliate links - buying through them supports the site at no extra cost to you.

Resources

Similar sensors