Ds1307 power. RTC module DS1307 connection to Arduino. Test project for DS1307

Real time clock module DS1307
Tiny RTC I2C module 24C32 memory DS1307 clock

A small module that performs the functions of a real-time clock. Made on the basis of the DS1307ZN + chip. Continuous counting of time occurs due to autonomous power supply from the battery installed in the module. The module also contains a 32 Kb EEPROM memory that retains information when all types of power are turned off. Memory and clock are connected by a common I2C interface bus. The I2C bus signals are output to the module contacts. When connected external power supply the battery is charged through a primitive charging circuit. The board has a place for mounting a digital temperature sensor DS18B20. It is not included in the package.
The use of this device occurs when measuring time intervals of more than a week with devices based on a microcontroller. It is unjustified and often impossible to use the own resources of the MC for this purpose. Provide uninterruptible power supply on the long term expensive, it is impossible to install a battery to power the MK due to the significant current consumption. This is where the DS1307 real-time clock module comes to the rescue.
Also, the DS1307 real-time clock module, thanks to its own memory, allows you to record event data that occurs several times a day, such as temperature measurements. The event log is then read from the module memory. These features make it possible to use the module as part of an autonomous automatic weather station or for climate research in hard-to-reach places: caves, rock tops. It becomes possible to register the tensor parameters of architectural structures, such as bridge supports and others. When equipping the device with radio communication, it is enough to install it in the area under study.

Characteristics

Supply voltage 5 V
Dimensions 27 x 28 x 8.4mm

Wiring diagram

The device communicates with the device electronics using the SCL and SDA signals. Chip IC2 - real time clock. Capacitors C1 and C2 reduce noise on the VCC supply line. Resistors R2 and R3 provide the proper level for the SCL and SDA signals. Pin 7 of IC2 receives the SQ signal, consisting of 1 Hz rectangular pulses. It is used to test the functionality of MS IC2. Components R4, R5, R6, VD1 provide recharging of the BAT1 battery. For data storage, the DS1307 real-time clock module contains an IC1 chip - non-volatile memory. US1 - temperature sensor. The signals of the module and the power line are output to connectors JP1 and P1.

information bus

I2C is a standard serial interface through two signal lines SCL, SDA and ground. The interface lines form a bus. Several chips can be connected to the I2C interface lines, not just the module chips. To identify the chip on the bus, namely writing data to the required MS and determining from which MS the data is coming. Each chip has a unique address for the routed bus. DS1307 has Address 0x68. It is written at the factory. The memory chip has address 0x50. AT software Arduino includes a software library that provides I2C support.

Real time clock chip

DS1307 has low power consumption, communicates with other devices through the I2C interface, contains a memory of 56 bytes. Contains clock and calendar up to 2100. Real-time clock chip provides other devices with information about the present moment: seconds, minutes, hours, day of the week, date. The number of days in each month is taken into account automatically. There is a compensation function for a leap year. There is a flag to determine if the clock is running in 24-hour mode or 12-hour mode. To work in 12-hour mode, the microcircuit has a bit, from where data is read for transmission about the time period: before or after lunch.

Non-volatile memory chip

Drawing of the real time clock module DS1307 from the side of the battery with the temperature sensor U1 installed.

Battery

In the holder for reverse side The board is equipped with a CR2032 lithium disk battery. It is produced by many manufacturers, for example, the one manufactured by GP provides a voltage of 3.6 V and a discharge current of 210 mAh. The battery is recharged during power-on, this is the mode of operation of the lithium battery that we encounter on motherboard computer.

Battery recharging

Software

For the module to work as part of the Arduino, an outdated library from the Adafruit website called RTCLib is quite suitable. The sketch is called DS1307.pde. There is an updated version. You should download the archive, unpack it, rename it and copy the library to your Arduino library directory.

Connecting to Arduino Mega

To do this, use sketches
SetRTC sets the time in hours according to the time specified in the sketch.
GetRTC displays the time.
Both sketches require the Wire library and define an I2C address. To set the clock address on the I2C bus, use this I2C scanner.

Connection with Arduino Mega.

Connect SCL and SDA to the corresponding pins 21 and 20 on the Arduino Mega 2560. Connect the power.

Connection with Arduino Uno


