Oct-23rd-2009

Interfacing DS1307 RTC Chip with AVR Microcontroller


Real Time Clocks, as the name suggests are clock modules. They are available as integrated circuits (ICs) and manages timing like a clock. Some RTC ICs also manages date like a calendar. The main advantage is that they have a system of battery backup which keeps the clock/ca lender running even in case of power failure. A very small current is required for keeping the RTC alive. This in most case is provided by a miniature 3v lithium coin cell. So even if the embedded system with RTC is powered off the RTC module is up and running by the backup cell. This same technique is used in PC timing also. If you have opened your computer case you will notice a small coin cell in the mother board.

In this tutorial we will learn to use a very famous RTC IC named DS1307. The DS1307 is described in the datasheet as follows

The DS1307 is a low-power clock/calendar with 56 bytes of battery-backed SRAM. The clock/calendar provides seconds, minutes, hours, day, date, month, and year information. The date at the end of the month is automatically adjusted for months with fewer than 31 days, including corrections for leap year. The DS1307 operates as a slave device on the I2C bus.

So the aim of the project will be to access the DS1307 registers, read time

  • Access the DS1307 registers i.e. read/write data to/from the DS1307 IC
  • Format the read data and display in LCD
  • Ability to get time from user and store it to DS1307. This provide means to setup the RTC module with correct time.

DS1307 Internal Registers

From software point of view the DS1307 is just a collection of some 8 bit registers. You can read these register to obtain the current time and date. You can also modify them to hold the correct time. After that the DS1307 keeps then updated with current date and time. The following registers are there.

ADDRESS BIT7 BIT6 BIT5 BIT4 BIT3 BIT2 BIT1 BIT0 FUNCTION RANGE
00H CH
10 SECONDS
SECOND
SECOND
00-59
01H
0
10 MINUTES
MINUTES
MINUTES
00-59
02H
0
12
10HR
10HR
HOUR
HOUR

1-12+AM/PM OR
00-23

24
am/pm
03H
0
0
0
0
0
DAY
DAY
01-07
04H
0
0
10 DATE
DATE
DATE
01-31
05H
0
0
0
10MONTH
MONTH
MONTH
01-12
06H
10 YEAR
YEAR
YEAR
00-99
07H

TO KEEP THINGS SIMPLE I HAVE SKIPPED THE CONTROL REGISTER

THIS IS USED FOR SQUARE WAVE GENERATION ON PIN7

08-3FH                 56 BYTE RAM 00h-FFh

The register uses BCD (Binary Coded Decimal) for storing the values. For example take register at address 01h, it stores the MINUTES. Say it is 37 minutes. Then it will be stored as follows.

DS1307 Register format is BCD

Fig. : BCD Format in DS1307 Registers.

The DS1307.c and DS1307.h provide easy access to the registers. I have provided just two functions that allows you to read and write the DS1307 registers.

/***************************************************

Function To Read Internal Registers of DS1307
---------------------------------------------

address : Address of the register
data: value of register is copied to this.


Returns:
0= Failure
1= Success
***************************************************/

uint8_t DS1307Read(uint8_t address,uint8_t *data)


/*************************************************** Function To Write Internal Registers of DS1307 --------------------------------------------- address : Address of the register data: value to write. Returns: 0= Failure 1= Success ***************************************************/ uint8_t DS1307Write(uint8_t address,uint8_t data)

These functions depends on the I2C library. The I2C (Inter IC Communication) is a popular communication protocol between ICs. The DS1307 and our AVR ATmega8 communicates using the I2C bus. I will give more details on I2C in a separate tutorial.

A Simple RTC Module

The DS1307 require an 32.768KHz crystal, a 3v lithium battery and 2 pull up registers to function. So I will make a small PCB that will hold all these. The image of module is shown below. The module can be connected to development boards using female-female burg wires.

DS1307 RCT Module with lithium cell

Fig. : A Simple DS1307 RTC Module.

 

DS1307 RTC Module Schematic for interface with PIC/AVR MCUs

Fig. :DS1307 RTC Module Circuit Diagram.

Once you have the RTC Module ready you can connect it with your favorite MCU like PIC or AVR or any other MCU. In this tutorial I will connect it with AVR ATmega8 MCU, I will also interface it with PIC MCUs latter on.

AVR ATmega8, DS1307 RTC Interface Example with LCD Module

To make a complete usable example we will connect a 16x2 LCD Module, and 3 push buttons. The detailed circuit diagram is given below.

AVR ATmega8 interface with DS1307 RTC

Fig. :AVR ATmega8 RTC Interface Circuit Diagram.

avr-gcc software

The full software for the example is written in C language and compiled with avr-gcc. The whole software is very modular. Following software modules are used.

  • LCD Interface modules for handling the display device. More detail is given on these pages.
  • Low Level I2C Interface Library. This handles the data communication using the hardware I2C module present inside AVR/PIC MCUs.
    • For Atmel AVR MCUs (Yet to be written)
    • For PIC16 MCUs.(Yet to be written)
    • For PIC18 MCUs.(Yet to be written)
  • DS1307 Module : This module built on top of above I2C module help in reading/writing data to and from the DS1307 chip. Functions are very simple and documented inside the .c and .h files itself.
  • The main application module RTC.c is the application software that uses the above modules to communicate with both the LCD and DS1307 chip. It also manages the handling of UI (User Interface) by the help of 3 push buttons.

