Arduino connection of real time clock ds3231. Synchronizing the time on the DS3231 module with the computer

Distinctive features:

  • Accuracy ±2 ppm over temperature range 0°C to +40°C
  • Accuracy ±3.5 ppm over temperature range -40°C to +85°C
  • Input for connecting an autonomous power source to ensure continuous operation
  • Operating temperature range commercial: from 0°C to +70°C industrial: -40°C to +85°C
  • Low consumption
  • Real time clock counting seconds, minutes, hours, days of the week, days of the month, month and year with leap year correction up to 2100
  • Two daily alarms
  • Exit square wave with programmable frequency
  • Fast (400 kHz) I 2 C interface
  • 3.3V power
  • Digital temperature sensor with measurement accuracy ±3°C
  • Register containing data about the required adjustment
  • nonRST reset input/output

Application:

  • Servers
  • Electronic electricity meters
  • Telematics equipment
  • GPS systems

Typical connection diagram for DS3231:

General description:

The DS3231 is a high-precision real-time clock (RTC) with built-in I 2 C interface, temperature compensated crystal oscillator (TCXO) and quartz resonator. The device has an input for connecting a backup autonomous power source, which allows timekeeping and temperature measurement even when the main supply voltage is turned off. The built-in quartz resonator increases the service life of the device and reduces the required number of external elements. The DS3231 is available in commercial and industrial temperature versions and is packaged in a 300 mil 16 pin SO package.

RTC provides counting of seconds, minutes, hours, days of the week, days of the month and year. The end date of the month is determined automatically taking into account leap years. The real time clock operates in 24 or 12 hour format with an indication of the current half of the day (AM/PM). The device has two daily alarms and a square wave output with a programmable frequency. Data exchange with the device is carried out through the built-in serial I 2 C compatible interface.

Many devices require constant recording of chronometric data (date, time); this function is performed by special electronic circuits, which is called the real time clock. Currently, a real-time clock is implemented in the form of a separate microcircuit, to which you need to add a quartz resonator and an autonomous power source. In some microcircuits, a quartz resonator is built inside. One of these clocks on a chip DS3231SN I bought it for mine projects . In the example I will connect a real-time clock to a Chinese analogue Arduino UNO.

They are a complete ZS-042 module that can be connected to various devices, not only to the Arduino platform.


The module is built on a microcircuit DS3231SN which is essentially a real time clock. Unlike the old watch model, for example on the DS1307 chip, this watch contains an internal quartz resonator, due to which the watch has an accurate time.

You can implement a clock on Arduino without DS3231SN, but then if the power is lost, the timer values ​​are reset.These same clocks have backup power, so if the power goes out, they continue to work.

The watch can count hours, minutes, seconds, dates, months, years (leap years are taken into account until 2100). They operate in 12 or 24 hour mode, contain two alarm clocks, and also have an internal thermometer with a range from -40 ° C to + 85 ° C. To connect to various devices, the clock is connected via I2C interface.


Location and purpose of pins on the ZS-042 module:

S.Q.W.- Programmable Square-Wave signal output.

SCLThrough this pin, data is exchanged with the clock via the I2C interface.

S.D.A.Data from the watch is transmitted through this pin.

VCCPower supply for real time clock, 5 volts required. If there is no voltage supplied to this pin, the watch goes into sleep mode.

GND- Earth.

To connect to Arduino UNO, We connect the SDA pin of the clock to pin A4, and the SCL pin to A5. The GND(-) and VCC(+5v) pins are used for power supply.

SDA and SCL pins on different Arduino boards:

S.D.A. SCL
UNO A4 A5
Mini A4 A5
Nano A4 A5
Mega2560 20 21
Leonardo 2 3

Let's install a CR2032 battery in the watch; such elements are used to power the BIOS in computers.

At USB connection cable to the Arduino, the LED on the clock should light up " POWER"(red LED).

In order to program the clock via Arduino IDE you need to install libraries.

Download library Time and DS1307RTC.

The last library was written for a clock on the DS1307 chip, but its interaction protocols are compatible with the DS3231, so the library will fit our clock.

