AZ-Delivery DS3231 Real Time Clock Module Guide
Welcome! Thank you for purchasing our AZ-Delivery DS3231 Real Time Clock Module. On the following pages, you will be introduced to how to use and set up this handy device. Have fun!
Introduction
The DS3231 Real Time Clock module is used as a time synchronization device in applications where precise timings are essential. The module is used in digital clocks, computer motherboards, digital cameras, embedded systems, etc.
It is a real-time clock with an integrated temperature-compensated crystal oscillator. There is an on-board battery holder, so that it can maintain continuous time keeping when the device is not powered from an external source.
One of the features of the module is that it can operate in 12-hour or 24-hour format and has an AM/PM indication capability. The module is programmable with two day-time alarms. Alarms can be programmed via an integrated EEPROM chip which can store alarm data in internal memory. There is also a 32KHz square-wave oscillator output pin, which can be used to synchronize time with other similar devices.
The internal clock can provide seconds, minutes, hours, day, date, month, and year information. The date at the end of the month is automatically adjusted for months which have less than 31 days. It also includes corrections for leap years. The module has an I2C interface with I2C serial address, and it can be connected alongside with other devices on the same I2C lines.
Specifications
Power supply voltage | 3.3V |
Operational temperature | from 0°C to +70°C |
Communication interface | I2C |
Battery backup | One 3V coin cell battery holder |
Digital temp sensor | ±3°C Accuracy |
Programmable square-wave | 32kHz [Output] |
Time of day alarms | 2 |
Low power consumption | less than 1mA |
Dimensions | 34 x 23 x 18mm [1.3 x 09 x 07in] |
The module consists of a DS3231 RTC Clock chip and Atmel AT24C32 EEPROM chip. The AT24C32 has memory storage capacity of 32kB and uses the I2C bus interface with 0x57 address which can be modified. It has a capability of setting the time and date, checking and clearing alarms, and logging data with a timestamp.
The module has a battery holder for a 3V button cell; the battery is not included with the module. A CR2032 or, alternatively, a LIR2032 is required. The battery serves as a backup power supply for the module. When the external power supply is switched off, the integrated chip with automatic detection switches to the emergency power supply provided by the battery.
The Pinout
The DS3231 RTC module has six pins on one side and an additional four for power supply and I2C interface lines on the other side. The pinout is shown below:
Pinout Diagram Description: The module has pins labeled POWER, 32K, SQW, SCL, SDA, VCC, and GND. The diagram shows these pins clearly marked on the PCB.
The DS3231 RTC module safely operates at 3.3V. VCC can only be connected to 5V if the RTC is operated with a LIR2032.
The 32K output pin is a crystal-controlled oscillator output pin. It provides a 32kHz square-wave signal and can be used to feed a reference signal for other devices. It may be left floating if not used.
The SQW pin can provide either an interrupt signal due to alarm conditions or a square-wave output signal.
How to Set Up Arduino IDE
If the Arduino IDE is not installed, follow the link and download the installation file for your operating system.
For Windows users: Double-click on the downloaded .exe file and follow the instructions in the installation window.
For Linux users: Download a file with the extension .tar.xz, which has to be extracted. Navigate to the extracted directory and open the terminal. Two .sh scripts need to be executed: arduino-linux-setup.sh
and install.sh
.
To run the first script in the terminal, execute: sh arduino-linux-setup.sh user_name
. Replace user_name
with your Linux superuser name. You will be prompted for your password. Wait for the script to complete.
The second script, install.sh
, is used after the first. Run: sh install.sh
.
After installation, find the Arduino IDE in your applications list.
Almost all operating systems come with a preinstalled text editor (e.g., Notepad on Windows, Gedit on Ubuntu, Leafpad on Raspbian). These are suitable for this guide.
Next, verify if your PC detects an Arduino board. Open the Arduino IDE and go to: Tools > Board > {your board name here}
. The board should be the Arduino/Genuino Uno.
The port to which the Arduino board is connected must be selected. Go to: Tools > Port > {port name goes here}
. The port name will appear in the drop-down menu when the Arduino board is connected via USB.
For Windows: Port names typically appear as COM ports (e.g., COM3).
For Linux: Port names are usually in the format /dev/ttyUSBx
, where x
is a number from 0 to 9.
How to Set Up the Raspberry Pi and Python
To use the module with the Raspberry Pi, first install the operating system and configure it for "Headless mode". Headless mode allows remote connection to the Raspberry Pi without a monitor, mouse, or keyboard, using only the Pi itself, power supply, and internet connection. This is explained in detail in the free eBook: "Raspberry Pi Quick Startup Guide".
The Raspbian operating system comes with Python preinstalled.
Connecting the Module with Microcontroller Compatible With Arduino
Connect the DS3231 RTC module to an Arduino-compatible microcontroller as shown in the following connection diagram:
Connection Diagram Description: The diagram shows an Arduino board and the DS3231 RTC module connected with wires. The module's pins (32K, SQW, SCL, SDA, VCC, GND) are connected to specific pins on the Arduino board.
Module Pin | Arduino Pin | Wire Color |
---|---|---|
SCL | A5 | Green wire |
SDA | A4 | Blue wire |
VCC | 3.3V | Red wire |
GND | GND | Black wire |
Library for Arduino IDE
To use the module with an Arduino Uno, it is recommended to download an external library called RTClib
. The version used in this guide is 1.3.3.
To download and install it: Open Arduino IDE, go to Tools > Manage Libraries
. In the new window, search for RTClib
and install the library made by Adafruit.
The library includes example sketches. To open one, navigate to File > Examples > RTClib > ds3231
. This sketch can be used to test the module. The sketch provided in this guide is a modified version for user-friendliness.
Sketch Example (Arduino)
The following C++ code demonstrates how to use the DS3231 module with Arduino:
#include <Wire.h>
#include "RTClib.h"
RTC_DS3231 rtc;
char daysOfTheWeek[7][12] = {
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
};
void setup() {
Serial.begin(9600);
delay(2000);
rtc.begin();
// To manually set date and time, uncomment the following line and adjust values:
// rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
// Example: rtc.adjust(DateTime(2020, 2, 24, 10, 00, 0));
}
void loop() {
DateTime now = rtc.now();
// Day of the week
Serial.print("Day of the week: ");
Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
Serial.println();
// Current time
Serial.print("Current Time: ");
if (now.hour() < 10) {
Serial.print("0");
}
Serial.print(now.hour(), DEC);
Serial.print(':');
if (now.minute() < 10) {
Serial.print("0");
}
Serial.print(now.minute(), DEC);
Serial.print(':');
if (now.second() < 10) {
Serial.print("0");
}
Serial.print(now.second(), DEC);
Serial.println();
// Current date
Serial.print("Current Date: ");
if (now.day() < 10) {
Serial.print("0");
}
Serial.print(now.day(), DEC);
Serial.print('/');
if (now.month() < 10) {
Serial.print("0");
}
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.year(), DEC);
Serial.print("");
Serial.println();
// Temperature
Serial.print("Temperature: ");
Serial.print(rtc.getTemperature());
Serial.println(" °C"); // Using degree symbol
Serial.println();
delay(2000);
}
After uploading the sketch to the Uno, open the Serial Monitor (Tools > Serial Monitor
). The output should display the day of the week, current time, current date, and temperature.
Code Explanation:
- The sketch begins by importing the
Wire.h
andRTClib.h
libraries for communication. - An
RTC_DS3231
object namedrtc
is created. - A character array
daysOfTheWeek
stores the names of the days for display. - In
setup()
, serial communication is initialized, andrtc.begin()
establishes communication with the module.rtc.adjust()
can be used to set the date and time. - In
loop()
,rtc.now()
retrieves the current date and time. The code then prints the day, time, date, and temperature, formatting values less than 10 with a leading zero for better readability.
Connecting the Module with Raspberry Pi
Connect the DS3231 RTC module to the Raspberry Pi as shown in the following connection diagram:
Connection Diagram Description: The diagram illustrates a Raspberry Pi board and the DS3231 RTC module connected via jumper wires. The module's pins (VCC, SDA, GND, SCL) are connected to specific GPIO pins on the Raspberry Pi.
RTC Pin | Raspberry Pi Pin | Physical Pin | Wire Color |
---|---|---|---|
VCC | 3V3 | 1 | Red wire |
SDA | GPIO2 | 3 | Blue wire |
GND | GND | 6 | Black wire |
SCL | GPIO3 | 5 | Green wire |
Enabling the I2C Interface
To use the module with the Raspberry Pi, the I2C interface must be enabled. Navigate through the menus: Application Menu > Preferences > Raspberry Pi Configuration
.
In the new window, under the "Interfaces" tab, enable the I2C option.
To detect I2C addresses: Install i2ctools
by running the following command in the terminal: sudo apt-get install i2ctools -y
.
Check the RTC module's I2C address by executing: i2cdetect -y 1
.
The output should show the I2C addresses. Typically, 0x68
is the address for the RTC module, and 0x57
is for the EEPROM chip.
If the I2C interface is not enabled, an error message will appear indicating that the device files could not be opened.
Libraries and Tools for Python
To use the Python script, the git
app and the python-smbus
library need to be installed. Run these commands in the terminal:
sudo apt-get update
sudo apt-get install -y python-smbus git
Download the external library script using:
git clone https://github.com/Slaveche90/az-delivery-ds3231.git
After downloading, the rtc_lib.py
script will be in the directory: /home/pi/az-delivery-ds3231
.
To change to this directory, use the command: cd az-delivery-ds3231
.
Python Script
The following Python script controls the RTC module:
import time
import rtc_lib # importing library functions
degree_sign = u'\xb0' # UTF8 symbol for degree sign
# Initialize the DS3231 module with I2C address 0x68
ds3231 = rtc_lib.SDL_DS3231(1, 0x68)
# Save the current date and time of the Raspberry Pi to the RTC module
ds3231.write_now()
# Alternative to write all parameters (optional):
# ds3231.write_all(seconds=None, minutes=None, hours=None,
# day=None, date=None, month=None, year=None, save_as_24h=True)
# Range: seconds [0-59]; minutes [0-59]; hours [0-23]; day [1-7];
# date [1-31]; month [1-12]; year [0-99]
# Function to add a leading zero to single-digit numbers
def check(num):
'''A function that puts a leading zero to single digit numbers.'''
if num < 10:
return '0{}'.format(num)
else:
return str(num)
print('[Press CTRL + C to end the script!]')
try:
while True:
# Print system time
print('\nSystem time: {}'.format(time.strftime('%Y-%m-%d %H:%M:%S')))
# Read date and time from RTC module
data = ds3231.read_datetime() # returns a tuple
# Format and print RTC date
# data[0]=dayOfWeek, data[1]=dayOfMonth, data[2]=month, data[3]=year
print('RTC date: {} {}.{}.{}'.format(data[0], data[1], check(data[2]), data[3])) # Year is 2-digit from read_datetime
# Format and print RTC time
# data[4]=hour, data[5]=minute, data[6]=second
print('RTC time: {}:{}:{}'.format(check(data[4]), check(data[5]), check(data[6])))
# Print RTC date and time in a specific string format
print('RTC date_time: {}'.format(ds3231.read_str()))
# Print temperature
print('Temperature: {:.1f}{}'.format(ds3231.getTemp(), degree_sign))
time.sleep(1) # Wait for 1 second
except KeyboardInterrupt:
print('\nScript end!')
Save the script as rtc.py
in the same directory as rtc_lib.py
. To run it, open the terminal in that directory and execute: python3 rtc.py
.
The output will show the system time, RTC date, RTC time, and temperature. Press CTRL + C
to stop the script.
Script Explanation:
- The script imports the
time
andrtc_lib
libraries. - A
degree_sign
variable stores the degree symbol. - The
ds3231
object is initialized for the RTC module. ds3231.write_now()
updates the RTC with the current system time.- The
check()
function ensures single-digit numbers are displayed with a leading zero. - The
try-except
block runs an infinite loop to continuously read and display time, date, and temperature from the RTC module. ds3231.read_datetime()
retrieves date and time as a tuple.ds3231.read_str()
provides date and time in a formatted string.ds3231.getTemp()
reads the temperature.time.sleep(1)
pauses execution for one second between readings.- A
KeyboardInterrupt
(CTRL+C) gracefully stops the script.
Conclusion
Now is the time to learn and make your own projects. You can do that with the help of many example scripts and other tutorials found on the Internet.
For high-quality products for Arduino and Raspberry Pi, AZ-Delivery Vertriebs GmbH is a recommended supplier. They provide numerous application examples, installation guides, eBooks, libraries, and assistance from technical experts.
Visit: https://az-delivery.de
For more information, see: https://az-delivery.de/pages/about-us