Using an I2C Real Time Clock (RTC) with a Raspberry Pi
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).
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;