Set the time in the SetRTC sketch and upload to the Arduino. Then press the reset button to set the clock. Now download the GetRTC sketch. Open the serial monitor and see. There is a special time library. It has many different features that can be useful depending on the situation. To set the time using the library you need to download the . When using a sketch, you can synchronize the real time clock with the PC clock.

Hello!
Today I want to tell you about such an interesting microcircuit as DS1307. This is a wonderful watch plus a calendar, and the most wonderful thing is that there is a bible in CVAVR for this mikruha. Yes, and she just fell into my arm and I decided to torment her 8) First of all, we need a diagram of its connection. It is quite simple and was taken from the datasheet. But there is a small exception here. The datasheet requires you to connect a resistor between the power leg and the rectangular pulse output leg. Since I was making a separate board, in order to be able to test further projects on it, I added another LED. It turned out very convenient. Seen for example second pulses.
The actual scheme.

And here's what it looks like assembled.

I tested in a bunch of ATmega32 + LCD 16x2 + DS1307. Next, there are two options. First, you can generate the code directly with the CVAVR generator. Second, write everything yourself. I suggest writing it yourself, but first let's go over the features of the DS1307.
1. rtc_init(rs, sqwe, out) This is the very first function to initialize the chip. Now all the arguments are in order. rs needed to set the frequency of the output rectangular pulses on the leg SQW/OUT. 0 - 1 Hz 1 - 4096 Hz 2 - 8192 Hz 3 - 32768 Hz sqwe needed to enable the output of rectangular pulses. 1 - possible 0 - no. out needed to determine the logic level on the output leg if there is no permission to output rectangular pulses. In bent. In short, if you do not need to pull your leg SQW/OUT, then the parameter sqwe put in 0 and now if out equals 1 , then it will be on the leg 1 , and if we write 0 , then on the leg too 0 . Example: rtc_init(0,1,0); This means to enable the output of rectangular pulses with a frequency of 1 Hz. 2. rtc_set_time(hour, min, sec) Well, from the name you can see that this function sets the time. Everything is simple here, the arguments are hours, minutes and seconds. 3. rtc_set_date(day, month, year) The same hat but with the date. four. rtc_get_time(&hour, &min, &sec) And here for more details. This function is needed to get the current time. The arguments of a function are the addresses of the variables where it will then write the values. This is done due to the fact that functions can only return one parameter (such is C). That is, before calling the function, you need to initialize three unsigned char variables. 5. rtc_get_date(&day, &month, &year) The same but with the date. Now everything is the same with examples. rtc_set_time(15, 0, 0); Set time 15:00:00 rtc_set_date(14, 2, 14); We set the date to February 14, 2014. Note that the year is written in two numbers. Piece of datasheet: Real-Time Clock (RTC) Counts Seconds, Minutes, Hours, Date of the Month, Month, Day of the week, and Year with Leap-Year Compensation Valid Up to 2100 Until the year 2100, and since an unsigned char is passed to our function, the value can be taken from 0 to 255. I did not try to drive more than a hundred, but the year 2014 recorded with a fright was displayed as 144 8) unsigned char hour, min, sec; rtc_get_time(&hour, &min, &sec); First, we initialize the variables, and then we call the function. After calling it, you can safely operate with the time that will be written to the variables. unsigned char day, month, year; rtc_get_date(&day, &month, &year); In principle, the same thing is here, only the date will lie in the variables. And finally, the whole program with comments as promised. /***************************************************** **** Real time clock program DS1307 Microcontroller: ATmega32 Crystal frequency: 3.686400 MHz **************************** *************************/ #include // Specify the port and pins for the I2C bus #asm .equ __i2c_port=0x1B ;PORTA .equ __sda_bit=0 .equ __scl_bit=1 #endasm #include // Connect the library to work with DS1307 #include // Specify which port the LCD is connected to #asm .equ __lcd_port=0x12 ;PORTD #endasm // We connect the library for working with the LCD #include // We connect the library for working with strings #include void main(void) ( // Array initialization for string and variables for data unsigned char string; unsigned char c, m, s, d, me, g; PORTA=0x00; DDRA=0x00; PORTB=0x00; DDRB=0x00; PORTC=0x00; DDRC=0x00; PORTD=0x00; DDRD=0x00; // Initialize the I2C bus i2c_init(); // Initialize DS1307 rtc_init(0,1,0); // Display initialization lcd_init(16); // I used these functions once to set the time and date. // rtc_set_time(16, 0, 0); // rtc_set_date(13, 2, 14); while (1) ( // Got the time rtc_get_time(&c, &m, &s); lcd_gotoxy(0,0); // Formatted sprintf(string, "Time %02i:%02i:%02i ", c, m, s); // Displayed the time lcd_puts(string); // Got the date rtc_get_date(&d, &me, &g); lcd_gotoxy(0,1); // Formatted sprintf(string, "Date %02i.%02i.20%2i ", d, me, g); // Displayed the date lcd_puts(string); ); ) Well, like everything. For a start, I think it’s clear, but there’s someone like it. Here's what it looks like in action.



