DS3231 RTC Real Time Clock_EN
DS3231 RTC Real Time Clock_EN
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!
Table of Contents
Introduction....................................................................................................3
Specifications................................................................................................5
The pinout.....................................................................................................6
How to set-up Arduino IDE............................................................................7
How to set-up the Raspberry Pi and Python...............................................11
Connecting the module with Uno.................................................................12
Sketch example.......................................................................................14
Connecting the module with Raspberry Pi..................................................20
Enabling the I2C interface.......................................................................21
Libraries and tools for Python..................................................................23
Python script............................................................................................24
-2-
Introduction
-3-
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.
-4-
Specifications
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 one 3V coin cell battery and the battery
is included with the module. The battery serves as back-up power supply for
the module. When external power supply is turned OFF, the automatic
detection on-board chip switches to battery back-up.
-5-
The pinout
The DS3231 RTC module has a six pins on one side and additional four, for
power supply and I2C interface lines on the other side. The pinout is shown
on the following image:
The 32K output pin is a crystal controlled oscillator output pin. It provides a
32kHz square-wave signal and it can be used to feed the 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.
-6-
How to set-up Arduino IDE
If the Arduino IDE is not installed, follow the link and download the
installation file for the operating system of choice.
For Windows users, double click on the downloaded .exe file and follow
the instructions in the installation window.
-7-
For Linux users, download a file with the extension .tar.xz, which has to
be extracted. When it is extracted, go to the extracted directory and open
the terminal in that directory. Two .sh scripts have to be executed, the first
called arduino-linux-setup.sh and the second called install.sh.
To run the first script in the terminal, open the terminal in the extracted
directory and run the following command:
sh arduino-linux-setup.sh user_name
user_name - is the name of a superuser in the Linux operating system. A
password for the superuser has to be entered when the command is
started. Wait for a few minutes for the script to complete everything.
The second script, called install.sh, has to be used after the installation
of the first script. Run the following command in the terminal (extracted
directory): sh install.sh
After the installation of these scripts, go to the All Apps, where the Arduino
IDE is installed.
-8-
Almost all operating systems come with a text editor preinstalled (for
example, Windows comes with Notepad, Linux Ubuntu comes with
Gedit, Linux Raspbian comes with Leafpad, etc.). All of these text
editors are perfectly fine for the purpose of the eBook.
Next thing is to check if your PC can detect an Arduino board. Open freshly
installed Arduino IDE, and go to:
Tools > Board > {your board name here}
{your board name here} should be the Arduino/Genuino Uno, as it can
be seen on the following image:
The port to which the Arduino board is connected has to be selected. Go to:
Tools > Port > {port name goes here}
and when the Arduino board is connected to the USB port, the port name
can be seen in the drop-down menu on the previous image.
-9-
If the Arduino IDE is used on Windows, port names are as follows:
- 10 -
How to set-up the Raspberry Pi and Python
For the Raspberry Pi, first the operating system has to be installed, then
everything has to be set-up so that it can be used in the Headless mode.
The Headless mode enables remote connection to the Raspberry Pi,
without the need for a PC screen Monitor, mouse or keyboard. The only
things that are used in this mode are the Raspberry Pi itself, power supply
and internet connection. All of this is explained minutely in the free eBook:
Raspberry Pi Quick Startup Guide
- 11 -
Connecting the module with Microcontroller
Compatible with Arduino
Connect the DS3231 RTC module with the Microcontroller compatible with
Arduino as shown on the following connection diagram:
- 12 -
Library for Arduino IDE
With the library comes several sketch examples, to open one, go to:
File > Examples > RTClib > ds3231
With this sketch example the module can be tested. The sketch in this
eBook is modified version of this sketch, to get more user-friendly output.
- 13 -
Sketch example
#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();
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
/* To manualy set date and time,
remove the coment // signs
and enter new values in the followingline
in this sequence: year, day, month, hour, minute and second.*/
//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();
- 14 -
//one tab
//Current time:
Serial.print("Current Time: ");
if (now.hour() < 10) {
Serial.print("0");
Serial.print(now.hour());
}
else {
Serial.print(now.hour(), DEC);
}
Serial.print(':');
- 15 -
//one tab
//Current date:
Serial.print("Current Date: ");
if (now.day() < 10) {
Serial.print("0");
Serial.print(now.day());
}
else {
Serial.print(now.day(), DEC);
}
Serial.print('/');
if (now.month() < 10) {
Serial.print("0");
Serial.print(now.month());
}
else {
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");
Serial.println();
delay(2000);
}
- 16 -
Upload the sketch to the Uno and open Serial Monitor: (Tools > Serial
Monitor).
The result should look like the output on the following image:
- 17 -
At the beginning of the sketch two libraries called Wire and RTClib are
imported. These libraries are used to import functions that can be used for
communication between the module and Uno.
Next, the function called rtc.adjust() is used. This function sets date
and time in the module. It has one argument, a DateTime object. To set
the current date and time of the PC during upload time, the following line of
code is used:
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
- 18 -
When a specific time and date has to be set, it can be done with adjust()
and DateTime() functions. For example, if date is to be set to: 09th March
2020. And time to 10:00:00, following line of code can be used:
rtc.adjust(DateTime(2020, 3, 09, 10, 00, 0));
At the beginning of the loop() function, the data is read from the module
and information is stored in the object called now with following line of code:
DateTime now = rtc.now();
The object now is type of DateTime. After reading and storing data to this
object, properties of this object are called to display data.
First, day of the week is printed. Next, the current time. The original sketch
output displayed values without a leading zero, so a simple if and else
statements are added for better output. Each time when numerical values
are less than 10, a leading zero is added to the output.
- 19 -
Connecting the module with Raspberry Pi
Connect the DS3231 RTC module with the Raspberry Pi as shown on the
following connection diagram:
- 20 -
Enabling the I2C interface
In order to use the module with Raspberry Pi, I2C interface of the
Raspberry Pi has to be enabled. Open following menu:
Application Menu > Preferences > Raspberry Pi Configuration
In the new window, under the tab Interfaces, enable the I2C radio button, as
on the following image:
- 21 -
To detect I2C address of the module, i2ctools should be installed. If It is
not installed, open the terminal and execute the following command:
sudo apt-get install i2ctools -y
Checking the RTC module I2C address is done by executing the following
command in the terminal:
i2cdetect -y 1
Where, the 0x68 is the I2C address of the RTC module and 0x57 is the I2C
address of the EEPROM chip.
If I2C interface is not enabled before executing the previous command, the
error will be displayed as on the following image:
- 22 -
Libraries and tools for Python
To use this script, the git app and python-smbus library have to be
installed. To do so, run the following commands in the terminal:
sudo apt-get update
sudo apt-get install -y python-smbus git
After downloading the library, the script rtc_lib.py can be found in the
following directory:
/home/pi/az-delivery-ds3231
- 23 -
Python script
import time
import rtc_lib # importing library functions
degree_sign = u'\xb0'
def check(num):
'''A fucntion that put leading zero to single digit number
return: string
'''
if num < 10:
return '0{}'.format(num)
else:
return str(num)
- 24 -
print('[Press CTRL + C to end the script!]')
try:
while True:
print('\nSystem time: {}'.format(
time.strftime('%Y-%m-%d %H:%M:%S')))
data = ds3231.read_datetime() # return tuple
print('RTC date: {} {}.{}.{}'.format(data[0],
data[1], check(data[2]), check(data[3])))
print('RTC time: {}:{}:{}'.format(check(data[4]),
check(data[5]), check(data[6])))
# return string
print('RTC date_time: {}'.format(ds3231.read_str()))
print('Temperature: {:.1f}C'.format(ds3231.getTemp(),
degree_sign))
time.sleep(1)
except KeyboardInterrupt:
print('\nScript end!')
- 25 -
Save the script by the name rtc.py in the same directory where the
rtc_lib.py script is saved. To run the script, open the terminal in the
directory where the script is saved and run the following command:
python3 rtc.py
- 26 -
The script starts with importing two libraries, time and rtc_lib.
Then, the object called ds3231 is created with the following line of code:
ds3231 = rtc_lib.SDL-DS3231(1, 0x68)
Where the number 0x68 represents the I2C address of the RTC module.
After this, the date and time in RTC is updated with the following line of
code:
ds3231.write_now()
The function write_now() stores in the RTC module the current date and
time of the Raspbian operating system.
There is another option to store time and date data. It can be done with the
following line of code:
ds3231.write_all(seconds=None,minutes=None,hours=None,day=None,
date=None,month=None,year=None,save_as_24h=True)
- 27 -
The function called write_all() has eight arguments and returns no
value. The arguments represent part of data for date and time. The values
for all arguments are integer numbers in the ranges:
Seconds: 0 - 59, Minutes: 0 - 59, Hours: 0 - 23 Day: 1 - 7 (day in week),
Date: 1 - 31, Month: 1 12, Year: 0 - 99
Save_as_24h: True/False (tested with only as True)
Next, a new function is created, called check(). The function has one
argument and returns a string value. It is used to add leading zero to the
single digit number. The argument represents the number which is then
checked if it is a single or double digit number. If the number is a single
digit, then the string value ‘0{}’.format(num) is returned. If the number
is not a double digit number then the string value str(num) is returned.
After that, the try-except block of code is created. In the try block of
code, the indefinite loop is created. In the indefinite loop the RTC data is
read, and displayed in the terminal. There are two ways to display data in
the terminal. The first is by using the function read_datetime() and the
second is by using the function read_str().
To stop the script press ‘CTRL + C’ on the keyboard. This is called the
keyboard interrupt. When the keyboard interrupt happens, the except
block of code is executed, displaying message Script end! in the
terminal.
- 28 -
The function read_datetime() has two arguments and returns a tuple.
The first argument represents the century, an integer value, for example: for
21st century, use century=21. The second argument represents time
zone info, used for datetime objects (it is not covered in this eBook). The
return value is a tuple which has seven elements. The elements are:
dayOfWeek, dayOfMonth, month, year, hour, minute and second (in this
order). All values for these elements are integer numbers, except the value
of dayOfWeek argument which is a string value, which represents the name
of the weekday.
The function read_str() has one argument and returns a string value.
The argument is the century argument, and is used as the century
argument of the read_datetime() function. The return value is a string
value, with predefined format for date and time data, as shown in the
following script output:
To get temperature data from the RTC module, use the function called
detTemp(). The function has no arguments and returns a float value. The
return value, a float value, represents the temperature data in Celsius.
- 29 -
Now it is the time to learn and make your own projects. You can do that with
the help of many example scripts and other tutorials, which can be found on
the Internet.
If you are looking for the high quality products for Arduino and
Raspberry Pi, AZ-Delivery Vertriebs GmbH is the right company to get
them from. You will be provided with numerous application examples,
full installation guides, eBooks, libraries and assistance from our
technical experts.
https://az-delivery.de
Have Fun!
Impressum
https://az-delivery.de/pages/about-us
- 30 -