Using the Real Time Clock

What is a Real Time Clock?

When logging data, it's often really really useful to have timestamps! That way you can take data one minute apart (by checking the clock) or noting at what time of day the data was logged.

The Arduino does have a built-in timekeeper called millis() and theres also timers built into the chip that can keep track of longer time periods like minutes or days. So why would you want to have a separate RTC chip? Well, the biggest reason is that millis() only keeps track of time since the Arduino was last powered - that means that when the power is turned on, the millisecond timer is set back to 0. The Arduino doesnt know its 'Tuesday' or 'March 8th' all it can tell is 'Its been 14,000 milliseconds since I was last turned on'.

OK so what if you wanted to set the time on the Arduino? You'd have to program in the date and time and you could have it count from that point on. But if it lost power, you'd have to reset the time. Much like very cheap alarm clocks: every time they lose power they blink 12:00

While this sort of basic timekeeping is OK for some projects, a data-logger will need to have consistent timekeeping that doesnt reset when the Arduino battery dies or is reprogrammed. Thus, we include a separate RTC! The RTC chip is a specialized chip that just keeps track of time. It can count leap-years and knows how many days are in a month, but it doesn't take care of Daylight Savings Time (because it changes from place to place)

This image shows a computer motherboard with a Real Time Clock called the DS1387. Theres a lithium battery in there which is why it's so big.

The RTC we'll be using is the PCF8523 or the DS1307.

If you have an Adafruit Datalogger Shield rev B, you will be using the PCF8523 - this RTC is newer and better than the DS1307. Look on your shield to see if you see PCF8523 written above the chip.

If you have an older Datalogger shield, you will be using the DS1307 - there's no text so you'll just need to remember that if it doesn't say PCF8523 it's the DS1307

Battery Backup

As long as it has a coin cell to run it, the RTC will merrily tick along for a long time, even when the Arduino loses power, or is reprogrammed.

Use any CR1220 3V lithium metal coin cell battery:

CR1220 12mm Diameter - 3V Lithium Coin Cell Battery

PRODUCT ID: 380
These are the highest quality & capacity batteries, the same as shipped with the iCufflinks, iNecklace, Datalogging and GPS Shields, GPS HAT, etc. One battery per order...
$0.95
IN STOCK
You MUST have a coin cell installed for the RTC to work, if there is no coin cell, it will act strangely and possibly hang the Arduino when you try to use it, so ALWAYS make SURE there's a battery installed, even if it's a dead battery.

Talking to the RTC

The RTC is an i2c device, which means it uses 2 wires to to communicate. These two wires are used to set the time and retrieve it. On the Arduino UNO, these pins are also wired to the Analog 4 and 5 pins. This is a bit annoying since of course we want to have up to 6 analog inputs to read data and now we've lost two.

For the RTC library, we'll be using a fork of JeeLab's excellent RTC library, which is available on GitHub. You can do that by visiting the github repo and manually downloading or, easier, just click this button to download the zip

Rename the uncompressed folder RTClib and check that the RTClib folder contains RTClib.cpp and RTClib.h

Place the RTClib library folder your arduinosketchfolder/libraries/ folder.
You may need to create the libraries subfolder if it's your first library. Restart the IDE.

We also have a great tutorial on Arduino library installation at:
http://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-use

Once done, restart the IDE

First RTC test

The first thing we'll demonstrate is a test sketch that will read the time from the RTC once a second. We'll also show what happens if you remove the battery and replace it since that causes the RTC to halt. So to start, remove the battery from the holder while the Arduino is not powered or plugged into USB. Wait 3 seconds and then replace the battery. This resets the RTC chip. Now load up the matching sketch for your RTC

  • For the Adafruit Datalogger shield rev B open up Examples->RTClib->pcf8523
  • For the older Adafruit Dataloggers, use Examples->RTClib->ds1307

Upload it to your Arduino with the datalogger shield on!

If you're having problems make sure you are running the right example! PCF8523 and DS1307 RTC chips are not identical so they have separate examples!

Now open up the Serial Console and make sure the baud rate is set correctly at 57600 baud you should see the following:

Whenever the RTC chip loses all power (including the backup battery) it will reset to an earlier date and report the time as 0:0:0 or similar. The DS1307 won't even count seconds (it's stopped).Whenever you set the time, this will kickstart the clock ticking.

So, basically, the upshot here is that you should never ever remove the battery once you've set the time. You shouldn't have to and the battery holder is very snug so unless the board is crushed, the battery won't 'fall out'

Setting the time

With the same sketch loaded, uncomment the line that starts with RTC.adjust like so:

  if (! rtc.initialized()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

This line is very cute, what it does is take the Date and Time according the computer you're using (right when you compile the code) and uses that to program the RTC. If your computer time is not set right you should fix that first. Then you must press the Upload button to compile and then immediately upload. If you compile and then upload later, the clock will be off by that amount of time.

Then open up the Serial monitor window to show that the time has been set

From now on, you won't have to ever set the time again: the battery will last 5 or more years

Reading the time

Now that the RTC is merrily ticking away, we'll want to query it for the time. Let's look at the sketch again to see how this is done

void loop () {
    DateTime now = rtc.now();
    
    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(") ");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

There's pretty much only one way to get the time using the RTClib, which is to call now(), a function that returns a DateTime object that describes the year, month, day, hour, minute and second when you called now().

There are some RTC libraries that instead have you call something like RTC.year() and RTC.hour() to get the current year and hour. However, there's one problem where if you happen to ask for the minute right at 3:14:59 just before the next minute rolls over, and then the second right after the minute rolls over (so at 3:15:00) you'll see the time as 3:14:00 which is a minute off. If you did it the other way around you could get 3:15:59 - so one minute off in the other direction.

Because this is not an especially unlikely occurance - particularly if you're querying the time pretty often - we take a 'snapshot' of the time from the RTC all at once and then we can pull it apart into day() or second() as seen above. It's a tiny bit more effort but we think its worth it to avoid mistakes!

We can also get a 'timestamp' out of the DateTime object by calling unixtime which counts the number of seconds (not counting leapseconds) since midnight, January 1st 1970

    Serial.print(" since 2000 = ");
    Serial.print(now.unixtime());
    Serial.print("s = ");
    Serial.print(now.unixtime() / 86400L);
    Serial.println("d");

Since there are 60*60*24 = 86400 seconds in a day, we can easily count days since then as well. This might be useful when you want to keep track of how much time has passed since the last query, making some math a lot easier (like checking if it's been 5 minutes later, just see if unixtime() has increased by 300, you dont have to worry about hour changes)

Last updated on 2016-09-05 at 09.39.04 PM Published on 2013-04-12 at 11.22.30 AM