Library 15- DS1307 Real Time Clock for STM32F4

In my 15th library, I will show you, how to operate with DS1307 Real Time Clock I2C module from maxim integrated.

DS1307 STM32F4xx resultThe DS1307 serial real-time clock (RTC) is a lowpower, full binary-coded decimal (BCD) clock/calendar plus 56 bytes f NV SRAM. Address and data are transferred serially through an I2C, bidirectional bus. The clock/calendar provides seconds, minutes, hours, day, date, month, and year information. The end of the month date is automatically adjusted for months with fewer than 31 days, including corrections for leap year. The clock operates in either the 24-hour or 12- hour format with AM/PM indicator. The DS1307 has a built-in power-sense circuit that detects power failures and automatically switches to the backup supply. Timekeeping operation continues while the part operates from the backup supply.

I have DS1307 Shield from ebay. They are almost free and you get battery too.

Do not use this library for future projects. Use internal RTC on STM32F4xx instead.

DS1307 features

  • Real time clock
  • Counts seconds, minutes, hours, day in a week, date, month and year
  • I2C interface
  • External oscillator 32.768kHz required
  • Binary-coded numbers
  • Square wave output pin



  • Set and get date and time from DS1307
  • Set/Get date/time from DS1307 separatelly
  • Enable/disable square wave output pin
  • Version 1.1 – July 30, 2014
    • Square wave output pin can be enabled
  • Version 1.2 – September 21, 2014
    • You can now check on iintialization if device is connected


    • STM32F4xx
    • STM32F4xx RCC
    • STM32F4xx GPIO
    • STM32F4xx I2C
  • TM
    • TM DELAY
    • TM I2C
    • defines.h
DS1307 STM32F4xx Description
VCC 5V Positive voltage
GND GND Ground
SDA PB7 I2C1, PinsPack 1
SCL PB6 I2C1, PinsPack 1

In case, you want custom I2C pins, you can set it in defines.h file (for corresponding pins look at my I2C library):

Datetime struct

There is a struct for date and time you are working with. It is used to set and to get time to/from DS1307.

Write date/time

You can write all (date and time) to DS1307 or you can write each thing separatelly.

Read date/time

You can read all (date and time) from DS1307 or you can read each thing separatelly.


DS1307 has one pin, which can be used to output frequency. This frequency can be 1Hz, 4096Hz, 8192Hz or 32768Hz. Also, pin can be set high or low. Pin has open-drain circuit, that means you need external pull up resistor to get pin working properly.

For this purpose I made 2 new functions

To use this functions, you also need enumeration typedef

Why use this pin? If you set this pin to 1Hz, then you can with your software update clock, no need to constantly check DS1307’s registers, because this takes loong time for one STM32F4xx device. Seconds are updated on falling edge of SQW/OUT pin, if it is set to 1Hz output.


Project available on Github, downlaod library here.

TM STM32F4 DS1307 Library

DS1307 External I2C RTC Clock library


Owner of this site. Also electronic enthusiasts, web developer, 3D printer fan, handball player and more. Big fan of STM32F4 devices. In anticipation of the new Discovery board for STM32F7 lines.

You may also like...

Read before commenting!

Before you make a new comment, make sure you agree with things listed below:

  • - Read post to make sure if it is already posted what you are asking for,
  • - Make sure you have the latest version of libraries used in your project,
  • - Make a clean and grammatically correct written message,
  • - Report as many details as possible, including what have you done so far,
  • - Do NOT post any code here. Use Pastebin,
  • - Do NOT post any error codes here. Use Pastebin,
  • - Specify STM32Fxxx family and used Discovery/EVAL/Nucleo or custom made board,
  • - Make sure your clock is set correct for PLL,
  • - If you are using my HAL drivers, please check this post how to start.
