Introduction: Setting the DS1307 Real Time Clock Using the Serial Monitor

The hardware is the standard setup and is as follows.

SDA of the RTC to pin 4 of the Arduino.
SCL of the RTC to pin 5 of the Arduino

Then of course pos and neg.
Just ignore the gizDuino info in the setup picture. left side of the page.

Complete details of this RTC can be found here.  Just click on Technical Manual on the left side of the page.

Step 1: Code

Copy and past this into the Arduino IDE and burn to the board. For this i am using an ACEDuino that has a ATMega 328P.
To set the date and time is all done is the serial monitor, which is the easiest i have found. 

///////////////////////////////////////////
// RTC data and time setter              //
//                                       //
// This sample program allows the user   //
// to set the date and time of an RTC    //
// using I2C.                            //
//                                       //
// Codes by:                             //
// eGizmo Mechatronix Central            //
// Taft, Manila, Philippines             //
// http://www.egizmo.com                 //
// April 15, 2013                        //
///////////////////////////////////////////

#include <Wire.h>
const int DS1307 = 0x68; // Address of DS1307 see data sheets
const char* days[] =
{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
const char* months[] =
{"January", "February", "March", "April", "May", "June", "July", "August","September", "October", "November", "December"};
 
// Initializes all values: 
byte second = 0;
byte minute = 0;
byte hour = 0;
byte weekday = 0;
byte monthday = 0;
byte month = 0;
byte year = 0;

void setup() {
  Wire.begin();
  Serial.begin(9600);
  delay(2000); // This delay allows the MCU to read the current date and time.
 
  Serial.print("The current date and time is: ");
  printTime();
  Serial.println("Please change to newline ending the settings on the lower right of the Serial Monitor");
  Serial.println("Would you like to set the date and time now? Y/N");
 
  while (!Serial.available()) delay(10);
  if (Serial.read() == 'y' || Serial.read() == 'Y')
 
  // This set of functions allows the user to change the date and time
  {
    Serial.read();
    setTime();
    Serial.print("The current date and time is now: ");
    printTime();
  }
 
 
  Serial.println("Thank you.");
}

// Continuous function for converting bytes to decimals and vice versa
void loop() {
}
byte decToBcd(byte val) {
  return ((val/10*16) + (val%10));
}
byte bcdToDec(byte val) {
  return ((val/16*10) + (val%16));
}


// This set of codes is allows input of data
void setTime() {
  Serial.print("Please enter the current year, 00-99. - ");
  year = readByte();
  Serial.println(year);
  Serial.print("Please enter the current month, 1-12. - ");
  month = readByte();
  Serial.println(months[month-1]);
  Serial.print("Please enter the current day of the month, 1-31. - ");
  monthday = readByte();
  Serial.println(monthday);
  Serial.println("Please enter the current day of the week, 1-7.");
  Serial.print("1 Sun | 2 Mon | 3 Tues | 4 Weds | 5 Thu | 6 Fri | 7 Sat - ");
  weekday = readByte();
  Serial.println(days[weekday-1]);
  Serial.print("Please enter the current hour in 24hr format, 0-23. - ");
  hour = readByte();
  Serial.println(hour);
  Serial.print("Please enter the current minute, 0-59. - ");
  minute = readByte();
  Serial.println(minute);
  second = 0;
  Serial.println("The data has been entered.");
 
  // The following codes transmits the data to the RTC
  Wire.beginTransmission(DS1307);
  Wire.write(byte(0));
  Wire.write(decToBcd(second));
  Wire.write(decToBcd(minute));
  Wire.write(decToBcd(hour));
  Wire.write(decToBcd(weekday));
  Wire.write(decToBcd(monthday));
  Wire.write(decToBcd(month));
  Wire.write(decToBcd(year));
  Wire.write(byte(0));
  Wire.endTransmission();
  // Ends transmission of data
}


byte readByte() {
  while (!Serial.available()) delay(10);
  byte reading = 0;
  byte incomingByte = Serial.read();
  while (incomingByte != '\n') {
    if (incomingByte >= '0' && incomingByte <= '9')
      reading = reading * 10 + (incomingByte - '0');
    else;
    incomingByte = Serial.read();
  }
  Serial.flush();
  return reading;
}


void printTime() {
  char buffer[3];
  const char* AMPM = 0;
  readTime();
  Serial.print(days[weekday-1]);
  Serial.print(" ");
  Serial.print(months[month-1]);
  Serial.print(" ");
  Serial.print(monthday);
  Serial.print(", 20");
  Serial.print(year);
  Serial.print(" ");
  if (hour > 12) {
    hour -= 12;
    AMPM = " PM";
  }
  else AMPM = " AM";
  Serial.print(hour);
  Serial.print(":");
  sprintf(buffer, "%02d", minute);
  Serial.print(buffer);
  Serial.println(AMPM);
}


void readTime() {
  Wire.beginTransmission(DS1307);
  Wire.write(byte(0));
  Wire.endTransmission();
  Wire.requestFrom(DS1307, 7);
  second = bcdToDec(Wire.read());
  minute = bcdToDec(Wire.read());
  hour = bcdToDec(Wire.read());
  weekday = bcdToDec(Wire.read());
  monthday = bcdToDec(Wire.read());
  month = bcdToDec(Wire.read());
  year = bcdToDec(Wire.read());
}

Step 2: Open the Serial Monitor

Open up the serial monitor and this what you will see. The date and time will not be the same but that's OK we are here to correct this.
Please follow along with the pictures for the input sequence.
If you mess up just start over until you enter everything correctly.  

Comments

author
wachinida (author)2017-07-18

great . then ,How can I made it display on TM1637 ?

author
yanadne (author)2017-06-20

thank you soo much code is very good.

author
hemanthgoalla (author)2015-04-23

The code worked fine for me. I also have the code how to display the time and date on the serial monitor. If anyone has any doubt regarding the code can contact me.

author

Brother when I have run the code I got the output as kkkkkkkkkkkkkkkkkkk..........
So please help me



author
foursemi (author)hemanthgoalla2017-01-02

I am getting the time format in 165, ..153 something like this. What is the wrong? can you suggest me..

author
foursemi (author)hemanthgoalla2017-01-02

Hello Hemanthgoalla,

I am not able to set the time in required format. Suggest me on that.

Thank you..

author
RaviD7 (author)hemanthgoalla2016-03-15

Hey, I am having trouble in displaying time and date when i upload the sketch and open serial monitor to see it. My problem is when i give 'y' character in serial monitor the setTime() function is executed which is fine because i want to set time and other parameters through serial monitor but WHAT I WANT IS WHEN I DONT PRESS 'Y' I SHOULD GET EARLIER VALUES OF TIME AND DATE FROM RTC AS A NORMAL FUNCTIONING AS SOON AS I OPEN SERIAL MONITOR AFTER UPLOADING THE CODE AND IN BETWEEN IF I GIVE 'Y' KEY IT SHOULD ONLY EXECUTE setTime(). so what should i do?

author
Pushan Panda (author)2016-12-26

Thank you this is amazing! Very sophisticated code!

author
spaansebrabander made it! (author)2016-12-21

I am a beginning Arduinist. I have a DS 1307 running with hh:mm:ss and on 2nd row dd/mm/yyyy. I however want on 2nd row "wednesday, december 21" Where /how can I fill in the date? You see, I use a real breadboard!

161221 - breadboard.jpg
author
Aditya Tripathi (author)2016-10-14

Thank you very much. You just made my work easy. Keep uploading such instructables.

author
richt_Biscuits (author)2015-11-05

Thank you for this code.

I am trying to set a simple RTC DS1307 but when I follow the prompts to set the time etc in the serial port it comes up with the below message...

the data has been entered.

The current date and time is now: . -....B. ... 165, 20165 153:165 PM

Thank you.

Any ideas how to get the actual time or what I am doing wrong? I am very new to arduino.

Cheers

R

author

i oso face the same problem here

author
moonguru (author)2016-08-22

Works well.

Could a DS3231 be substituted in place of the DS1307?

author
LoicK1 (author)2016-07-06

Hi,

i have a little problem, i've this message:

The current date and time is: ¾û�ÍÇÿ^¿þºþ^ß±¿yw}¿•�ß©Óïp}ŸöÿÿÙ?î݇¿wÿ—ûÜ<ß÷÷Û{÷Ïï,ûóÞ[ïW¼;}Û]ÝßÍÿûþíséÿWû÷éÿÿùùËÅþïmÖk}ãî~ÞïxŸû_ÿ¶Ù¿o®Íý¿Wÿï}Þÿ,Ý 165, 20165 153:165 PM
Please change to newline ending the settings on the lower right of the Serial Monitor
Would you like to set the date and time now? Y/N

