Skip to main content
ESPBoards

ESP32 DS3231 / AT24C32 Real-Time Clock (RTC)

The DS3231 is a highly accurate I²C real-time clock with an integrated temperature-compensated crystal oscillator, providing precise timekeeping and calendar functions, along with programmable alarms and square-wave output, suitable for applications requiring reliable timekeeping.

Jump to Code Examples

Arduino Core Image
ESP-IDF Image
ESPHome Image
PlatformIO Image
MicroPython Image

Quick Links

DS3231 / AT24C32 Real-Time Clock (RTC) Datasheet ButtonDS3231 / AT24C32 Real-Time Clock (RTC) Specs ButtonDS3231 / AT24C32 Real-Time Clock (RTC) Specs ButtonDS3231 / AT24C32 Real-Time Clock (RTC) Specs Button

DS3231 / AT24C32 Price

DS3231 / AT24C32 Real-Time Clock (RTC)
Normally, the DS3231 / AT24C32 Real-Time Clock (RTC) costs around 3.50$ per Psc.
The prices are subject to change. Check current price:

Amazon com

Amazon de logo

Aliexpress logo

About DS3231 / AT24C32 Real-Time Clock (RTC)

The DS3231 is a low-cost, extremely accurate I²C real-time clock (RTC) with an integrated temperature-compensated crystal oscillator (TCXO) and crystal. It provides timekeeping functions with high precision, maintaining seconds, minutes, hours, day, date, month, and year information, with leap-year compensation valid up to 2100. Compared to the DS1307, the DS3231 offers higher accuracy and includes a built-in temperature sensor for compensation, ensuring timekeeping precision across a wide temperature range.

DS3231 / AT24C32 Sensor Technical Specifications

Below you can see the DS3231 / AT24C32 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: I2C
  • Timekeeping Range: Seconds to Years (with Leap-Year Compensation up to 2100)
  • Operating Voltage: 2.3V to 5.5V
  • Timekeeping Accuracy: ±2 ppm from 0°C to +40°C; ±3.5 ppm from -40°C to +85°C
  • Interface: I²C (up to 400 kHz)
  • Clock Output Frequencies: 1 Hz, 1.024 kHz, 4.096 kHz, 8.192 kHz
  • Alarm Function: Two Programmable Time-of-Day Alarms
  • Temperature Sensor Accuracy: ±3°C
  • Operating Temperature: 0°C to +70°C (Commercial); -40°C to +85°C (Industrial)

DS3231 / AT24C32 Sensor Pinout

Below you can see the pinout for the DS3231 / AT24C32 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 DS3231 pinout is as follows:

  • 32kHz: 32.768 kHz output (optional).
  • VBAT: Backup battery input.
  • INT/SQW: Interrupt or square-wave output.
  • SCL: Serial Clock Line for I²C communication.
  • GND: Ground connection.
  • SDA: Serial Data Line for I²C communication.
  • RST: Reset input/output.
  • VCC: Power supply input (2.3V to 5.5V).

DS3231 / AT24C32 Wiring with ESP32

Below you can see the wiring for the DS3231 / AT24C32 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.

To interface the DS3231 with a microcontroller like Arduino or ESP32, connect VCC to a 3.3V or 5V power supply, GND to ground, SDA to the microcontroller's I²C data pin, and SCL to the I²C clock pin. The VBAT pin can be connected to a backup battery to maintain timekeeping during power loss. The INT/SQW pin can be connected to a digital input on the microcontroller if interrupt or square-wave output functionality is required. The RST pin can be used for manual reset control if needed.

Code Examples

Below you can find code examples of DS3231 / AT24C32 Real-Time Clock (RTC) with ESP32 in several frameworks:

If you encounter issues while using the DS3231 / AT24C32 Real-Time Clock (RTC), check the Common Issues Troubleshooting Guide.

Arduino Core Image

ESP32 DS3231 / AT24C32 Arduino IDE Code Example

Example in Arduino IDE

Fill in your main Arduino IDE sketch file with the following code to use the DS3231 / AT24C32 Real-Time Clock (RTC):

#include <Wire.h>
#include <RTClib.h>

RTC_DS3231 rtc;

void setup() {
Serial.begin(9600);
Wire.begin();
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}
if (rtc.lostPower()) {
rtc.adjust(DateTime(2023, 12, 4, 14, 30, 0)); // Set initial date/time
}
}

