Juhin Christophe replied to the topic 'Raspberry real time' in the forum. 4 years ago

Re: The Correct way to add a RTC

Quote
I finally found it. See the penultimate post on page 3:

www.raspberrypi.org/forums/viewtopic.php?p=842661#p842661


Thu Aug 24, 2017 5:54 pm
After searching for a long while, and after a lot of experiments, I've putted togheter all the information I've collected all around the Net about how to connect a realtime clock to the Raspberry and allow the OS use it as system clock even if no connections to a NTP server.
I've used a DS3231, but the following should work even with a DS1307. Just use ds1307 where into the following instructions is used ds3231.

The following, definitively worked for me, using Raspbian Jessie. So:
edit the file using sudo nano /boot/config.txt and add or modify a line that looks like the following:

Code: Select all

dtoverlay=i2c-rtc,ds1307
Edit the file using sudo nano /etc/init.d/hwclock.sh and comment out the content in order to be sure that the content looks like the following:

Code: Select all

#if [ -d /run/udev ] || [ -d /dev/.udev ]; then
# return 0
#fi

Then disable the fake-hwclock and enable the hwclock.sh with the following group of commands:

Code: Select all

sudo apt-get remove fake-hwclock
sudo rm /etc/cron.hourly/fake-hwclock
sudo update-rc.d -f fake-hwclock remove
sudo rm /etc/init.d/fake-hwclock
sudo update-rc.d hwclock.sh enable

Then modify the file using sudo nano /lib/udev/hwclock-set locate the following lines and be sure to comment it out:

Code: Select all

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

Now, create two system services in order to set the system's clock when the OS boot and also to write to the RTC at the shutdown. So, the first one:

Code: Select all

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

...and paste in it the following:

Code: Select all

[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

and the second one:

Code: Select all

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

Paste in it the following:

Code: Select all

[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

Finally, enable the services issuing once the following command:

Code: Select all

sudo systemctl enable hwclock-start hwclock-stop

You can also verify that the RTC module has been loaded using

Code: Select all

sudo lsmod

Read More...