Oct 11

Using an I2C Real Time Clock (RTC) with a Raspberry Pi

Updated instructions for newer Pi's over here.

Unlike most computers the Raspberry Pi doesn't contain a Real Time Clock (RTC), we assume it was left out of the design to save space and/or money. A RTC is a coin cell battery powered clock which keeps accurate time, even when the computer is powered off. Without one, the Raspberry Pi isn't capable of keeping time by itself.

If you're using a Pi Model B with an Internet connection then you can get the time from the Internet using Network Time Protocol (NTP), however if you're using a Model A or just don't have a network connection, then you'll need an RTC to keep time.

We've found a simple to use RTC module for the Raspberry Pi with the Dallas DS3231 I2C RTC chip which is also a bunch more accurate than the commonly used DS1307 chip. It's also tiny, and fits right on the Pi's GPIO header (seen top left of the image).

Raspberry Pi RTC Module installed

Here's the basic steps you need to get the Pi RTC Module going on the latest Raspbian distribution you can download from the Raspberry Pi Foundation's website.

# Remove the module blacklist entry so it can be loaded on boot
sudo sed -i 's/blacklist i2c-bcm2708/#blacklist i2c-bcm2708/' /etc/modprobe.d/raspi-blacklist.conf
# Load the module now
sudo modprobe i2c-bcm2708
# Notify Linux of the Dallas RTC device
echo ds1307 0x68 | sudo tee /sys/class/i2c-adapter/i2c-1/new_device
# Test whether Linux can see our RTC module.
sudo hwclock

That's it! You can also add the i2c initialisation command to rc.local which means it will be run at every boot up;

# Add the RTC device on boot
sudo sed -i 's#^exit 0$#echo ds1307 0x68 > /sys/class/i2c-adapter/i2c-1/new_device#' /etc/rc.local
echo exit 0 | sudo tee -a /etc/rc.local

This doesn't cover automatically setting the clock on boot and but you can do so by adding another line (above exit 0) to rc.local with;

hwclock -s

