The DS3231 chip is an accurate real time clock with support for battery backed non-volatile RAM to maintain the time while the computer is off. Some very cheap boards are currently available to add one of these to a Raspberry Pi with minimal footprint. However, recent changes to the Linux kernel make this slightly different to enable. Fortunately the most recent distributions now include support for the Device Tree based peripheral support system.
I2C RTC support is already included in the current Raspberry Pi compatible distributions but must be enabled by editing config.txt which is used in the early boot stages to pass configuration parameters to the kernel. On lubuntu or rasbian this file is in /boot but on OpenElec it is found in /flash which is a separate filesystem that needs remounting with read-write permissions. This file only needs a line to enable the i2c device in Device Tree by adding dtoverlay=i2c-rtc,ds3231. Once this is done the next boot will detect the device and automatically make use of it.
If you want to manually add the device without forcing a reboot and set the time then install i2c-tools and check that it is detected:
pat@monitor1:~$ sudo i2cdetect -y 1 0 1 2 3 4 5 6 7 8 9 a b c d e f 00: -- -- -- -- -- -- -- -- -- -- -- -- -- 10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 60: -- -- -- -- -- -- -- -- 68 -- -- -- -- -- -- -- 70: -- -- -- -- -- -- -- --
To then add this as an RTC device the following command enables it in the running system and causes a new /dev/rtc0 device to be created:
sudo su -c 'echo ds3231 0x68 > /sys/class/i2c-adapter/i2c-1/new_device'
Testing this will show the time is set to some meaningless default:
pat@monitor1:~$ sudo hwclock -r Sat 05 Feb 2000 07:45:53 GMT -0.696570 seconds
The system time is currently correct as this system is already running NTP and connected to the network. The hardware clock can therefore be updated from the system clock.
pat@spd-status:~$ sudo hwclock --systohc pat@spd-status:~$ sudo hwclock Thu 13 Aug 2015 12:42:30 BST -0.573334 seconds
Now it should all work properly with the kernel keeping the hardware clock current and reading it on bootup to fix the time in the absence of networking and NTP.