Fabrication Instructions

Assemble the circuits according to the circuit diagrams shown above. Burn the hex file (download link given at the end of article) to an ATmega8 using a suitable programmer. Set the fuse byte as follows LOW=21 HEX HIGH=D9 HEX . Apply power to the circuit and adjust the LCD Contrast Pot until the display is clear. The initial time should be shown as 00:00:00. Now press the "menu" key to enter the main menu. Use the LEFT and RIGHT Key to move between options and ENTER to select an item. The main menu has the following options.

  • Set Time
  • Set On Time (NOT IMPLEMENTED YET)
  • Set Off Time (NOT IMPLEMENTED YET)
  • Quit
avr rtc main menu

Fig. : The Main Menu.

Go to the "Set Time" option, the following UI will be displayed.

Fig. : Setting the time.

Use the "Move Sel" key to move between Hour,Minute,Second,AM/PM, and <OK>. Use the "Increase"/"Decrease" buttons to adjust value. Finally go to <OK> and press any key. A message will be shown, "Main Time Set". The main menu will return. Select "Quit" from the main menu and the main screen showing the current time will be displayed. Now the RTC is setup, it will keep the time even if you switch off the circuit. Next the you power up the circuit it will still show the REAL time!

DS1307 rtc example main screen

Fig. : DS1307 RTC Example Main Screen.

Downloads

A Request From Readers

If you find this article useful or have any doubts or want to share your valuable suggestions, please leave a comment or two ! I would be glad to hear from you.

-The Author

Avinash Gupta

Videos

The ATmega8 DS1307 RTC Interface example in action.