Comment will be deleted on breaking these rules without notification!
  • Petr Machala

    Is there a posibbility to somehow wakeup MCU from sleep with external RTC?

    • Yes. Connect SQW/OUT pin to your stm with exti enabled and set frequency for sqw pin.

      But why use external rtc?

      • Petr Machala

        I wanted to have a small baterry to power only the RTC to ensure that the RTC configuration is not lost if there is no power source…like in a PC…and I believe that this is imposssible on 32F429I board due the wiring of the borad…but by waking up I ment like once in an hour not 4096 times a sec 🙂

        • Im sure that vbat pin has jumper on board which you can remove (0ohm resistor) and connect external battery to this pin.
          Then you have separated rtc power and flexible wakeup options.

          • Petr Machala

            You mean R52?

          • Might be. Dont have schematic here.

          • Tia

            Can I change the DS1307 into RTC DS3231? some day ago I try it with AT-Mega8 from Atmel and it can work good. Can I do the same in ARM STM32f4 with external RTC? thanks

          • If worked then, you have hange it will work again.

          • Tia

            Thanks for your quick respons, but I still get error. When I uncomment the while(1), the data is nothing I get. but if I comment the while(1), I get the data when I show it in the serial PC. ;

            Day: 1Date: 01Month: 01Year: 2001Hours: 01Minutes: 01Seconds: 01Day: 1Date: 01Month: 01Year: 2001Hours: 01Minutes: 01Seconds: 01Day: 1Date: 01Month: 01Year: 2001Hours: 01Minutes: 01Seconds: 01Day: 1Date: 01Month: 01Year: 2001Hours: 01Minutes: 01Seconds: 01Day: 1Date: 01Month: 01Year: 2001Hours: 01Minutes: 01Seconds: 01Day: 1

            what should I do?

          • Tia

            I used DS1307

          • Petr Machala

            But in general…if I want to wakeup MCU in a long term way (like I wrote once an hour) the only possibility is only internal RTC right?

          • Yes, but I think that 1 hour interval is not possible. It is very big interval.

            But you can use rtc alarm, set clock for one hour from now, when alarm happen, read rtc, set new alarm time and do your stuff.

          • Petr Machala

            Thanks for your help…I like more the external RTC but this waking up after long periods of time is very important to me si internal is my only choice…

  • abdurrahman korkmaz

    i used stm32f429 discovery and this example gives “ds1307 error”..please why?

    • Check I2C connection, check if your RTC module has VCC power.
      You need VCC power for your RTC module if you want to communicate with it. Battery is only used for RTC time in module.

      PS: Instead of DS1307 RTC use internal on STM32F4 for future use. Saves space in PCB and works faster.

      • George

        I have the same issue. I have 5V Vcc. The connections to PB6 and PB7 are good. Used 4.7k and 10k resistors for pull-up and no go.tried 3 different crystals as well. It only connected twice.

        • Grounds connected?

          • George

            The grounds are fine. I purchased a new DS1307 and crystal. Connected it for the first time and it worked. When I cycled the power it does not connect again.

  • John Doe

    Hi, trying to add tm_stm32f4_delay.c to a barebones coocox project, and got error below. Any suggestions?


    [cc] arm-none-eabi-gcc -mcpu=cortex-m4 -mthumb -g2 -nostartfiles -Wl, -O0 -Wl,–gc-sections -LC:UsersAmikamAppDataRoamingCooCoxCoIDEconfigurationProgramDataFirstProject -Wl,-TC:UsersAmikamAppDataRoamingCooCoxCoIDEconfigurationProgramDataFirstProject/arm-gcc-link.ld -g -o FirstProject.elf ..objstm32f4xx_gpio.o ..objstartup_stm32f4xx.o ..objstm32f4xx_rcc.o ..objsystem_stm32f4xx.o ..objmain.o ..objtm_stm32f4_delay.o

    [cc] m:/stm/gnu tools arm embedded/4.9-2015q2/bin/../lib/gcc/arm-none-eabi/4.9.3/../../../../arm-none-eabi/lib/armv7e-mlibg.a(lib_a-sbrkr.o): In function _sbrk_r':

    [cc] collect2.exe: error: ld returned 1 exit status

    [cc] sbrkr.c:(.text._sbrk_r+0xc): undefined reference to _sbrk’

    • Search on google for _sbrk implementation, or add syscalls.c file from coocox to your project.

      • John Doe

        Thanks! got it working!

  • Gary

    Hello TM,

    I am using an Abracon AB-RTCMC-32.768kHz-AIGZ-S7 RTC device. As it turns out, the DS1307 and the Abracon are very similar, and I was able to use your DS1307 driver with only a couple of small changes!
    However, something weird is going on, and I’m trying to figure it out, but can’t.
    Instead of seconds incrementing, the minutes are incrementing! I think it’s because the Abracon has a fractional second register at the top (0x00), and the DS1307 does not. I also see that the registers are shifted by 1 up on the Abracon. For example, here are the first 4 registers:

    00h 10th/100th of seconds X X X X X X X X
    01h Seconds 0 X X X X X X X
    02h Minutes 0 X X X X X X X
    03h Hours X X X X X X X X

    I added this as the first value in the time struct:

    uint8_t fracseconds; /*!< 1/10 seconds parameter, from 00 to 99 */
    and changed the address map to match the Abracon, but I think the problem is in the read.

    All other values: Y-M-D-H are Ok – but if I left it running long enough, the hour may change when it's not supposed to, as well.

    Any suggestion as to what I need to change in the reading?


  • Gary

    Hi TM,
    It’s okay, I’ve figured it out. Since the Abracon passes back one additional byte for fractional seconds, I added a new variable to the struct and changed the number of bytes from 7 to 8 on the read.

    Works great!

    • Instead of using external rtc, use internal one. Works faster and has a lot of features. And you don’t need i2c readings and waste time.

      • Gary

        It might be easier, but there’s just no way you’ll get 2ppm from the STM clock. 😎

        • 2pps = 2Hz => T = 0.5s
          Pin should be toggled on T/2 interval =.25s

          RTC wakeuo interrupt and pin toggle in that function.

          No way? 😉
          Have a nice day.

          • Hassine

            hi bro think you so much for this content please i need a help about the vocal recognition with stm32f4 discovery and the library we needed to record the voice thanks

  • Pingback: STM32F411 Nucleo I2C DS3231 1Hz Square Wave with External Interrupt | µC eXperiment()

  • Nguyễn Phúc Anh Đồng

    I can’t never use any of your library. I complied the project without errors but none of your code working. I’m using STM32F407VGT6, I can’t make anything work, even the simple example you provided ( UART, I2C..) . Can you suggest any idea?

    • Entropy

      (just a thought), did you check that your PLL clock settings are correctly configured? for this MCU these should be set to 8,336,2 and 7 respectively as PLL_M. PLL_N, PLL_P and PLL_Q.

      • Correct. Also, make sure that PLL_M must match HSE_VALUE. If HSE_VALUE is 8MHz, then PLL_M is 8 and so on.
        If HSE is not used, PLL_M should be set to 16 for internal HSI clock.

  • vm

    Hello Sir,
    How to print next date and current date from current date or date before or after 1 week from current date using this library ??

  • vm

    Hello Sir,
    How to print next date and current date from current date or date before or after 1 week from current date using this library ??