Page 1 of 2

DS1307 RTC

Posted: Tue Jul 05, 2011 9:04 pm
by JohnCrow
DS 1307 Real Time Clock Tutorial

The new double summer issue (2011) of “Elektor “ as always has a good selection of small interesting circuits.
One that caught my eye was for a real time clock that can be linked to a Microcontroller.

A couple of IC’s were ordered along with the relevant crystal, and the it was time to study the data sheet.

The datasheet , like most datasheets can be somewhat cryptic, so a search of the Matrix forums for more information and ideas was begun.

A lot of information was found to be available, but somewhat spread over many postings.
This tutorial is the consolidated results of my finding.

Hardware needed :

EB006 Multi-programmer - Standard configuration with a PIC 16F877A
EB005 LCD Display
EB016 Protoboard


DS1307 RTC
Crystal 32.768 kHz - For the RTC
Jumper Wires
10k-ohm resistors (2)
100nF Capacitor
CR2032 Lithium Battery & Holder


I will present this tutorial in 2 parts. Programming the data, and reading the data back.

PART 1 Programming the RTC

The flowchart posted by DAN81 is the initial basis of my experiments, as I found this program worked correctly and after some study I understood what it was trying to do.

This is a link to Dan81’s original

http://www.matrixmultimedia.com/mmforum ... rtc#p18528


This is a link to the DS1307 Data Sheet

http://www.maxim-ic.com/datasheet/index.mvp/id/2688

A similar circuit to the elektor one can be found in the data sheet.



The DS1307RTC operates using the I2C protocol.

I2C Bus Connection.

DS 1307 Pin 5 = SDA To PIC PORT C bit 4
DS 1307 Pin 6 = SCL T0 PIC PORT C bit 3

Note both these lines need a pull up resistor connected to 5V

Battery Backup.

A 3V lithium button cell is connected between Pin 3 V-Bat and ground
If battery backup is not needed Pin 3 V-Bat must be connected to ground.


Flowcode Programming.

The I2C protocol is built into Flowcode, so the following will show how to setup the device to program with the current time and date.

The calculation box in the flowchart

RTC = 0x68 Base address
RTC_W = ( RTC << 1 ) + 0 This adds the direction bit to set to write. = 0xD0

This sets up the variables. The numbers can be changed to suit.

Hour = 0x19
Minute = 0x25
Second = 0x00
Day = 0x03
Date = 0x05
Month = 0x07
Year = 0x11

This sets up the day letter shown on the display. These changed automatically once the clock passes through midnight.

Weekday[1] = 'S'
Weekday[2] = 'M'
Weekday[3] = 'T'
Weekday[4] = 'W'
Weekday[5] = 'T'
Weekday[6] = 'F'
Weekday[7] = 'S'

The days can be moved round so Monday is day 1 if preferred, all the DS1307 sees is the number. The letter is added by the PIC program.

First The I2C component needs to be added to the form.

The first macro needs to be MI2C Init - This is placed in MAIN
This will initialise the I2C bus.

Place this early on near the start of the flowchart before any loops etc.

The rest of the commands are in the Setup_Clock macro.

First we have to set up the section of the flowchart that will perform the actual write operations.

The MI2C Start Needs to be the first macro in the list.

The address is calculated as follow
The 7bit base address of the DS1307 is
Binary = 1101000
Hex = 0x68

This needs to be transmitted followed by the direction bit (0 for write 1 for read)

This makes the overall address

Binary = 11010000
Hex = 0xD0

MI2C Transmit Byte This sets the address of the DS1307 and puts it in to write mode
The program uses the variable already setup RTC_W, though 0xD0 could also be used.



MI2C Transmit Byte This sets the first timekeeper register
Data(Byte) = 0

We then enter each parameter in the order sec/min/hour/day number/date/month/year
By using the following method.

MI2C Transmit Byte
Data(Byte) = seconds

MI2C Transmit Byte
Data(Byte) = minutes

And so on as once each parameter has been programmed the next one is selected.

The final parameter being the year value

MI2C Transmit Byte
Data(Byte) = year

Finally we send the stop command
MI2C Stop

This will program the clock with the following


Time = 19:25:00
Date = T 05:07:11

It is possible to program the device to use 12 hour clock and AM/PM indicators. This is slightly more advanced could be looked at later.