Libraries need to be downloaded, unpacked and placed in the folder "libraries" When starting Arduino IDE, they with examples should appear in " Samples».

Set the Date and Time.

To do this, copy this code into the Arduino IDE.

For correct settings you need to change the data in the line

setTime(13,35,0,22,12,2016);



In parentheses, separated by commas, set the correct ones: hours, minutes, seconds, day, month, year. In my example, it is set to 13 hours 35 minutes 0 seconds, December 22, 2016. Upload the sketch to Arduino.

Now, in order to read the readings from the clock, you can use the example: “ File» - « Samples» - « DS1307RTC» - « ReadTest" And for upload it to Arduino.

The window that opens will display the current date and time. If you turn off the power to the clock module from the Arduino, the Arduino will not be able to track the values ​​and after some time the message " ...read error! "(highlighted in red). After power is restored, the date and time will continue to count down. The date and time were not reset because the watch was powered by its CR2032 battery.

In many Arduino projects, it is required to monitor and record the time of occurrence of certain events. Real time clock module equipped with extra batteries, allows you to store current date, regardless of the availability of power on the device itself. In this article we will talk about the most common RTC modules DS1307, DS1302, DS3231 that can be used with Arduino board.

The clock module is a small board containing, as a rule, one of the DS1307, DS1302, DS3231 microcircuits. In addition, on the board you can practically find a battery installation mechanism. Such boards are often used to track time, date, day of the week and other chronometric parameters. The modules operate on autonomous power - batteries, accumulators, and continue to count even if the power to the Arduino is turned off. The most common watch models are DS1302, DS1307, DS3231. They are based on an RTC (real time clock) module connected to Arduino.

The clock counts in units that are convenient to an ordinary person– minutes, hours, days of the week and others, in contrast to conventional counters and clock generators that read “ticks”. Arduino has special function millis(), which can also read different time intervals. But the main disadvantage of this function is that it resets to zero when the timer is turned on. With its help you can only read time; it is impossible to set the date or day of the week. Real-time clock modules are used to solve this problem.

The electronic circuit includes a microcircuit, a power supply, a quartz resonator and resistors. The quartz resonator operates at a frequency of 32768 Hz, which is convenient for a conventional binary counter. The DS3231 circuit has built-in quartz and thermal stabilization, which allows for highly accurate values.

Comparison of popular RTC modules DS1302, DS1307, DS3231

In this table we have provided a list of the most popular modules and their main characteristics.

Name Frequency Accuracy Supported protocols
DS1307 1 Hz, 4.096 kHz, 8.192 kHz, 32.768 kHz Depends on the quartz - usually the value reaches 2.5 seconds per day, it is impossible to achieve accuracy higher than 1 second per day. Also, accuracy depends on temperature. I2C
DS1302 32.768 kHz 5 seconds a day I2C, SPI
DS3231 Two outputs - the first at 32.768 kHz, the second programmable from 1 Hz to 8.192 kHz ±2 ppm at temperatures from 0C to 40C.

±3.5 ppm at temperatures from -40C to 85C.

Temperature measurement accuracy – ±3С

I2C

Module DS1307

DS1307 is a module that is used for timing. It is assembled on the basis of the DS1307ZN chip, power comes from a lithium battery for implementation battery life over a long period of time. The battery on the board is mounted on the reverse side. The module has an AT24C32 chip - this is a 32 KB non-volatile EEPROM memory. Both microcircuits are connected by an I2C bus. DS1307 has low power consumption and contains a clock and calendar for the year 2100.

The module has the following parameters:

  • Power supply – 5V;
  • Operating temperature range from -40C to 85C;
  • 56 bytes of memory;
  • Lithium battery LIR2032;
  • Implements 12 and 24 hour modes;
  • I2C interface support.

The module is justified in cases where data is read quite rarely, at intervals of a week or more. This allows you to save on power, since uninterrupted use will require more voltage, even with a battery. The presence of memory allows you to register various parameters (for example, temperature measurement) and read the received information from the module.