void loop() {
DateTime now = rtc.now();
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 interface with the DS3231 RTC module using the RTClib library. In the setup() function, the RTC is initialized, and if it has lost power, the date and time are set. The loop() function retrieves the current time and date from the RTC and prints them to the Serial Monitor every second.

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.

ESP-IDF Image

ESP32 DS3231 / AT24C32 ESP-IDF Code Example
Example in Espressif IoT Framework (ESP-IDF)

If you're using ESP-IDF to work with the DS3231 / AT24C32 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/i2c.h"
#include "ds3231.h"

#define I2C_MASTER_SCL_IO 22
#define I2C_MASTER_SDA_IO 21

void app_main(void) {
i2c_config_t i2c_config = {
.mode = I2C_MODE_MASTER,
.sda_io_num = I2C_MASTER_SDA_IO,
.scl_io_num = I2C_MASTER_SCL_IO,
.sda_pullup_en = GPIO_PULLUP_ENABLE,
.scl_pullup_en = GPIO_PULLUP_ENABLE,
.master.clk_speed = 100000
};
i2c_param_config(I2C_NUM_0, &i2c_config);
i2c_driver_install(I2C_NUM_0, I2C_MODE_MASTER, 0, 0, 0);

ds3231_init(I2C_NUM_0);
ds3231_set_datetime(2023, 12, 4, 14, 30, 0);

while (1) {
ds3231_datetime_t now;
ds3231_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 demonstrates how to interface with the DS3231 RTC over I²C. SDA and SCL are connected to GPIO21 and GPIO22, respectively. The RTC is initialized, and the date and time are set using ds3231_set_datetime(). The current time and date are retrieved with ds3231_get_datetime() and displayed on the console every second.

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.

ESPHome Image

ESP32 DS3231 / AT24C32 ESPHome Code Example

Example in ESPHome (Home Assistant)

Fill in this configuration in your ESPHome YAML configuration file (example.yml) to integrate the DS3231 / AT24C32 Real-Time Clock (RTC)

i2c:
sda: GPIO21
scl: GPIO22

time:
- platform: ds3231
id: ds3231_time
update_interval: 1s

sensor:
- platform: custom
lambda: |-
auto my_sensor = new DS3231Sensor(id(ds3231_time));
return {my_sensor};
sensors:
- name: "DS3231 Date and Time"

The ESPHome configuration sets up I²C communication with the DS3231 RTC using SDA on GPIO21 and SCL on GPIO22. The time platform fetches the date and time at 1-second intervals. A custom sensor processes and displays the time and date in a human-readable format.

Upload this code to your ESP32 using the ESPHome dashboard or the esphome run command.

PlatformIO Image

ESP32 DS3231 / AT24C32 PlatformIO Code Example

Example in PlatformIO Framework

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:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 115200

ESP32 DS3231 / AT24C32 PlatformIO Example Code

Write this code in your PlatformIO project under the src/main.cpp file to use the DS3231 / AT24C32 Real-Time Clock (RTC):

#include <Wire.h>
#include <RTClib.h>

RTC_DS3231 rtc;

void setup() {
Serial.begin(115200);
Wire.begin(21, 22); // SDA: GPIO21, SCL: GPIO22
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}
if (rtc.lostPower()) {
rtc.adjust(DateTime(2023, 12, 4, 14, 30, 0)); // Set initial date/time
}
}

void loop() {
DateTime now = rtc.now();
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 PlatformIO code demonstrates how to interface with the DS3231 RTC using I²C. SDA and SCL are connected to GPIO21 and GPIO22, respectively. The RTC is initialized, and if it has lost power, the date and time are set. The loop() retrieves the current time and date and prints them every second.

Upload the code to your ESP32 using the PlatformIO "Upload" button in your IDE or the pio run --target upload command.

MicroPython Image

ESP32 DS3231 / AT24C32 MicroPython Code Example

Example in Micro Python Framework

Fill in this script in your MicroPython main.py file (main.py) to integrate the DS3231 / AT24C32 Real-Time Clock (RTC) with your ESP32.

from machine import I2C, Pin
import time

# DS3231 I2C address
DS3231_ADDRESS = 0x68

def bcd_to_decimal(bcd):
return (bcd >> 4) * 10 + (bcd & 0x0F)

def decimal_to_bcd(decimal):
return ((decimal // 10) << 4) | (decimal % 10)

def set_time(i2c, year, month, day, hour, minute, second):
data = [decimal_to_bcd(second), decimal_to_bcd(minute), decimal_to_bcd(hour),
decimal_to_bcd(day), 0, decimal_to_bcd(month), decimal_to_bcd(year - 2000)]
i2c.writeto_mem(DS3231_ADDRESS, 0x00, bytes(data))

def get_time(i2c):
data = i2c.readfrom_mem(DS3231_ADDRESS, 0x00, 7)
second = bcd_to_decimal(data[0])
minute = bcd_to_decimal(data[1])
hour = bcd_to_decimal(data[2])
day = bcd_to_decimal(data[4])
month = bcd_to_decimal(data[5] & 0x1F)
year = bcd_to_decimal(data[6]) + 2000
return year, month, day, hour, minute, second

# Initialize I2C
i2c = I2C(0, scl=Pin(22), sda=Pin(21))

# Set initial time
set_time(i2c, 2023, 12, 4, 14, 30, 0)

# Loop to read time
while True:
year, month, day, hour, minute, second = get_time(i2c)
print(f"Time: {hour:02}:{minute:02}:{second:02}, Date: {year:04}/{month:02}/{day:02}")
time.sleep(1)

This MicroPython script interfaces with the DS3231 RTC over I²C using SDA (GPIO21) and SCL (GPIO22). The set_time() function sets the date and time on the DS3231 by writing BCD-encoded values to its memory. The get_time() function reads the current date and time from the DS3231, decodes the BCD values into integers, and returns them in a human-readable format. The main loop continuously fetches the current time and date from the DS3231 and prints them every second.

Upload this code to your ESP32 using a MicroPython-compatible IDE, such as Thonny, uPyCraft, or tools like ampy.

DS3231 / AT24C32 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 DS3231 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 SDA and SCL pins are correctly connected to the appropriate digital pins on the microcontroller. If the problem persists, consider replacing the DS3231 module, as some units, especially from unreliable sources, may be faulty.

Incorrect or Corrupted Date and Time Display

Issue: The DS3231 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 DS3231 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 DS3231 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 VBAT pin to maintain timekeeping during power loss. Ensure that the battery is fresh and properly connected. Verify that the VCC 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 DS3231 / AT24C32 Real-Time Clock (RTC), its pinout, connection with ESP32 and DS3231 / AT24C32 Real-Time Clock (RTC) code examples with Arduino IDE, ESP-IDF, ESPHome and PlatformIO.