Please comment if points are not clear and I will try to improve on it.

First Prototype
First Prototype
DS1307RTC.jpg (77.07 KiB) Viewed 264234 times
Note no backup battery as the CR2032 holder has not arrived yet :(
DS1307 RTC Programmer.fcf
(10.5 KiB) Downloaded 6686 times
PART 2 Will cover reading the data back from the RTC

Re: DS1307 RTC

Posted: Wed Jul 06, 2011 3:54 pm
by Dan81
Hello John

Hour = 0x19
.......
Year = 0x11


Registers are coded in BCD (not binary) .
http://en.wikipedia.org/wiki/Binary-coded_decimal

In your case : the time is 19 (7pm) it must be written 0001 1001 = 0x19.
(dont write binary : 0001 0011 = 16 + 3 = 19)
When you want to write (or read) a register you must do a conversion from decimal to BCD.


Daniel

Re: DS1307 RTC

Posted: Wed Jul 06, 2011 6:58 pm
by JohnCrow
Hi Dan
Thanks for the comments.

I see how it works using BCD, I have just tried programming my chip using BCD values and it works.

But when I looked at your flowchat I saw you had used the actual numeric value but prefixed by 0x i.e in hex

Had not realised until now (just done some quick sums so think im right in saying) that using the actual time or date I need but prefix with 0x is seen by the DS1307 as BCD. :? :roll:

Re: DS1307 RTC

Posted: Sat Jul 09, 2011 7:44 pm
by JohnCrow
The prototype RTC has now been transfered to a EB-017 Patch Board

The slide switch near the Lithium battery is to switch the battery out of circuit when not needed. This conects Pin 3 on the DS1307 to ground.
The RTC will still function in this mode, as long as the circuit is powered, but if the power is removed, the RTC will loose it settings.

A couple of capacitors are placed between the 5V and ground buses.

Pin 5 = SDA
Pin 6 = SCL
Pin 7 = SQW
These can be patched to the relevant pins on the processor using jumbers
These lines have 10k-ohm pullup resistors to the 5V line.

The 3 push switches are available if a set of switches are needed for the application the RTC is used for.

Again these can be patched using jumpers.
Circuit Diagram
Circuit Diagram
Circuit Diagram.gif (6.43 KiB) Viewed 264130 times
DS1307 RTC E-Block
DS1307 RTC E-Block
Real Time Clock.jpg (90.12 KiB) Viewed 264149 times

Re: DS1307 RTC

Posted: Sun Jul 10, 2011 11:29 am
by JohnCrow
Part 2
Reading Time From The RTC

Once the DS1307 RTC IC has been programmed as in Part 1 it will assuming the battery is still good, retain the setings for upto 10 years (The device takes a maximum of 500nA)
Again, I have used the program posted by Dan81 and as the basis for this I have cut the program down to just read back the time data , i.e. seconds, minutes, hours.
These again are my notes while trying to understand how the device works.
Before the read cycle starts the device is addressed as a write

Start
Tx_Byte RTC_W
Tx_Byte 0
Restart

The read cycle then continues as below.

Tx_Byte RTC_R

Rx_Byte
Last(Byte) 0
Return Value Reg_Seconds

Rx_Byte
Last (Byte) 0
Return Value Reg_Minutes

Rx_Byte
Last(Byte) 1 Set to 1 to return "Not Acknowledge" this ends the read cycle
Return Value Reg_Hour

Once the data has been read back the values are still in BCD format and need to be converted to decimal.
This is done as follows.


Actual time read is 16 Seconds, 32 Minutes, 15 Hours. (They are read in this order)
The calculation back to decimal is done as follows

16 Seconds = 22 (BCD) = 0001 0110

Var1 = Reg_second AND 0x0F
0001 0110
0000 1111 & (= 0x0F)
0000 0110 = 6

Var2 = ( Reg_second >> 4 ) AND 0x07
0001 0110 >>4 = 0001 (Shifted right 4 places) = 0000 0001 (The least significant 4 bits are discarded)

0000 0001
0000 0111 & (0x07)
0000 0001 = 1

Second = Var1 + ( Var2 * 10 )
6 + (1*10) = 16

Minutes & Hours are calculated in a similar way.
Var1 = Reg_Minute AND 0x0F
Var2 = ( Reg_Minute >> 4 ) AND 0x07
Minute = Var1 + ( Var2 * 10 )
Var1 = Reg_Hour AND 0x0F
Var2 = ( Reg_Hour >> 4 ) AND 0x03
Hour = Var1 + ( Var2 * 10 )

The Display Time macro simply prints the data to the LCD. Where a value is less than 10 , it is prefixed with a zero. This is simply to make all 3 sets of values double digit.
DS1307 - Read Full Time Data.fcf
Read Time Data
(11.5 KiB) Downloaded 6639 times

Re: DS1307 RTC

Posted: Sun Jul 10, 2011 6:10 pm
by JohnCrow
Part 3
Reading Date From The RTC

This is performed in the same way as reading the time

Start
Tx_Byte RTC_W
Tx_Byte 0
Restart

The read cycle then continues as below.

Tx_Byte RTC_R
Rx_Byte
Last(Byte) 3 Sets pointer to register 3 (DAY)
Return Value DAY

Rx_Byte
Last (Byte) 0
Return Value Reg_Date

Rx_Byte
Last (Byte) 0
Return Value Reg_Month

Rx_Byte
Last(Byte) 1 Set to 1 to return "Not Acknowledge" this ends the read cycle
Return Value Reg_Year

The conversions to decimal are done the same way as for time.
The only extra part is using the array to lookup the Day Letter.

Day Array
Weekday[1] = 'S'
Weekday[2] = 'M'
Weekday[3] = 'T'
Weekday[4] = 'W'
Weekday[5] = 'T'
Weekday[6] = 'F'
Weekday[7] = 'S'

Calculate Date
var1 = Reg_Date AND 0x0F
var2 = (Reg_Date >> 4 ) AND 0x03
Date = var1 + ( var2 * 10 )

Calculate Month
var1 = Reg_Month AND 0x0F
var2 = (Reg_Month >> 4 ) AND 0x01
Month = var1 + ( var2 * 10 )

Calculate Year
var1 = Reg_Year AND 0x0F
var2 = (Reg_Year >> 4 ) AND 0x0F
YEAR = var1 + ( var2 * 10 )
DS1307 - Read Full Date Data.fcf
Read Date Data
(11.5 KiB) Downloaded 6543 times

Re: DS1307 RTC

Posted: Thu Sep 29, 2011 7:18 pm
by JohnCrow
Ive updated the DS1307 RTC Programming software, so it can be entered on the keypad (PORT D)
Once the data has been entered, the program waits for the # key to be pressed before sending the data to the chip.
This way it allows for programming it against a standard time signal or accurate clock.

The data is entered in decimal and converted to BCD before being programmed.

Note
Time is entered in 24 hour clock
Day number starts with Sunday = 1

Re: DS1307 RTC

Posted: Fri Jun 01, 2012 2:27 pm
by JohnCrow
Just built a new version of the hardware.
The circuit is exactly the same as the one above, except its a lot smaller and has wire connections rather than the D-Connector.
Care must be taken with the routing of the data/clock wiring anf not to have the wires too long.

Also i have not fitted a switch to isolate the battery backup. The current draw is in uA so a lithium button cell is still going to last for a long time.
DS1307 RTC V2.JPG
DS1307 RTC V2.JPG (78.1 KiB) Viewed 262949 times
The LHS blue terminals are 5V & Gnd
The RHS blue terminals are SCL & SDA (I2C bus)

Re: DS1307 RTC

Posted: Fri Sep 28, 2012 11:46 pm
by medelec35
Hi John,
As you may of gathered I have a new demo board:
http://www.matrixmultimedia.com/mmforum ... =3&t=11310
I'm creating Flowcharts for all the functions of demo board.
After changing base address to suit RTCC on demo board, your flowchart works a treat!.
Thanks for the great tutorial.

I will be using most of your flowchart when within main Flowchart for the demo board if you don't mind me integrating it?
I will of course credit you for it. :)