69 responses to "Using an I2C Real Time Clock (RTC) with a Raspberry Pi"

  1. After following the instuctions I found that
    hwclock --debug -s
    Produced the error
    /dev/rtc not found - No usable clock interface

    i2cdetect -y 0 and ictdetect -y 1 showed nothing but zeros

    Although the picture seems clear I wondered if it was a mistake since the first two Pi connectors are power.
    With nothing left to lose I moved the board over to the inner set of connectors.

    i2cdetect showed a 68 on the grid and the file /dev/rtc0 appeared after booting.

    Putting a symbolic link ln -s /dev/rtc /dev/rtc0 allowed the hwclock to find the real time clock and it shows the time.

    Can you check all this please and adjust the picture on your web page.
  2. Hi Keir,

    Thanks very much for the comment, I'm sure it will help others. I'm not sure why you had to create a symlink when I didn't.

    Cheers,

    Hadley
  3. this works fine for my R2 Pis but, I have an R1 where this does not work. I know that internally the SDA and SCL pins have different registers. Any suggestions?

    - Dirk Slawinski
  4. Pending moderation
  5. Hi Dirk

    For a Rev1 Pi you need to change:

    echo ds1307 0x68 | sudo tee /sys/class/i2c-adapter/i2c-1/new_device

    to:

    echo ds1307 0x68 | sudo tee /sys/class/i2c-adapter/i2c-0/new_device

    Hugh
  6. Thank Hugh,

    Good point, I had completely forgotten about that!

    Cheers,

    Hadley
  7. fantastic! thank you!

    - Dirk
  8. What GPIO port?
    i have a raspberry pi "model b" and a RTC like your.
    I can't see if you are using the firsts 5 pin of the top, or the bottom.
    If we use this image:
    http://www.learnhowtodo.org/wp-content/uploads/2014/01/Raspberry-pi-rev-1-gpio-p...

    I have to install my ds3231 on the top (5v,5v,ground,gpio14,gpio15)?
    OR
    I have to put my ds3231 on the bottom (3v,gpio0,gpio1,gpio4,ground)?

    Thank You very much!!!

    pd: here they are using the bottom (3v,gpio0,gpio1,gpio4,ground) http://nicegear.co.nz/obj/images/pi-rtc-module-mounting.png
  9. Hi Bvita

    It depends what RTC module you're using. For the one we sell there's an image on the product page showing what pins to install it on.

    Hadley
  10. Will the changes mentioned above work with this and a Pi B+ ??
    I'm trying to build a simple Network Time Server for a Video security/NAS system that has no computers or Internet Access..

    Thanks for any direction!
  11. Pending moderation
  12. Pending moderation
  13. Hi JanJ,

    It will work fine with the Raspberry Pi Model B+ as the processor is exactly the same and the GPIO port is compatible.

    Cheers,

    Hadley
  14. Hi Hadley:
    Following the instructions, I am able to see a time when running sudo hwclock. But the date is Jan 01, 2000. How do I set the time and date on the RTC?
    Thanks!!!!
    Dave
  15. Hi Dave,

    You can use hwclock, check out the manpage for all the details;

    hwclock --set --date="2011-08-14 16:45:05"
  16. Thanks! Where can I find the manpage?
  17. Hi Dave,

    Type at the command line;

    man hwclock

    Regards,

    Hadley
  18. Pending moderation
  19. Pending moderation
  20. instead of:
    echo exit 0 | sudo tee -a /etc/rc.local

    it's easier to use:
    echo exit 0 >> /etc/rc.local

  21. That would only work if you were root.
  22. Dallas DS3231 I2C RTC chip which contain a temperature sensor.
    How can i check it on Raspberry?
  23. We don't have instructions for that currently.
  24. I have 2 each PI B, 2-each B+, and one BananaPi none on which this RTC works. I get the 'Invalid argument' back when I send the 'echo ds1307 0x68 | sudo tee /sys/class/i2c-adapter/i2c-1/new_device' command. It is not blacklisted. Can anyone help?

    Thanks.
  25. I entered the commands at the top of this page but hit trouble. My keyboard sent the pound sign instead of # because I neglected to set the keyboard at NOOBS startup. I'm now left with bad lines in the bootup stages. They get skipped but look untidy and perhaps waste time. How do I get rid of them?

    The good news is that the RTC time and date got set automatically when I went online and did some browsing. If you're intending to go online, don't set up the RTC - it may just get set automatically.
  26. Hi Neil,

    Check the file /etc/rc.local for any bad commands, that could be the issue.

    hads
  27. How do I check a file? Googling doesn't tell me.
  28. After following the instruction, the fake-hwclock service and NTP are still running. Maybe think about removing them??

    sudo update-rc.d -f fake-hwclock remove
    sudo update-rc.d -f ntp remove
  29. Pending moderation
  30. Pending moderation
  31. Hi, just want to ask. the configuration is it the same as in raspbmc or openelec?
  32. I'm unsure about that.
  33. Pending moderation
  34. Pending moderation
  35. Pending moderation
  36. Pending moderation
  37. Pending moderation
  38. At my wits end, and now using a December 2014 Pi download. I've done all the commands and yet the DS3231 fails to keep time after a restart. With nano editor, I've verified that the rc.local lines are correct, and even re-entered them manually. The one big problem seems to be that I'm denied permission to read or edit the /sys/class/i2c-adapter/i2c-1/new_device file (using nano). From the GUI, I can open each folder until I get to /new_device. The permissions on that file are: View content=Only owner, Change content=Only owner. I'm denied permission to change the permissions. Anyone have a clue?
  39. Hi Neil,

    You'll need to be the root user to deal with the device, the commands above should run the things that need to be root with sudo.

    Cheers,

    Hadley
  40. Hadley, that's my complaint - I cannot read or edit the /new_device file even by typing:
    sudo nano /sys/class/i2c-adapter/i2c-1/new_device
    Permission is denied. It's just not as simple as your answer implies.
  41. Neil,

    You don't need to edit it, it's not a file, it's part of the sysfs.

    Hadley
  42. Hadley, if I can't read or edit the file, doesn't that mean that the command lines you provided above won't be inserted in the file? Therefore the RTC never works, right?
  43. OK I started afresh with a new download of NOOBS Raspbian (2015-02-02). In /etc/modprobe.d there is no raspi-blacklist.conf file. Great I thought, no need to unblacklist the DS1307. Then I found that in /sys/class/i2c-adapter there is no i2c-1 folder. I'm refused permission to create it. It looks like the above instructions are way out of date for late versions of Raspbian. I've wasted a week trying to get the RTC going, and wish I'd never heard of the Pi. Am going back to my DOS PC and continue writing my Assembler programs.
  44. Almost by accident I stumbled across a Help column. It appears the i2c adapter is NOT loaded by default in this 2015-02-02 distribution, unlike in earlier versions. To enable it, type sudo raspi-config, then select option 8 (Advanced Options), then select A7 I2C, then select Yes to enable. Hope this helps someone.
  45. Neil Barnett, thanks to your last comment about autoloading kernel module for i2c.
    Because after reboot I have to start again from:
    $ sudo modprobe i2c-bcm2708

    Btw, my another Raspberry runs Fedora 18 and kernel doesn't have module rtc-ds1307 anymore. They decided to remove it. So I've made python scripts for reading and setting time to DS3231 through i2c bus. It is really simple (not like in Raspbian of course).
  46. On my Raspberry Pi B+, I must add "sudo" to setting the clock on boot :

    "

    This doesn't cover automatically setting the clock on boot and but you can do so by adding another line (above exit 0) to rc.local with;

    sudo hwclock -s

    "
  47. Mine's working now - turns out I had played with gpio ports and had exported GPIO2 3 and 4 for turning on and off some LEDs.
    Once I unexported those, they were available for the i2c driver to use, and it all just worked.

    Only downside is now my breadboard breakout cable doesn't fit... so I will move the RTC to the breadboard!
  48. Good tip, thanks Criggie.
  49. Openelec 5.08 on Rasp Pi2. I got this working for your DS3231 module. It uses Device Tree Overlay and just needs 1 line added.

    Edit /flash/config.txt:
    (Editing via SSH)
    mount -o remount,rw /flash
    vi or nano /flash/config.txt
    Add to end of config.txt:
    dtoverlay=i2c-rtc,ds3231

    Save changes.
    mount -o remount,ro /flash
    reboot

    Then set the time through usual commands. I use the nptd in the autostart.sh and will use a hwclock command to correct the hwclock.

    Source webpages:
    https://github.com/raspberrypi/firmware/blob/master/boot/overlays/README
    http://wiki.openelec.tv/index.php/Config.txt
  50. Hi Peter,

    Great information, thanks for sharing.

    Cheers,

    Hadley
  51. Pending moderation
  52. In my case (OSMC), the following addition to
    /boot/config.txt
    is needed:

    dtparam=i2c_arm=on
    dtoverlay=i2c-rtc,ds3231
  53. Thanks for you comment Jiri. I've been meaning to check out OSMC as an alternative to OpenELEC myself.
  54. For those wanting to use RPi2, RTC & Openmediavault, this guide is essential (I wasted a lot of time attempting to get it all working using other guides- thanks tekkb).

    http://forums.openmediavault.org/index.php/Thread/8770-RPi-2-RTC-module-from-unr...
  55. Stumbled on this tonight...

    You are welcome Peter. : )

    Hope we see more Kiwis on the OMV forum. I will try to get Emby working on the RPi 2 in the nexts weeks. Have to try and build requisite libraries 1st.
  56. Some notes, the following worked for us with a Pi model 2 B,

    `sudo raspi-config` to enable I2C.
    If not taken care of by raspi-config, need to uncomment the
    dtparam=i2c_arm=on line in /boot/config.txt and add another line with
    dtparam=i2c1=on

    The blacklist edit is no more.

    Need to add a line to modprobe 'i2c-dev' in
    /etc/modules, along with i2c-bcm2708.

    Then reboot.

    Install 'sudo apt-get install i2c-tools python-smbus',
    then check with 'i2cdetect -l' and 'i2cdetect -y 1' to
    check that the device is found at 0x68.

    While connected to the internet let NTP run for a while, then
    check with "ntpq -p". Then set the hwclock's time from NTP-
    controlled system time with 'hwclock -w'.


    I found the 'hwclock -s' in /etc/rc.local left the system clock
    about 5 seconds in the past, maybe the device is still waking up
    at that point.
    Adding another "(sleep 15; hwclock -s) &" line in rc.local makes
    things better by running it again once it has had enough time to
    catch its breath.

    In the end I did not put "service fake-hwclock stop" before the
    "hwclock -s" in rc.local as I think that only does anything at
    system shutdown, to record the last known time. So it does not
    interfere and maybe even helps for the critical time between when
    the filesystem mounts and when rc.local starts the hwclock later
    in the boot process.

    Test system vs. hardware clock time with "date; hwclock; date"
  57. A correction to the previous post:

    After a day's testing it seems that fake-hwclock does indeed interfere with the real hwclock if left active. An old (bad) system time seems to be written to the real hwclock at system shutdown.

    Either "service fake-hwclock stop" needs to be in /etc/rc.local before the call to "hwclock -s" or else the service disabled for the default runlevel with update-rc.d as suggested in post #28 above.
  58. Pending moderation
  59. Pending moderation
  60. Pending moderation
  61. I own a Raspberry Pi Model B, purchased back in February, 2015. When I first followed these procedures, the RTC worked flawlessly. Then there was an update, probably a kernel upgrade, regardless, now, it recognizes the RTC but when I reboot, it doesn't have the most current time.

    With all of the comments in this blog, has the original post been updated to reflect all of the recommendations that have been known to work and the different models, as needed?
  62. Figured it out. I missed the reference in the steps below where Hamish posted in step 56 about "setting" the clock to the RTC with hwclock -w. No where in the setup procedures, does it mention to write the time to the RTC with this command. I have been looking for days, trying to figure this out and stumbled across it on Adafruit's website and then seeing it listed above.

    All of these little mentions posted above should be added to the original procedures and fellas like me won't be circling the wagons for days before I'm successful. Just a thought.

    John
  63. Pending moderation
  64. Pending moderation
  65. Followed your script to the letter and 45 mins later bingo all working. Swittched pi off over night switched on in morning clock reads 08:45 bang on.

    Great script

    Mike
  66. Pending moderation
  67. Hi, I'm running a Raspberry Pi 3b as a ham radio node/ repeater controller. It's running the Hamvoip Asterisk Arch Linux software. I'm trying to get my DS3231 RTC up and running with no success. I tried using the script from the following site...

    https://gist.github.com/grubernd/aed721614b36aaa31fd97ef5ab1ec6be

    when I run hwclock I get this...

    hwclock: Cannot access the Hardware Clock via any known method.
    hwclock: Use the --debug option to see the details of our search for an access method.

    The clock doesn't get detected. I tried your instructions. No luck. I can post the script and replies if that would help. I have two clocks and neither one works. Any help would be greatly appreciated. Thanks in advance, Vendel/ K2DSI.
  68. Hi, I'm running a Raspberry Pi 3b as a ham radio node/ repeater controller. It's running the Hamvoip Asterisk Arch Linux software. I'm trying to get my DS3231 RTC up and running with no success. I tried using the script from the following site...

    https://gist.github.com/grubernd/aed721614b36aaa31fd97ef5ab1ec6be

    when I run hwclock I get this...

    hwclock: Cannot access the Hardware Clock via any known method.
    hwclock: Use the --debug option to see the details of our search for an access method.

    The clock doesn't get detected. I tried your instructions. No luck. I can post the script and replies if that would help. I have two clocks and neither one works. Any help would be greatly appreciated. Thanks in advance, Vendel/ K2DSI.
  69. Oops, sorry about the double post, Vendel

Leave a comment