Roman 29.10.15 21:30

Thanks for the article, everything is clear and without water.

Alexey 29.10.15 22:47

Trying)

Zhenya 07.11.15 09:33

Thanks a lot Alexey!

Alexey 07.11.15 10:23

Please.

Peter 05.04.16 00:11

Is it really possible to repeat this in the flowcode program?

Alexey 04/05/16 08:52

And what is this program?

Mikhail 09.09.16 00:18
Alexey 09.09.16 12:16
Sergey 20.11.16 12:28

Thanks for the detailed explanation of the examples. Could you add an example manual installation time in RTC? Sometimes a time adjustment is needed.

Alexey 20.11.16 15:33

For full-fledged work with real-time clocks DS1307 and DS3231, I have written functions that are included in the . I recommend using it for more simplified project generation under Atmel Studio. You can also see video about using this library.

Benjamin 10.12.16 23:33

Rtc_set_date(13, 2, 14);
The compiler may swear at such a record "too few arguments" since 4 arguments must be passed, the first of which is the day of the week. Therefore, you need to transfer 4 numbers, and pick up - also 4. As far as I know, in some versions of codevision it rolls with three, but I personally messed around until I found out why the time is calmly written and read, but the date is not.

Alexey 11.12.16 00:00

That's why I gave up on CVAVR with its jambs (and they are not only in hours), switched to AtmelStudio and wrote a library for it a-five CVAVR. Now I have everything working and not buggy.)))

ANONYMOUS 02.03.17 00:39

I advise everyone to replace Ds1307 with 3231, because 32 is much more accurate, and 1307 is only suitable for timers.

ANTONYM 03.04.17 15:18

Much more precisely - how much exactly? IMHO the accuracy of the clock is determined by 99.9999999% accuracy quartz resonator.

Alexey 03.04.17 16:09

Well, not quite. The person probably just meant thermal compensation, since the frequency of quartz also depends on temperature.

IgorKazantse 31.07.19 16:54

Situation: I bought mikruha DS1307. Soldered your diagram. The only function needed is the output of second pulses. Nothing else is needed. What to do? Which programmer to use? [email protected]

Alexey 01.08.19 10:50

The programmer is not needed. You need to write a program for any MK that will send a command to set the frequency of the output leg SQW / OUT. Further, while there is voltage on the microcircuit, the output will be a meander at 1Hz.

In many designs it is useful to know current time, but it is not always possible, and if the controller is heavily loaded, the clock will constantly lag behind or rush, which is not very good. The output can be an external ready-made time source - a real-time clock - DS1307.

The clock consists of a DS1307 chip, a 32.768 kHz quartz, a battery, and 2 pull-up resistors on the SDA and SLC lines. Thanks to the battery, they continue to go when the external power is turned off. Also, the DS1307 has free 56 bytes of volatile static RAM that you can use for your own purposes.

The SCL and SDA lines are I2C. On the SQW line - there is a clock pulse with a frequency from 1 Hz to 32.768 KHz, it is usually not used.

The watch has a couple of features:

1. in order for them to work, they must have a battery or, in extreme cases, a 4-10kΩ resistor, otherwise they will not work and respond with all kinds of garbage.
2. there should be a closed earth loop around the quartz tracks and it is also better to connect the quartz body to the ground

A bit of theory

