Introduction: Set Up Real Time Clock (RTC) on Raspberry Pi

About: Engineer. Educator. Entrepreneur.
Note: There were some issues with the audio on the YouTube video. I've taken it down temporarily and will upload a fixed video and update the link soon. Sorry for the inconvenience.

Raspberry Pi does not include a hardware clock on board. It uses internet access to set the time with the help of NTP servers. Use of a hardware real time clock (RTC) allows the Raspberry Pi to be used without internet access and still provide services that use time stamps. DS1307 is a commonly available I2C based RTC IC. Using the I2C protocol supported by the Raspberry Pi, real time clock support can easily be added with a cost of around $2-3.

Hardware Setup:

1. Obtain a DS1307 board or make one yourself (it's very straightforward).
2. Ensure that the I2C data and clock lines (SDA and SCL) does not have any pull-up resistors. If any pull-ups are present, remove them.
3. Connect a battery (most boards use CR2032 Lithium Cells) to the DS1307.
4. Make the connections to the Raspberry Pi. Refer here for the GPIO header pinouts. 5V, GND, SDA and SCL need to be connected.

Software Setup:

1. Enable i2c on the Raspberry Pi.

Run sudo nano /etc/modprobe.d/raspi-blacklist.conf
Locate the line blacklist i2c-bcm2708
Comment it out by typing a '#' in front. i.e. #blacklist i2c-bcm2708

2. Load the required modules at startup.

Run sudo nano /etc/modules
Add the following line at the end
i2c-bcm2708
i2c-dev
rtc-ds1307


3. Install i2c-tools

Run sudo apt-get install i2c-tools

4. Reboot (Run sudo reboot)

Note: The following commands require root privileges to run. It is easier to run them from a root prompt.
A root prompt can be launched by running sudo bash.


5. Check for I2C connectivity to DS1307

Run i2cdetect -y 0 on Model A
Run i2cdetect -y 1 on Model B

The address 0x68 should be listed if the module is connected properly.

6. Instantiate the DS1307

Run echo ds1307 0x68 > /sys/class/i2c-adapter/i2c-0/new_device on Model A
Run echo ds1307 0x68 > /sys/class/i2c-adapter/i2c-1/new_device on Model B

7. Ensure that the system time is set.

8. Initialize the hardware clock

Run hwclock --systohc -D --noadjfile --utc
This will set the time on the DS1307.

9. Verify the hardware clock

Run hwclock -r
If everything is configured correctly, the time and date is displayed.

10. Configure the hardware clock to synchronize on boot up.

Run nano /etc/rc.local
Insert the following lines before the 'exit 0' line

echo ds1307 0x68 > /sys/class/i2c-adapter/i2c-0/new_device on Model A
echo ds1307 0x68 > /sys/class/i2c-adapter/i2c-1/new_device on Model B

sudo hwclock -s

That's it. You're all set.