Adding a Real Time Clock to the Pi via I²C

Using a PCF8523 or DS3231 RTC equipped pcb


Power down your Pi before you connect something onto the GPIO pins!

Adding a Real Time Clock to the Pi via I²C

Adafruit PCF8523 - direct connect
Adafruit DS3231 - breakout


Install i2c-tools

To see the I²C address matrix: $ sudo apt-get install python-smbus i2c-tools -y Check if you see the RTC clock with address 0x68 in the matrix: $ sudo i2cdetect -y 1


Add device tree overlay

You can add support for the RTC by adding a device tree overlay: $ sudo nano /boot/config.txt Edit the pi configuration and add the RTC chip to the end of the file: dtoverlay=i2c-rtc,ds3231 Or dtoverlay=i2c-rtc,pcf8523 Save and Reboot


Check whether the device tree overlay works properly

$ sudo i2cdetect -y 1 There should now be UU where 0x68 used to be.
Once you have the Kernel driver running, i2cdetect will skip over 0x68 and display UU instead, this means its working!


Delete fake hardware clock

$ sudo apt-get -y remove fake-hwclock -y $ sudo update-rc.d -f fake-hwclock remove


Edit the original RTC script:

$ sudo nano /lib/udev/hwclock-set Find: if [ -e /run/systemd/system ] ; then exit 0 fi Comment out or delete: #if [ -e /run/systemd/system ] ; then # exit 0 #fi


Solving RTC read issues on Stretch

It seems Raspbian Stretch uses systemd-timesyncd.service instead of ntp.service.
So you have to disable time sync in order for RTC time set to work properly: $ sudo systemctl stop systemd-timesyncd.service $ sudo systemctl disable systemd-timesyncd.service


Get access to the RTC and update with the system time

The Pi should be connected to the internet. Check for the correct date/time: $ date If this gives the correct time/date, set the Hardware Clock from the System Clock, and update the timestamps in /etc/adjtime : $ sudo hwclock --systohc This does the same as hwclock -w

You only have to do this once, as long as the battery is full and working.
When the battery is replaced you need to do this again, because the RTC has lost all it's memory.


Test the RTC clock

Take the ultimate test by turning the Pi off for a while and then turning it back on WITHOUT internet access!
So that you know for sure that the RTC clock is used and not NTP.

Pi system time & RTC module time: $ date && sudo hwclock -r Monitor the drift between your system clock and the rtc module: $ sudo hwclock -c The above command will not return to the prompt, it will run continuously printing the clock drift every 10 seconds, until you interrupt it with Ctrl-C

That's it!