The chronometer has a fixed address 68h, in a 7 bit address + 1 bit indicates the action - read / write.
The following algorithm is used for recording:
The first byte is the address of the clock 68h + 0 bits indicating the entry, total D0h. After confirmation is received, the register address is transmitted. This will set the register pointer. Then the transfer of data bytes starts to stop it - an end condition is generated.
For reading:
The first byte is the clock address 68h + 1 bit indicating the entry, total D1h. After decoding the address and issuing an acknowledgment, the device starts transmitting data from the specified address (stored in the pointer register). If the register pointer is not written before the start of reading, then the first address read is the address that was last stored in it. The DS1307 must accept a "Non-acknowledge" to complete the read.

To turn on the clock, set the CH bit to zero, this should be done forcibly, because. the clock is off by default after being turned on.

The clock stores information in binary-decimal form - to obtain data, it is enough to read the corresponding register.

DS1307 can work in both 24 and 12 hour mode - bit 12/24 (02h 6 bits) is responsible for this. In 24-hour mode, bits 5 and 4 of register 02h correspond to the current ten of the hour, in 12-hour mode, bit 4 stores the ten, and 5 indicates the a.m./p.m.

7 register is responsible for the output clock generator, SQW output. The OUT bit inverts the output, the SQWE bit turns on the clock, and the RS0 and RS1 bits set the clock frequency.

Practice

A small real-time clock module was made. A clock was assembled on a breadboard using a PIC16F628A microcontroller, a 2×16 character-generating display, one button for setting the time, a real-time clock module, and with a small amount of strapping.

The board contains a DS1307 chip in SMD design. Quartz is soldered to it at 32.768 kHz, in the DT-38 package, there should be an earth ring around the quartz and the quartz itself should also be connected to the ground, for this a special hole is provided next to it. The watch is powered by a 3V CR120 battery. Also, to indicate the operation of the module, you can install an SMD LED with a 470 Ohm resistor in a 0805 size case.

PIC16F628A does not contain hardware I2C, so it was implemented in software. Software I2C was written from scratch, it differs slightly from the standard protocol in that it does not wait for confirmation from the slave. Software I2C will be covered in one of the following articles. Based on the I2C functions, the following DS1307 control functions have been implemented:

Void ds_write(unsigned char addr,unsigned char data) ( i2c_start(); i2c_write(0xD0); i2c_write(addr); i2c_write(data); i2c_stop(); ) unsigned char ds_read(unsigned char addr) ( unsigned temp; i2c_start( ); i2c_write(0xD0); i2c_write(addr); i2c_stop(); i2c_start(); i2c_write(0xD1); temp=i2c_read(0); i2c_stop(); return temp; ) void ds_off() ( ds_write(0x00,ds_read (0x00)|0x80); ) void ds_on() ( ds_write(0x00,ds_read(0x00)&~0x80); ) void ds_init() ( unsigned char i; // set mode to 24 hours i=ds_read(0x02); if ((i&0x40)!=0) ( ds_write(0x02,i&~0x40); ) // If the clock is off, then turn it on i=ds_read(0x00); if((i&0x80)!=0) ( ds_write(0x00,i& ~0x80); ) ) unsigned char IntToBoolInt(unsigned char data) ( data=data%100; return data/10*16+data%10; )

ds_write( address , data byte ) - sends 1 byte of data to the specified address DS1307
data byte ds_read( address ) - reads 1 byte of data from the specified address DS1307
ds_off()- turn off DS1307
ds_on()- enable DS1307
ds_init()- initialization DS1307
byte IntToBoolInt( byte ) - a function for converting a number to binary-decimal form

During initialization, the following bits are checked and set if the following bits are off: the bit responsible for the 24-hour clock operation mode and the bit responsible for the clock on state. 2 functions have been implemented to enable and disable the clock. The DS1307 can send and receive both single-byte and multi-byte transmissions, but to simplify the operation of the clock, the functions for reading and writing are only single-byte. To set the clock, there is also a function for converting the usual decimal representation of a number into binary decimal, in which the microcircuit stores time indicators. The given functions for working with the clock are quite enough.

The firmware implements functions for reading and displaying the time - time(), dates - date(). In an infinite loop at some time intervals, these functions are called to display the time and date on the display. Let's consider how the function for reading with the subsequent output of the current time is arranged:

Void time() ( unsigned char i; SetLCDPosition(1, 0); i=ds_read(0x02); buffer = i/16+"0"; buffer = i%16+"0"; buffer = ":"; i =ds_read(0x01); buffer = i/16+"0"; buffer = i%16+"0"; buffer = ":"; i=ds_read(0x00); buffer = i/16+"0"; buffer = i%16+"0"; buffer = "\0"; ShowStr(buffer); )

The cursor is positioned on the display. We read the value of the register responsible for the hour and half a byte, because the data is stored in binary-decimal form, we write it to the buffer. Next, add a separator in the form of a colon. We read and write to the buffer in the same way the values ​​of minutes and seconds. We display the contents of the buffer on the display. The function for displaying the current date is arranged in the same way.

The firmware has a function to set the hours and minutes - set_time(). This function sets the time with one button. How to do it: press the button - the display shows the inscription "Set hour:" and the number of hours, increase the hour by short pressing the button; having set the hour with a long press, we move on to setting the minutes, as evidenced by the inscription “Set min:”, set the minutes in the same way, and with a long press we return to the endless cycle to the hours. But since this function is large, we will give only one line from it, which writes the value of minutes to DS1307:

Ds_write(0x02,IntToBoolInt(time));

We write to the register that corresponds to the minutes the desired value, previously reduced to binary-decimal form.

Calculation of real time in seconds, minutes, hours, dates of the month, months, days of the week and years, taking into account the highness of the current year up to 2100.

56 bytes non-volatile RAM for data storage

2-wire serial interface

Programmable square wave generator. Can output 1Hz, 4.096kHz, 8.192kHz and 32.768kHz.

Automatic detection of main power failure and connection of a backup

24 hour and 12 hour mode

Consumption less than 500 nA when powered by a backup battery at a temperature of 25C°

The microcircuit is available in eight-pin DIP and SOIC packages. The pinout is the same for everyone. Next, I will give the lines from the datasheet for completeness.

Microchip documentation (datasheet)

Pin assignment:

. X1, X2- Used to connect a 32.768 kHz quartz resonator

. vbat- Input for any standard 3V lithium battery or other power source. For normal operation DS1307 requires battery voltage to be between 2.0...3.5V. lithium battery with a capacity of 48 mAh or more when no power will support DS1307 in
for more than 10 years at 25°C.

. GND- overall disadvantage

. Vcc- This is +5V input. When the supply voltage is higher than 1.25 * VBAT, the device is fully accessible, and data can be read and written. When a 3V battery is connected to the device, and Vcc is lower than 1.25 * VBAT, reading and writing are prohibited, but the timing function continues to work. As soon as Vcc falls below VBAT, the RAM and RTC switch to battery-powered VBAT.

. SQW/OUT- Output signal with rectangular pulses.

. SCL- (Serial Clock Input - serial clock input) - used to synchronize data via the serial interface.

. SDA- (Serial Data Input/Output - input/output of serial data) - input/output pin for a two-wire serial interface.

Working with SQW/OUT pin.

First, consider the structure of the DS1307 registers.

The structure of the registers of the DS1307 microcircuit

We are interested in the "Control register" located at 0x7, because. it determines the operation of the SQW/OUT output.

If the SQWE bit = 1, then the formation of rectangular pulses begins, if SQWE = 0, then the output will be the value of the OUT bit.

The RS0 and RS1 bits are responsible for the pulse frequency, namely:

RS0 RS1 Frequency
0 0 1 Hz
0 1 4.096 kHz
1 0 8.192 kHz
1 1 32.768 kHz

Here's an example:

If we need to start forming rectangular pulses with a frequency of 1 Hz, then we need to send the byte 00010000 or 0x10 in hexadecimal to the 0x7 register of the microcircuit, which has address 0x68.

Using the Library Wire.h, It can be done in the following way:

wire.beginTransmission(0x68); wire.write(0x7); wire.write(0x10); Wire.endTransmission();

Connection to Arduino:

The pins responsible for the I2C interface on Arduino boards based on different controllers vary.

Required libraries:

to work with DS1307: http://www.pjrc.com/teensy/td_libs_DS1307RTC.html
for working with time: http://www.pjrc.com/teensy/td_libs_Time.html

Time setting

. Manually in code

The time is set manually in the program code and uploaded to the Arduino board. This method not the most accurate Compilation and download times may vary.

Program code example

#include #include void setup () { Serial.begin(9600); while (! Serial ) ; // Leonardo board only // get time from RTC Serial //synchronization failed else Serial.println("RTC has set the system time" ); //set manually 16.02.2016 12:53 TimeElements te; te.Second = 0; //seconds te.Minute = 53; //minutes te.Hour = 12; //hours te.Day = 16; //day te.Month = 2; // month te.Year = 2016 - 1970; //the year in the library is counted from 1970 time_t timeVal = makeTime(te); RTC.set(timeVal); setTime(timeVal); ) void loop() ( digitalClockDisplay(); //output time delay (1000); ) void digitalClockDisplay() ( Serial Serial.print(" "); Serial.print(day()); Serial.print(" "); Serial.print(month()); Serial.print(" "); Serial.print(year()); Serial //output time through ":" Serial.print(":"); if (digits< 10) Serial.print("0"); Serial.print(digits); )

. Installation from"Port Monitor"

More accurate time setting. The time is set through the "port monitor" during the controller operation.

We open the monitor, enter the data in the required format, look at the reference clock, catch the moment and click "send".

Program code example

// format for indicating the current time "DD.MM.YY hh:mm:ss" //where DD - day, MM - month, YY - year, hh - hours, mm - minutes, ss - seconds //YY - from 00 to 99 for 2000-2099#include #include bool isTimeSet = false ; //flag indicating if the date has already been set void setup () { Serial.begin(9600); while (! Serial ) ; // Leonardo board only setSyncProvider(RTC.get); // get time from RTC if (timeStatus() != timeSet) Serial.println("Unable to sync with the RTC" ); //synchronization failed else Serial.println("RTC has set the system time" ); ) void loop() ( if ( Serial.available()) ( //command received with time setTimeFromFormatString( Serial.readStringUntil("\n" )); isTimeSet = true ; //date has been set) if (isTimeSet) //if date was set( digitalClockDisplay(); // time display ) delay (1000); ) void digitalClockDisplay() ( Serial.print(hour()); printDigits(minute()); printDigits(second()); Serial.print(" "); Serial.print(day()); Serial.print(" "); Serial.print(month()); Serial.print(" "); Serial.print(year()); Serial.println(); ) void printDigits(int digits) ( //output time through ":" Serial.print(":"); if (digits< 10) Serial.print("0"); Serial.print(digits); ) void setTimeFromFormatString(String time) ( //DD.MM.YY hh:mm:ss int day = time.substring(0, 2).toInt(); int month = time.substring(3, 5).toInt(); int year = time.substring(6, 8).toInt(); int hours = time.substring(9, 11).toInt(); int minutes = time.substring(12, 14).toInt(); int seconds = time.substring(15, 17).toInt(); TimeElements te; te.Second = seconds; te.Minute = minutes; te.Hour = hours; te.Day = day ; te.Month = month ; te.Year = year + 30; //the year in the library is counted from 1970. We want from 2000 time_t timeVal = makeTime(te); RTC.set(timeVal); setTime(timeVal); )

The DS1307 Serial Real Time Clock is a low power full BCD calendar clock that includes 56 bytes of non-volatile SRAM. Addresses and data are transferred sequentially over a two-wire, bi-directional bus. Clock-calendar counts seconds, minutes, hours, day, date, month and year. The last date of the month is automatically adjusted for months with less than 31 days, including leap year correction. The clock works in both 24-hour and 12-hour modes with an AM/PM indicator. The DS1307 has a built-in power monitoring circuit that detects power outages and automatically switches to battery power.

Microchip work.

DS1307 works as a slave on the serial bus. It is accessed by setting the START condition and sending the device an identification code followed by a register address. The registers following it are accessed sequentially until the STOP condition is met.
If V CC falls below 1.25*V BAT, DS1307 interrupts the access process and resets the address counter, and at this time external signals are not accepted (to prevent erroneous data from being written).
If V CC falls below V BAT, DS1307 switches to low-current battery backup mode.
On power up, the DS1307 switches from battery to Vcc when Vcc exceeds V BAT + 0.2 V. Incoming signals are accepted when Vcc exceeds 1.25*V BAT.
Download Russian description Downloaded 3077 times

Download original documentation