This page looks best with JavaScript enabled

Adding RTC to RaspberryPi

 ·  🎃 kr0m

For our RTC to work, we will have to patch the kernel sources to add support for PCF2127A and compile with support for I2C. I recommend following the steps explained in this previous article where the kernel was compiled on an x86-based PC since it will be much faster than compiling the kernel on the RaspberryPi itself.

We proceed with the patching of the sources:

cd /usr/src/rpi_kernel/linux
wget https://github.com/afterthoughtsoftware/linux/commit/fd5ff2d88f470ed70ff58393eee61110b181816a.patch
patch -p1 < fd5ff2d88f470ed70ff58393eee61110b181816a.patch

We compile the kernel:

make ARCH=arm CROSS_COMPILE=${CCPREFIX} menuconfig

Device Drivers -> I2C support -> I2C Hardware Bus support -> BCM2708 BSC
Device Drivers -> Real Time Clock -> Philips PCF2127A (only I2C)

We must indicate which address within the I2C bus it has in RTC(0x51) and which module should manage it:

echo pcf2127a 0x51 > /sys/class/i2c-adapter/i2c-1/new_device

We assign the date manually and transfer it to the RTC:

date MMDDHHMMYYYY
hwclock -w

If we want to read the date saved in the RTC, just:

hwclock -r

If we want to read the date from the RTC and configure the OS:

hwclock -s

For everything to work correctly, the timezone must be configured correctly:

  • Gentoo:

    cp /usr/share/zoneinfo/Europe/Madrid /etc/localtime
    echo “Europe/Madrid” > /etc/timezone

  • Debian:

    dpkg-reconfigure tzdata

At each boot, we will read the date from the RTC and configure it in the OS:

  • Gentoo:

    vi /etc/local.d/RTC.start

    echo pcf2127a 0x51 > /sys/class/i2c-adapter/i2c-1/new_device
    sleep 2
    hwclock -s &
    
    chmod 700 /etc/local.d/RTC.start
  • Debian:

    vi /etc/rc.local

    echo pcf2127a 0x51 > /sys/class/i2c-adapter/i2c-1/new_device
    sleep 2
    hwclock -s &
    

Now, even if we turn off the rasp and remove the power, the date will not be lost unless the RTC button battery runs out.