Using a Real-Time Clock over SPI with the Raspberry Pi 3 – DS3234

rtc_spi

I would suggest when following these notes to have a ethernet connection at the beginning of this to get NTP time first.

To get NTP time run the following command:

sudo ntpd -gq

Enable the SPI interface:

sudo raspi-config

Create the following dts file: ds3234-rpi.dts

/dts-v1/;
/plugin/;

/ {
    compatible = "brcm,bcm2835";
    fragment@0 {
        target = <&spi0>;
        __overlay__ {
            spidev@0 {
                status = "disabled";
            };
            ds3234@0 {
                compatible = "ds3234";
                reg = ;
                #address-cells = ;
                #size-cells = ;
                spi-max-frequency = ;
            };
        };
    };
};

Create the Makefile:

DTC=dtc
 
all: ds3234-rpi.dtb
 
ds3234-rpi.dtb: ds3234-rpi.dts
        $(DTC) -@ -I dts -O dtb -o ds3234-Rpi.Dtbo ds3234-rpi.Dts
 
install-ds3234-rpi.dtbo: ds3234-rpi.dtbo
        cp ds3234-rpi.dtbo /boot/overlays/
 
install: install-ds3234-rpi.dtbo
 
clean:
        rm *.dtbo

Compile the overlay:

sudo make
sudo make install

Modify /boot/config.txt and include the following:

# RTC
dtoverlay=ds3234-rpi

Modify /lib/udev/hwclock-set by commenting out the following code:

if [ -e /run/systemd/system ] ; then
    exit 0
fi

So it looks like this:

#if [ -e /run/systemd/system ] ; then
#    exit 0
#fi

Remove the fake-hwclock:

sudo apt-get remove fake-hwclock

Create a two systemd services –
to set the system time on boot from the RTC and also write time to the RTC on shutdown.

/etc/systemd/system/hwclock-start.service

[Unit]
Description=Set time from RTC on startup
After=network.target

[Service]
Type=oneshot
ExecStart=/sbin/hwclock -s
TimeoutSec=0

[Install]
WantedBy=multi-user.target

/etc/systemd/system/hwclock-stop.service

[Unit]
Description=Synchronise Hardware Clock to System Clock
DefaultDependencies=no
Before=shutdown.target

[Service]
Type=oneshot
ExecStart=/sbin/hwclock --systohc

[Install]
WantedBy=reboot.target halt.target poweroff.target

Enable the services to run:

systemctl enable hwclock-start hwclock-stop

Reboot your Pi and verify the hardware clock time:

sudo hwclock -r

Verify that the rtc_ds3234 module has loaded:

sudo lsmod

Verify systemtime

date

If all went well your should have a functional hardware clock you can disconnect ethernet and reboot and test if you have system time and hwclock time that match.

Leave a Reply

Your email address will not be published. Required fields are marked *