Interaction with other devices and exchange of information with them is carried out using the I2C interface from the SCL and SDA pins. The circuit contains resistors that allow you to provide the required signal level. The board also has a special place for mounting the DS18B20 temperature sensor. The contacts are distributed into 2 groups, pitch 2.54 mm. The first group of contacts contains the following pins:

  • DS – output for sensor DS18B20;
  • SCL – clock line;
  • SDA – data line;
  • VCC – 5V;

The second group of contacts contains:

  • SQ – 1 MHz;
  • BAT – input for lithium battery.

To connect to the Arduino board, you need the board itself (in this case we are considering Arduino Uno), an RTC DS1307 real-time clock module, wires and a USB cable.

To connect the controller to Arduino, 4 pins are used - VCC, ground, SCL, SDA.. VCC from the clock is connected to 5V on the Arduino, ground from the clock is connected to ground from the Arduino, SDA - A4, SCL - A5.

To start working with the clock module, you need to install the DS1307RTC, TimeLib and Wire libraries. You can also use RTCLib for work.

Checking the RTC module

When you run the first code, the program will read data from the module once per second. First, you can see how the program behaves if you remove the battery from the module and replace it with another while the Arduino board is not connected to the computer. You need to wait a few seconds and remove the battery, eventually the watch will reboot. Then you need to select an example from the Examples→RTClib→ds1307 menu. It is important to set the transmission speed correctly to 57600 bps.

When you open the Serial Monitor window, the following lines should appear:

The time will show 0:0:0. This is because the watch loses power and will stop counting time. For this reason, the battery must not be removed while the module is operating.

To set the time on the module, you need to find the line in the sketch

RTC.adjust(DateTime(__DATE__, __TIME__));

This line will contain data from the computer that is used to flash the real-time clock module. For correct operation You must first check that the date and time on the computer are correct, and only then start flashing the clock module. After setup, the monitor will display the following data:

The setup is done correctly and there is no need to additionally reconfigure the real-time clock.

Time reading. Once the module is configured, time requests can be sent. This is done using the now() function, which returns a DateTime object that contains time and date information. There are a number of libraries that are used to read time. For example, RTC.year() and RTC.hour() - they separately obtain information about the year and hour. When working with them, a problem may arise: for example, a request to display the time will be made at 1:19:59. Before showing the time 1:20:00, the clock will display the time 1:19:00, meaning, in essence, one minute will be lost. Therefore, these libraries are advisable to use in cases where reading occurs infrequently - once every few days. There are other functions for calling time, but if you need to reduce or avoid errors, it is better to use now() and extract the necessary readings from it.

Example project with i2C clock module and display

The project is a regular clock; the indicator will display exact time, and the colon between the numbers will blink at intervals of one second. To implement the project, you will need an Arduino Uno board, a digital indicator, a real-time clock (in this case, the above-described ds1307 module), a shield for connection (in this case, Troyka Shield is used), a battery for the clock and wires.

The project uses a simple four-digit indicator on the TM1637 chip. The device has a two-wire interface and provides 8 levels of monitor brightness. Used only to display time in hours:minutes format. The indicator is easy to use and easy to connect. It is beneficial to use for projects where minute or hourly data verification is not required. To get more complete information LCD monitors are used to indicate time and date.

The clock module is connected to the SCL/SDA pins, which belong to the I2C bus. You also need to connect ground and power. It is connected to Arduino in the same way as described above: SDA – A4, SCL – A5, ground from the module to ground from Arduino, VCC -5V.

The indicator is connected simply - its CLK and DIO pins are connected to any digital pins on the board.

Sketch. To write code, use the setup function, which allows you to initialize the clock and indicator and record the compilation time. Printing the time to the screen will be done using loop.