The date's format is'nt ok.

The probleme already exist after settings:

The data has been entered.
The current date and time is now: ¾û�ÍÇÿ^¿þºþ^ß±¿yw}¿•�ß©Óïp}ŸöÿÿÙ?î݇¿wÿ—ûÜ<ß÷÷Û{÷Ïï,ûóÞ[ïW¼;}Û]ÝßÍÿûþíséÿWû÷éÿÿùùËÅþïmÖk}ãî~ÞïxŸû_ÿ¶Ù¿o®Íý¿Wÿï}Þÿ,Ý 165, 20165 153:165 PM
Thank you.

If someone can help me...

Thanks!

author
PanTau78 (author)2014-10-26

hi, thanks for the code, but i have one problem with it.

After i type in the y for yes, the code fill automatically the year with a 0

Please enter the current year, 00-99. - 0 (this could not be set)

Please enter the current month, 1-12. -

Any ideas what the problem is ?

Thanks and greats

André

author
nagarjunareddy (author)PanTau782016-04-10

i face same problem ..

author
BatuhanG1 (author)nagarjunareddy2016-04-14

i solved it..

instead of pressing 'y' and enter, write 'y016' (for 2016), it'll write it like that

author
nagarjunareddy (author)PanTau782016-04-10

i face same problem ..