17 Responses to “Interfacing DS1307 RTC Chip with AVR Microcontroller”

  1. 1
    Kenneth Finnegan Says:

    I just finished my first project using the DS1307, and I appreciate your idea of building the complete module on perf board. I think I might go back and do that… :-)

    There is a way around needing the pull-up resistors on the clock module (at least with an ATMEGA168): Set the SCL and SDA lines high, which enables pull-up resistors inside the controller. I only know how to do this in the Arduino environment, but I do know that it’s possible.

    I also used the SRAM, which was super convenient for when I wanted to be able to reset the atmega, but be able to pick up from where I left off.

    http://kennethfinnegan.blogspot.com/2009/10/arduino-temperature-logger.html

  2. 2
    foxit Says:

    I can not simulate this circuit in Proteus. It does not work.
    I don`t understand why. Please? help.

  3. 3
    AVR Micro Says:

    This is an excellent article! Detailed description suitable also for beginners. I will not build this project but I enjoyed a lot reading it.

  4. 4
    Anthony Says:

    Hi Avinash
    This is my favourite Chip (DS1307)
    I know it pretty Good

    I give a Lib for my friend
    for BCD->BIN
    *sec = ((*sec & 0xF0) >> 4)*10 + (*sec & 0×0F);
    *mnt = ((*mnt & 0xF0) >> 4)*10 + (*mnt & 0×0F);
    *hr = ((*hr & 0xF0) >> 4)*10 + (*hr & 0×0F);
    *day = ((*day & 0xF0) >> 4)*10 + (*day & 0×0F);
    *year = ((*year & 0xF0) >> 4)*10 + (*year & 0×0F);
    *date = ((*date & 0xF0) >> 4)*10 + (*date & 0×0F);
    *mn = ((*mn & 0xF0) >> 4)*10 + (*mn & 0×0F);

    for BIN->BCD
    _I2C_write(((sec/10)<<4) + (sec%10));
    _I2C_write(((min/10)<<4) + (min%10));
    _I2C_write(((hour/10)<<4) + (hour%10));

    ///////////////////////////////////////////////////////////

    ////Read Ram
    unsigned char rtc_read(unsigned char address_)
    {
    unsigned char data_;
    _i2c_start();
    _i2c_write(0xd0);
    _i2c_write(address_);
    _i2c_start();
    _i2c_write(0xd1);
    data=_i2c_read(0);
    _i2c_stop();
    return data_;
    }

    ///
    void rtc_write(unsigned char address,unsigned char data)
    {
    _i2c_start();
    _i2c_write(0xd0);
    _i2c_write(address);
    _i2c_write(data);
    _i2c_stop();
    }

    void rtc_init(unsigned char rs,unsigned char sqwe,unsigned char out)
    {
    rs&=3;
    if (sqwe) rs|=0×10;
    if (out) rs|=0×80;
    _i2c_start();
    _i2c_write(0xd0);
    _i2c_write(7);
    _i2c_write(rs);
    _i2c_stop();
    }

    void rtc_get_time(unsigned char *hour,unsigned char *min,unsigned char *sec)
    {
    _i2c_start();
    _i2c_write(0xd0);
    _i2c_write(0);
    _i2c_start();
    _i2c_write(0xd1);
    *sec=bcd2bin(_i2c_read(1));
    *min=bcd2bin(_i2c_read(1));
    *hour=bcd2bin(_i2c_read(0));
    _i2c_stop();
    }

    void rtc_set_time(unsigned char hour,unsigned char min,unsigned char sec)
    {
    _i2c_start();
    _i2c_write(0xd0);
    _i2c_write(0);
    _i2c_write(bin2bcd(sec));
    _i2c_write(bin2bcd(min));
    _i2c_write(bin2bcd(hour));
    _i2c_stop();
    }

    void rtc_get_date(unsigned char *date,unsigned char *month,unsigned char *year)
    {
    _i2c_start();
    _i2c_write(0xd0);
    _i2c_write(4);
    _i2c_start();
    _i2c_write(0xd1);
    *date=bcd2bin(_i2c_read(1));
    *month=bcd2bin(_i2c_read(1));
    *year=bcd2bin(_i2c_read(0));
    _i2c_stop();
    }

    void rtc_set_date(unsigned char date,unsigned char month,unsigned char year)
    {
    _i2c_start();
    _i2c_write(0xd0);
    _i2c_write(4);
    _i2c_write(bin2bcd(date));
    _i2c_write(bin2bcd(month));
    _i2c_write(bin2bcd(year));
    _i2c_stop();
    }

  5. 5
    myway Says:

    anyone using SW I2C on other pins like scl and sda, i need simple function for i2c_write, i2c_start, i2c_read??
    thanks for help

  6. 6
    Praful Says:

    Dear Sir,
    I made a clock as per your design and used a hex file given by you but it just shows a cursor blinking on lcd and nothing else .
    I like this project and i want to do this but ………..
    Please help to solve this ……………
    Thanking You……………
    Praful
    09881303008

  7. 7
    Avinash Says:

    @Praful

    When I published this project (or any other) I took GREAT CARE and try to give as much information as possible to SUCCESSFULLY make the project. I feel really pity at you that u could not make it :( May be some people are really too low on patience to ask at once that the thing is not working. The project is already a kind of like SPOON FEEDING a baby. I can’t do more than this.

    • Check the fuse bits
    • Check pull up resistor on SDA and SCL pins
    • If u don’t have enough knowledge please don’t try to be over smart and change/modify circuit and/or replace(with other value or equivalent) or remove componets

  8. 8
    gaurav roy Says:

    dude.please complete the rf communication between microcontrollers.still waiting for that………….

  9. 9
    Mathivanan Says:

    Great!!! Thanks…. Fully Explained ….Very nice Comments…

  10. 10
    kashif ali Says:

    quiet brief stuff, nicely explained..!!

  11. 11
    kunal Says:

    hi avinash, can you help me in interfacing atmega8 with PT2258. basicaly it’s a hometheatre project.
    thanks in advance.

  12. 12
    Ravi Kiran Says:

    Hi Avinash,

    I feel that there is a bug in the circuit that you have given.
    In the first image(in DS1307 Circuit), it is given that the SCL pin to be connected to the SDA pin of the MCU and SDA to SCL of the MCU. But the SCL pin of an I2C device should be connected to the SCL pin of any other I2C Device. I think this is a bug and please verify the same…
    Awaiting reply…..

    Thank You

  13. 13
    nazat shaikh Says:

    hi,
    I made a project only to read DS1307 after every 1sec and for that i took your code as a reference. I checked the hardware & everything is OK, but the RTC update the time only once.Please reply…..
    thank you

  14. 14
    alex Says:

    I made this circuit and code in proteus for simulate it, but I can not do it. I shall apreciate if someone can send me a file in proteus. and other question is why there are many code windows when I opened in avrStudio 4?, it can simulate or I need to add every code windows? please help me, sorry I’m novice, but I’ll try to do it. thanks a lot

  15. 15
    Manas Paul Says:

    Dear Avinash Sir,
    This program is too good.This is my first AVR success program and LCD display program.Sir how I develop the 128×64 LCD display.Give the circuit diagram with program.I am also a customer of AVR kit.Thanks again.

  16. 16
    parag Says:

    hello sir,
    i am working on a project using PIC 16F877. can u help me for writing code for interfacing DS1307 with PIC using instructions only and not in c-language.
    please reply…
    thank u.

  17. 17
    Tifany Wiebusch Says:

    I go along with you actually, I believe! Might this become doable for you to have your blog translated directly into Russian? English is actually my own 2nd language.

Leave a Reply

Comments

    • Del Chann: Hello is it possible to use this board to interface with a smoke sensor, motion sensor,...
    • Elijah Nicolia: May I consider part regarding your main guide to my personal site
    • Tifany Wiebusch: I go along with you actually, I believe! Might this become doable for you to have...
    • Sinopteek: When i try to run this software under OpenSuSe 11.2 (x64), i’ll have next error:...
    • kapil: @Dhananjay I used that its working and it can programme 3 to 4 times after that there is a...
    • Dhananjay: Sir, At present I am using progisp to flash AT89SXX with usbasp(with modified firmware)....
    • Shashi Jain: plz dont fight wid each other…k i accept my fault… neway m not a rich person...

Video