Martin

Re: DS1307 RTC

Posted: Sat Sep 29, 2012 9:11 am
by JohnCrow
Hi Martin
Thats fine, use the program as you need to.
Just ordered one myself. Its worth it for the PICkit3 alone, though I do have a PICkit2 anyway.

Re: DS1307 RTC

Posted: Sat Sep 29, 2012 10:31 am
by medelec35
Hi John great tutorial!
Thanks for posting it.

I'm just learning out RTC and I2C
In doing that the one thing I have noticed is to start osc, 7th bit of 1st address (address for seconds) has to 1 or osc will not run so RTC will be stopped.

So for 0 seconds instead of setting to 0, it has to be set to 0x80

Did you find that is the case?

Re: DS1307 RTC

Posted: Sat Sep 29, 2012 10:46 am
by Dan81
Hello Martin

the 8th bit (bit 7) of the "seconds register" is CH (Clock Halt).
It must at "0" if you want that RTC runs.

see datasheet p 8 : CLOCK AND CALENDAR
Bit 7 of Register 0 is the clock halt (CH) bit. When this bit is set to 1, the oscillator is disabled. When cleared to 0, the oscillator is enabled.

I think the CH bit is at "0" when you buy the DS1307. :( (I may be wrong)

Daniel

Re: DS1307 RTC

Posted: Sat Sep 29, 2012 11:18 am
by JohnCrow
Hi
I dont remember having to set that bit with my program, but it was a while ago I did this project.
So as Dan points out it maybe set by default

Re: DS1307 RTC

Posted: Sat Sep 29, 2012 12:24 pm
by medelec35
Thanks for your replies

I have got MCP79410 that's on a demo board.
RTC Datasheet:
http://ww1.microchip.com/downloads/en/D ... 22266D.pdf

I can only get RTC to run on that if bit7 is set to 1.

Ahh I have just notice on the data sheets that the two are different.

on MCP79410 bit 7 has to be 1
on DS1307 bit 7 has to be 0

That's why I got confused.

Today is the fist time I have programmed and used this type of RTC.
So i'm learning :)

Martin

Re: DS1307 RTC

Posted: Mon Oct 01, 2012 11:48 am
by jgu1
Hi John!

Thank´s for the nice project. :D

Maybe a stupid question. I want to hear if I understand your very fine project well.

If I want to use your watch for reading do I need to mix these programs:

Is the adjustment of the time with keyboard :DS1307 RTC Programmer-Keypad Entry Press # To Enter.fcf
and
is the retrieval of data times: DS1307 - Read Full Date Data.fcf

As far I understand

Best regard

Jorgen

Re: DS1307 RTC

Posted: Mon Oct 01, 2012 12:29 pm
by JohnCrow
Hi
DS1307 RTC Programmer-Keypad Entry Press # To Enter.fcf
This program is used to program the DS1307 with the time & date first time it is used.
This is then stored and retained by the backup battery.
DS1307 - Read Full Date Data.fcf
This is used to read the data from the device and display it on the LCD

Re: DS1307 RTC

Posted: Mon Oct 01, 2012 12:34 pm
by Enamul
DS1307 RTC Programmer-Keypad Entry Press # To Enter.fcf
I will post complete RTC code with keypad initial time and date entry option..which will maintain real time in the absence of power with the help of coin battery as John mentioned.

Re: DS1307 RTC

Posted: Tue Oct 02, 2012 1:57 pm
by Enamul
Hi,
I have received couple of requests from different FC users to have RTC program with keypad initial time and date setting option. Finally, I have managed some time to modify the code I develop from John's post to add KEYPAD to set date and time. In the attached program, I am assuming user is going to use coin battery back-up so the clock can retain time and date after power up in case of power cut.

The program is written in this way that it will restrict user to put right time. I mean if user put wrong time or date it will prompt again to put right time and date. Even if leap-year feature is enabled here. Hope everyone will enjoy this. Please get in touch with me if you have any query.

Note: I forgot to mention one important thing I did here. As the user will entry time and date which is generally in decimal or hex in PIC..For example, if anyone enters
TIME:17:12:45
DATE:02/10/12
If the variable the values in hex will be like TIME:11:0C:2D and DATE:02/0A/0C. so the date and time entry will be wrong as we have to send the value user has inputted in decimal need to be sent to DS1307 in hex. That's why I have converted the decimal values to hex before sending.

Re: DS1307 RTC

Posted: Sat Oct 13, 2012 5:32 pm
by Enamul
Hello,
The above RTC with keypad although is very nice to use..but keypad occupies 7 pins of PIC port. In my most of products I use 3 push switch (SET, UP & DOWN) for user interface which consumes only 3 pins but can give same feature of KEYPAD. I am posting RTC program here with same setting feature using just three active low (pin is pulled up by 4.7 K) momentary switches.
This program also restrict user from wrong date or time entry and the date and time entered in decimal is converted to hex like last one. To maintain real-time RTC should have coin battery back-up..Default set time is 00:00:00 and date is 01/01/00 but anyone can change that to any value.
It makes my product quite easy to configure and hope that also helps others :)

