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
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:
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:
Description=Enable battery backed-up RTC
ExecStartPre=-/usr/bin/bash -c '/usr/bin/echo ds3231 0x68 > /sys/class/i2c-adapter/i2c-1/new_device'
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.