author
sai303 (author)2016-02-01

Hai I am doing this project with Arduino uno and i have completed but in serial terminal i am able to see only " the current date is " other than this i am not able to get anything as mentioned in the images in your website . Kindly help me ... advance thanks

author
Simone72 (author)2014-12-10

Hello everyone! I'm testing this sketch with a Mega2560 and a DS3231...

Luckily the address of the chip is the same as the DS1307 ;-)

With the Serial Monitor (API 1.5.8) I can get access to the setting and display the good clock, but I have the same problem of PanTau78, it's impossible to set the Year!

I suppose that there one little problem in the function readByte at line 105...

Who has the solution?

author
LongJ (author)Simone722014-12-31

At the bottom right of the serial monitor screen set the box so it says "carriage Return" and answer 'y' and then set it to "Both NL & CR" then type in your other info.

Just some sloppy coding ..... But at least it works which is more than I can say for the Adafruit RTClib-Master library which won't set the time no matter what I tried

author
Discoveryellow (author)LongJ2016-01-04

Thanks! Setting dropdown menu in Serial Monitor to "Both NL & CR" worked for my issue where I could not get past the first setting (year setting). How did you figure it out?

The Adafruit RTClib-Master library is now outdated and my Arduino client is complaining and wont use it. That is not to mention that I prefer not to use additional libraries just to set the clock.

author
Discoveryellow (author)LongJ2016-01-04

Thanks! Setting dropdown menu in Serial Monitor to "Both NL & CR" worked for my issue where I could not get past the first setting (year setting). How did you figure it out?

The Adafruit RTClib-Master library is now outdated and my Arduino client is complaining and wont use it. That is not to mention that I prefer not to use additional libraries just to set the clock.

author
Marco-LuisS (author)2015-11-27

This code worked for me straight out the box, I'm using a homebrew RTC board with the SQW/OUT (pin 7) cabled to a led, to get noticed of my RTC clock running, If I may suggest, in the last "Wire.write(byte(0));" line, should be "Wire.write(byte(0x90));" for setting the control register to Square-Wave Output Enable once per second. (Per datasheet).

I'm using a Arduino Nano V3.0 (seems to be a chinese clone...)

Thumbs up!

author
JaredE (author)2015-08-20

Awesome! Worked flawlessly. Thanks for this!

author
JohnC20 made it! (author)2015-06-29