#include #include "TM1637.h" #include "DS1307.h" //you need to include all the necessary libraries for working with the clock and display. char compileTime = __TIME__; //compilation time. #define DISPLAY_CLK_PIN 10 #define DISPLAY_DIO_PIN 11 //numbers from the Arduino outputs to which the screen is connected; void setup() ( display.set(); display.init(); //connect and configure the screen. clock.begin(); //turn on the clock. byte hour = getInt(compileTime, 0); byte minute = getInt( compileTime, 2); byte second = getInt(compileTime, 4); //getting time. clock.fillByHMS(hour, minute, second); //preparing for writing to the time module clock.setTime(); information received in internal memory, start of time reading. ) void loop() ( int8_t timeDisp; //display on each of the four digits. clock.getTime(); //query to get the time. timeDisp = clock.hour / 10; timeDisp = clock.hour % 10; timeDisp = clock .minute / 10; timeDisp = clock.minute % 10; //various operations for obtaining tens, units of hours, minutes, and so on display.display(timeDisp); //displaying the time on the indicator display.point(clock.second %). 2 ? POINT_ON: POINT_OFF);//turn on and off the colon after a second. ) char getInt(const char* string, int startIndex) ( return int(string - "0") * 10 + int(string) - "0"; //actions to correctly write the time into a two-digit integer. Otherwise, just a couple of characters will be displayed on the screen.

After this, the sketch needs to be loaded and the time will be shown on the monitor.

The program could be slightly modernized. When the power is turned off, the sketch written above will cause the display to show the time that was set during compilation after turning it on. In the setup function, each time the time that has passed from 00:00:00 to the start of compilation will be calculated. This hash will be compared to what is stored in the EEPROM, which is retained when power is removed.

To write and read time to or from non-volatile memory, you need to add the EEPROMWriteInt and EEPROMReadInt functions. They are needed to check whether the hash matches/mismatches the hash recorded in the EEPROM.

The project can be improved. If you use an LCD monitor, you can make a project that displays the date and time on the screen. The connection of all elements is shown in the figure.

As a result, you will need to specify in the code new library(for LCD screens this is LiquidCrystal), and add lines to the loop() function to get the date.

The operating algorithm is as follows:

  • Connecting all components;
  • Check - the time and date on the monitor screen should change every second. If the time on the screen is incorrect, you need to add the RTC.write (tmElements_t tm) function to the sketch. Problems with incorrect times are due to the fact that the clock module resets the date and time to 00:00:00 01/01/2000 when turned off.
  • The write function allows you to get the date and time from the computer, after which the correct parameters will be indicated on the screen.

Conclusion

Clock modules are used in many projects. They are needed for data recording systems, when creating timers and control devices that operate according to a given schedule, in household appliances. With widely available and cheap modules, you can create projects such as an alarm clock or a sensor data logger, recording information to an SD card or showing the time on a display screen. In this article, we looked at typical usage scenarios and connection options for the most popular types of modules.

The DS3231 module (RTC, ZS-042) is a low-cost board with an extremely accurate real-time clock (RTC), with temperature compensation of the crystal oscillator and crystal. The module includes a lithium battery that maintains uninterrupted operation even when the power supply is turned off. The integrated generator improves the accuracy of the device and reduces the number of components.

Technical Parameters

Supply voltage: 3.3V and 5V
Memory chip: AT24C32 (32 KB)
Accuracy: ±0.432 sec per day
Quartz frequency: 32.768 kHz
Supported protocol: I2C
Dimensions: 38mm x 22mm x 15mm

General information

Most microcircuits, such as DS1307, use an external quartz oscillator with a frequency of 32 kHz, but they have a significant drawback: when the temperature changes, the quartz frequency changes, which leads to an error in timing. This problem is eliminated in the DS3231 chip, which contains a crystal oscillator and a temperature sensor that compensates for temperature changes so that the time remains accurate (temperature data can be read if necessary). The DS3231 chip also supports seconds, minutes, hours, day of the week, date, month and year information, and also monitors the number of days in a month and corrects for leap years. It supports clocks in two formats: 24 and 12, and it is also possible to program two alarms. The module operates on a two-wire I2C bus.