Re: DS1307 RTC

Posted: Sat Nov 17, 2012 9:06 am
by Enamul
Hello

I have written a code which will take care British summer time (BST) or day-light saving (DLS) issue automatically. I thought it would be good to post that program here so that everyone looking for RTC can get the idea and use that in their code if they want. Specially John presented this thread so nice that any addition to this thread will make it more better and useful.
To use the code user don't need to do anything except entering the real-time and date in the FIRST_TIME macro..code will do the rest. But for testing whether it is working ok or not..user can test using past time or future time in FIRST_TIME macro to move the clock forward or reverse..to see whether clock works ok in the eve of time change.
British Summer Time(BST)
It is worth to mention the idea of DLS as well so if anyone doesn't know how normally it is done can get some idea.
BST begins at 1:00 AM GMT on the last Sunday of March and ends at 1:00 AM GMT on the last Sunday of October. In 2012, this period was from 25 March to 28 October. In 2013 it will begin on 31 March and end on 27 October.
So if you enter date & time in FIRST_TIME likewise..

Code: Select all

//1=SUNDAY,2=MONDAY,3=TUESDAY,4=WEDNESDAY,
//5=THURSDAY,6=FRIDAY,7=SATURDAY
HOUR = 0x3F AND 0x00
MIN = 0x50
SEC = 0x59
DAY = 0x01
DATE = 0x28
MONTH = 0x10
YEAR = 0x12
so that in display Time:00:50:59 and Date:28/10/2012 SUN
At Time:01:00:01 the clock should return to Time:00:00:01
again if you try following