OK this made my setting up the DS1307 RTC fast and easy. Thanks

20150629_204359.jpg
author
sawrajs (author)2015-04-17

Hi

this code is working perfectly but i am nt able to set the DATE. can u please help me regarding this.

author
barracuda43 (author)2015-01-05

Hello.

Worked great but

How i change pm hr mode to 24hr mode

Thanks

author
onob422 (author)2014-11-18

thank you so much !! very helpful :)

author
raviteja1986 (author)2014-11-08

I connected DS1307 and its working. but there is time delay around 3 mins. how to avoid it

author
Mihajloz (author)2014-10-12

hi,

thanks a zillion for the code. It works perfectly.
Can I change SLC and SDA to connect to other lines (like A2 and A1) ? What I would need to change in the code? (is parameter 0x68 imortant for that)?

thanks for answer

author
TravisD1 (author)Mihajloz2014-10-28

Hey ,

As far as I know the SLC and SDA lines are set into the specific micro and cant be changed. If you look at the data sheet for the 328P you will see that the pins are set as such, because of this you cant change the pins of this method of communication,,,,, ran into this a while back and just had to deal with it :(

author
AdityaP3 (author)2014-09-30

Works Perfectly for Me!!!

author
desireecruzmanicad (author)2014-09-20

its not working ...

author
WWC (author)desireecruzmanicad2014-09-21

Gosh thats to bad.

author
nikhilbadhe11 (author)2014-09-12

arduino gives followig error..when i set the time.plz tell me solution.

The current date and time is: 165, 20165 153:165 PM

Please change to newline ending the settings on the lower right of the Serial Monitor

Would you like to set the date and time now? Y/N

Please enter the current year, 00-99. - 14

Please enter the current month, 1-12. - September

Please enter the current day of the month, 1-31. - 12

Please enter the current day of the week, 1-7.

1 Sun | 2 Mon | 3 Tues | 4 Weds | 5 Thu | 6 Fri | 7 Sat - Saturday

Please enter the current hour in 24hr format, 0-23. - 22

Please enter the current minute, 0-59. - 56

The data has been entered.

The current date and time is now: 9ò­e¿t÷¼?éî}¯nLùsÖ»¢ÇÎâÿþ¹ÿ¶"ÿþÿ]©¦¹Ø^jÿÜÒ>ö­ê‹-Ïkù´1®¿ì­Þpûä>ïÿ¦vŸVûõÝ9vûòó],ïÒkQÿ’ŸVÅ7¼F­¢2~¾­G×óqá÷~;ÊfåãßÏYvAÿ§ÖýÇ÷{;¸{þûß{m»ÿ¬¦ßüÿó´Û5÷ÎÇÜæûyםîÕß(šÐÿªß}Ñåeîù÷þhu-ŸéïFñÅݽ>_¿]»‡ç®û;{>“ÝŸ×ÿ‡“¿Oÿ¿7þÏãý~½ÖßÃÍ?þ¦¼O;§¾Õõu0Ÿoê/žÞgÿ÷uï'Öw}r¾«ýœ§Œ´êýVõ»¿Ì+¥õ¯öߘ¨”ÿÝÎï;åížyïLß¾]ܟï„úüØéþÄ[ÂÎþ$Uõýª+Y{‡ÕÎÝÅ÷Ø|§üº¦Ž÷ÙÝÝË