Now a little about the module itself; it is built on the DS3231N chip. Resistor assembly RP1 (4.7 kOhm) is required to pull up the 32K, SQW, SCL and SDA lines (by the way, if several modules with an I2C bus are used, it is necessary to unsolder the pull-up resistors on other modules). The second assembly of resistors is necessary to tighten up the lines A0, A1 and A2; they are needed to change the addressing of the AT24C32N memory chip. Resistor R5 and diode D1 serve to recharge the battery; in principle, they can be removed, since a regular SR2032 battery lasts for years. An AT24C32N memory chip is also installed, this is like a bonus; it is not needed to operate the RTC DS3231N clock. Resistor R1 and the Power LED signal that the module is turned on. As mentioned, the module operates on the I2C bus; for convenience, these buses were routed to two connectors J1 and J2; the assignment of the remaining contacts can be seen below. Purpose J1
32K: output, frequency 32 kHz
SQW: output
SDA: data line (Serial Dфta)
VCC: “+” module power supply
GND: “-” module power supply Purpose J2
SCL: Serial CLock
SDA: Serial Data line
VCC: “+” module power supply
GND: “-” module power supply


I’ll tell you a little about the AT24C32N chip, this is a chip with 32k memory (EEPROM) from the manufacturer Atmel, assembled in a SOIC8 package, operating on a two-wire I2C bus. The address of the microcircuit is 0x57; if necessary, it can be easily changed using jumpers A0, A1 and A2 (this allows you to increase the number of connected AT24C32/64 microcircuits). Since the AT24C32N chip has three address input(A0, A1 and A2), which can be in two states, either log “1” or log “0”, eight addresses are available to the microcircuit. from 0x50 to 0x57.

Connecting DS3231 to Arduino

Required parts:
Arduino UNO R3 x 1 pc.
Real time clock on DS3231, RTC, SPI, AT24C32 x 1 pc.
DuPont wire, 2.54 mm, 20 cm, F-M (Female - Male) x 1 pc.
USB cable 2.0 A-B x 1 pcs.

Connection:
IN in this example I will only use the DS3231 module and Arduino UNO R3, all data will be transferred to “Port Monitoring”. The circuit is not complicated, only four wires are needed, first we connect the I2C bus, SCL in A4 (Arduino UNO) and SDA in A5 (Arduino UNO), all that remains is to connect the power supply GND to GND and VCC to 5V (can be written from 3.3V), circuit assembled, now we need to prepare the software part.

There is no library that works with the DS3231 in the Arduino IDE, you need to download “DS3231” and add it to the Arduino development environment.

Setting the DS3231 time
When you turn it on for the first time, you need to program the time, open the example from the DS3231 library “File” -> “Examples” -> “DS3231” -> “Arduino” -> “DS3231_Serial_Easy”, or copy the code from below

/* Testing was carried out on Arduino IDE 1.8.0 Test date 08/31/2018. */ #include // Connect the Wire DS3231 library rtc(SDA, SCL); // Initialize DS3231 void setup() ( Serial.begin(115200); // Installation serial connection rtc.begin(); // Initialize rtc // Set the time rtc.setDOW(FRIDAY); // Set the day of the week rtc.setTime(16, 29, 0); // Set the time to 16:29:00 (24 hour format) rtc.setDate(31, 8, 2018); // Set the date to August 31, 2018) void loop() ( Serial.print(rtc.getDOWStr()); // Send the day-week Serial.print(" "); Serial.print(rtc.getDateStr()); // Send the date Serial.print(" -- "); Serial.println(rtc.getTimeStr()); // Send the time delay (1000); // Delay in one second)

Testing was carried out on Arduino IDE 1.8.0

Test date: 08/31/2018

#include // Include the Wire library

DS3231 rtc (SDA, SCL); // Initialize DS3231

void setup()

Serial. begin(115200); // Establish a serial connection

rtc. begin(); // Initialize rtc

// Set the time

rtc. setDOW(FRIDAY); // Set day-of-week

rtc. setTime(16, 29, 0); // Set the time to 16:29:00 (24 hour format)

void loop()

Serial. print (rtc . getDOWStr () ) ; // Send day-week

Serial. print (" " ) ;

Serial. print (rtc . getDateStr () ) ; // Send the date

Serial. print (" -- " ) ;

Serial. println(rtc. getTimeStr()); // Send time

delay(1000); // One second delay

Upload the sketch to the Arduino controller and open “Port Monitoring”

Share