Code: Select all

//1=SUNDAY,2=MONDAY,3=TUESDAY,4=WEDNESDAY,
//5=THURSDAY,6=FRIDAY,7=SATURDAY
HOUR = 0x3F AND 0x00
MIN = 0x50
SEC = 0x59
DAY = 0x01
DATE = 0x25
MONTH = 0x03
YEAR = 0x12
so that in display Time:00:50:59 and Date:25/03/2012 SUN
At Time:01:00:01 the clock should forward to Time:02:00:01

Edit: I have seen the date is changed in time change but it shouldn't be..I think it is because of BCD issue of DS1307 as I am writing decimal value but should write BCD in DS1307..this is fixed now.

Re: DS1307 RTC

Posted: Sat Nov 17, 2012 10:16 am
by JohnCrow
Will have to give this a try over the weekend

DS1307 RTC for PIC 18F4550

Posted: Wed Mar 27, 2013 2:46 pm
by Siddhartha
HI John

Your tutorial for ds1307 rtc is really helpful for 16f877a. But when I port it on 18f4550 , it prints momentarily garbage and blanks lcd as final output.

Kindly help me to sort this bug.

Re: DS1307 RTC

Posted: Thu Mar 28, 2013 10:30 am
by JohnCrow
Hi
With the 18F4550 (and the 18F4455) the I2C is on Port B

SDA = RB0
SCL = RB1

You will need to connect the RTC device to these pins and move the LCD to another port
Let me know if this sorts it for you, if not Ill try it on my hardware over the weekend.

Re: DS1307 RTC

Posted: Wed Apr 03, 2013 1:45 pm
by Siddhartha
Thanks John

Your suggestion really worked out well for my project.

Re: DS1307 RTC

Posted: Sat Jul 05, 2014 7:37 am
by siwo278
Hello

I'm working on a similar clock, with the possibility of downloading time with DCF77. Decoding the information I have more or less an refined. I only have a problem communicating with RTC DS1307, which in your project is used. My processor is a PIC16F876A clocked at 19.66 MHz, RTC1307 hooked into RC4 SDA and SCL RC3 (of course podciądnięte at 5V using resistors 3300 ohm). In my system it looks so bad that the processor reads data from the RTC by writing such information 45:85:85 45/25/165. Can I ask for help?