ïÿßÿ?}ý‹x]÷zÙõM‡žÑ²»oßÜ~[w“µÖýNëØ|ϟÏ

ÿƒ*¼Ÿ9ý¿;óˏÖû.½þ±¿«Ó=Ÿñê#²­A;©£Î;-?Ÿ(k&z¿ç}ý¿ÅÕޕ羍?Úßì÷é™jùÔV÷tkŸ¾uå±oûëëû\¾¼óÛ¦üŠâklŸ7ߍ{ÿï<ÚüS»éEƒç­œiøë?~_ïïö”SÈ/ýò<oû>îVß¼q™òão›Ÿþ¢úÿnßd+mùãßz¿3_â±~_Ÿv»¤Öå?¿Ý|êë§ý¿~X¦}þ'úîŸÞDýãÿÿ÷Yÿ¥ƒG'oéþ=;ßaßW֞ôÿ^®%ûçRþ?ýþþGŸ3ÿWžüwBGùþkõ«)cVK‡k}J½1ë4m—\é˜èo~³“~*Ö¶õû½çÿ/t®¥öٟ˜¯¶6ëÉvus'ÿ«faô­õï15«þ}¸ïòt¿‚2ÞíÜŸEø~ýóÞn3ßùßËÕé~:×ïýîËÛz1nwÓϯOüØöžÞ컇ú.Žºhý®þ=ƒŒãýÏþUî–ýÕ¿ßvô÷Pìó=ÿÿÙ+ýþÿߔw[–ýI¿PþN¤ÿ\{¾]à½¹¿¿ºÿnm|Ÿ/°wìôóŸýËì?ì?¾ïÝÕë[×ÖïéüÿnÍÖn;£ÂáømΌ?¾»¨ŸŸoÒëãøÛÏÌÉøéß¿¿ó¹s=Ú«ßÿòZé~ß~¤ßßó/jü=µÿÿžÏSÿeýö¹µBW7†ºúëÞöýéÞÿ¸³Ì~ùîÙÍdµg?«ïköºÐ><{É{þ§˜øìþ™½â–ú½M7úûÿö{­þ§ÞÃþÖckΝn½Ÿ3þïMóo¿Ÿƒí}Ïö×ÿß}|–ü¹wßÏï\÷÷_¥õÕÛûɘ§ýë>_‰ßoÈÝ3Ýëý_mÿúgw²må–ÞŠ³ úÿêÕþ÷Výµþäɳ?ü×÷³“¢þÓößwÿóûåÿ

@ü¼]¬þ%ûÎÞÛ¾:ïÛ>¯©}zo=×{üýë>mPúó~î

OCúµÖ5¾Öלb—ýä

Øßÿ|Ã›Ò÷Û÷õ÷£3y¯¹û=‹ïܓïï¼µNOn§ò¯q§ûyë‡Õþÿ¹îauŸÝœñvool¸oÛºß[½VÄ»\íw}¦ÍýúÍ«û¦é/å]îfïÑßR­•üòç÷ÿïÝyëÏgåt»MÔzí^¹¤ÿ/ýù®ûíõWûëíõzkå??÷gÿ7ÐÿŸ¿{?¯?­“©OoyW”µ%õ×ïüÑÎÛ¿úé$ÿûI–øÿw³ùö.=Þ±Òn<¾Ìšéçgýÿÿ{÷žóõ¿ÚçýSïcÛË=~õ¹¿ÿéßS©?îóûÿÏԋ•lßäûöß¾Dúñã±Ë©i—ïtmÅÝê÷lr”mGº¹Ó 165, 20165 153:165 PM

Thank you.

author
WWC (author)nikhilbadhe112014-09-12

So whats the problem, follow the directions and start with the first line, enter it and move on. Its a little tricky but is not impossible.

author
nikhilbadhe11 (author)WWC2014-09-17

after upload serial monitor shows right time.but wen i again connect arduino to pc then it shows 165/165 like garbage values..i also connected battery to rtc.

author
MJMAKOY (author)2014-01-06

hi camblonie!

scl is connected to pin5,sda connected to pin4,gnd of rtc connected to gnd of gizduino, vcc connected to 5v of gizduino. but still rtc not working.

here is serial monitor output:

The current date and time is: 165, 20165 153:165 PM
Please change to newline ending the settings on the lower right of the Serial Monitor
Would you like to set the date and time now? Y/N
Please enter the current year, 00-99. - 14
Please enter the current month, 1-12. - January
Please enter the current day of the month, 1-31. - 7
Please enter the current day of the week, 1-7.
1 Sun | 2 Mon | 3 Tues | 4 Weds | 5 Thu | 6 Fri | 7 Sat - Tuesday
Please enter the current hour in 24hr format, 0-23. - 9
Please enter the current minute, 0-59. - 28
The data has been entered.
The current date and time is now: xh.•<³wa´­—þ«ƒÃÖ.t÷äc­‡|÷V}ú\‑Ü­µ—9b¦ïaÑr––Óª6ñ*ÍôŠ÷Iëd§ß¹üK¾–g»ýº­KEö?;åü3ܟó­axה޾ÞÒoº«èًžÈí¾Kx~=òÏ{’+ñRõ´Â†•Îb³~ýõkÝ<;{ùΗ®I׎_·Œ›}ùgUsï>Nz´Þoz}¯!¿|kÎùò=•qŽ·~m2ãօÑ&çÉ6„³^)·ûuì~®æºïmŒöØw®d´äëҏÇÿþžêdß6êž?áÿËIÆï,ž
[³k¡µÜˆÿ¦‑Í:ö°©KœM_ýÊSÄÚó»Ú
µ{Î\»ÔÿÞòîÖzkMãÖïü
ˆoÚk®äJÓdjŠ÷.<óï79ñ¨<{Ë{Ö} 165, 20165 153:165 PM
Thank you.

author
nikhilbadhe11 (author)MJMAKOY2014-09-12

ive same problems as you mentioned.did you get any solution on this?? plz tell me..

author
WWC (author)nikhilbadhe112014-09-12

Continue with setting the date and time.

author
MJMAKOY (author)MJMAKOY2014-01-06

its me hellomark

author
SacredFoyer (author)2014-01-17

Hello, I have a problem about the time and date and the details are down below

The current date and time is: 165, 20165 153:165 PM
Please change to newline ending the settings on the lower right of the Serial Monitor
Would you like to set the date and time now? Y/N
Please enter the current year, 00-99. - 14
Please enter the current month, 1-12. - January
Please enter the current day of the month, 1-31. - 18
Please enter the current day of the week, 1-7.
1 Sun | 2 Mon | 3 Tues | 4 Weds | 5 Thu | 6 Fri | 7 Sat - Saturday
Please enter the current hour in 24hr format, 0-23. - 7
Please enter the current minute, 0-59. - 0
The data has been entered.
The current date and time is now: 165, 20165 153:165 PM
Thank you.

author
diy_bloke (author)SacredFoyer2014-09-04

if you get the 165 output there si something wrong. There are two lines of thought:
1- there is a bad connection somewhere (that is what ladyada says)

2- yr chip is fried (that is my experience)

author
KNallor (author)SacredFoyer2014-01-21

Hi,

Try running a I2C-Scanner code on your Arduino (http://playground.arduino.cc/Main/I2cScanner). You might get several different adresses back and maybe an other adress might work for your module.

I got 0x68 and 0x50 above code works fine for me with 0x68. But I get exactly the same output as you do, if I change "const int DS1307 = 0x68;" to " "const int DS1307 = 0x50;" in line 16.

Hope that helps.

author
dariyaks (author)KNallor2014-04-15

Hello, I've checked for I2C-Scanner, but the result is: Scanning...

No I2C devices found; What's wrong?

author
WWC (author)SacredFoyer2014-01-17

Whats the problem?

author
ash124 (author)2014-08-05

Hi!

I am facing the same problem as stuartsjg faced ...i-e when i pressed "Y" i got the message of thank you in the serial monitor ,and during this action i had disabled the newline ,still i got the same problem it looks like that the program is not jumping to the setTime() loop... here is the picture of serial monitor..plz help me out in this

oops.png
author
stuartsjg (author)2014-02-18

Hello,

This looks good, however once i get to here:
The current date and time is: Saturday February 18, 2014 10:01 PM
Please change to newline ending the settings on the lower right of the Serial Monitor
Would you like to set the date and time now? Y/N
Please enter the current year, 00-99. -

I type in to the send box "14" and press send, there is no response. Any ideas why?

author
CRImier (author)stuartsjg2014-06-19

For pressing "y", disable newlines. Then, for sending digits, enable "Newline". The needed drop-down list is at the bottom of Serial Monitor, next to baud rate drop-down.

About This Instructable

118,247views

64favorites

License:

Bio: Why would i buy something ready made when i can make it myself with half the features for twice the money? DIY!
More by WWC:3D Pinted Spool ReelHard Drive Tachometer for a Desktop Computer4093 Schmidt Trigger / Fan Speed Regulation
Add instructable to: