Frost on a roof

#Raspberry

DS3231 RTC on Raspberry with Fedora

A minor downside of the Raspberry Pi is that it is not equipped with a battery backed-up real-time clock. After every reboot, the system time is messed up and needs to be corrected by NTP, which in turn requires a network connection.

Luckily, there are readily assembled RTC modules available. They base on the DS3231 real time clock chip. A tiny battery is keeping the time when the Raspberry is disconnected from power. You can find those modules for less than two Euros a piece at marketplaces like Amazon, eBay, or Alibaba. The module is just plugged onto the pin header of the RasPi.

It is quite easy to use the RTC on Raspbian. On Fedora for Raspberry Pi, the installation was a little more tricky though.

In a first step, the RTC must be added as a new I²C device:

/usr/bin/echo ds3231 0x68 > /sys/class/i2c-adapter/i2c-1/new_device

(If you have a Raspberry Rev 1, you'd use /sys/class/i2c-adapter/i2c-0/new_device instead.)

The RTC does not store the time zone, so we need to tell the system that we'd like to use the system's time zone:

timedatectl set-local-rtc 0

And finally we copy the current system's time to the RTC chip:

hwclock -w

The RTC is now set up and ready for operation. But we're not done yet. When the system boots up, the DS3231 is unknown to the system again. We have to add a systemd service for adding it and reading the time, by creating a file called /etc/systemd/system/my-rtc.service with the following content:

[Unit]
Description=Enable battery backed-up RTC
Before=basic.target
After=sysinit.target
DefaultDependencies=no

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStartPre=-/usr/bin/bash -c '/usr/bin/echo ds3231 0x68 > /sys/class/i2c-adapter/i2c-1/new_device'
ExecStartPre=-/usr/bin/sleep 0.2
ExecStart=/usr/sbin/hwclock -s

[Install]
WantedBy=basic.target

The service is enabled via:

systemctl enable my-rtc

And now every time the system boots up, the DS3231 is added as I²C device and the system clock is set to the time found in the RTC. If a network is available, NTP will later take over and set the network time.

It's not the most elegant solution, I guess. I had to add a sleep command because it turned out that the hardware is not immediately available after adding the device. I'd like to hear from you if you found a better way.

Remember to manually use hwclock -w from time to time, to reset the RTC to the correct time. If you shut down your RasPi frequently, you could add another systemd service that automatically writes the current time on system shutdown.