Real-time Clock

One of the requirements for my irrigation controller project is to have an accurate system clock – irrigation programs need to run at the correct time.  This is where the absence of a Chardware RTC on the Raspberry Pi becomes apparent. – It isn’t a good idea to always assume that I will have network connectivity and access to NTP servers on bootup.  As a result, part of my project build includes a DS3231 RTC on the I2C bus of the Raspberry Pi Zero which is the brains of the controller. The RTC module that I bought is available in packs of 3 for under $5 on dx.com.

Once the RTC is physically installed, there is still a bit of work involved in getting the Pi to use it.  There is a useful guide, which I found on Adafruit.  After setting up your I2C bus, you need to get the Pi to use the RTC on bootup.  This wasn’t immediately obvious, but the guide on Adafruit showed the steps I needed to follow.

First you need to add RTC support by adding a device tree overlay.  This is done in /boot/config.txt by adding the following line:

dtoverlay=i2c-rtc,ds3231

After rebooting, the output of i2cdetect -y 1 will show UU where it previously listed the I2C address of the RTC (68):

I2C Output after reboot

Next we need to remove the “fake hardware clock” which is installed in Raspbian by default, as follows:

sudo apt-get -y remove fake-hwclock
sudo update-rc.d -f fake-hwclock remove

 

Now you need to make sure that the RTC is read on boot.  You will need to edit the file /lib/udev/hwclock-set, and comment out the following 3 lines:

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

Finally, you will need to set the RTC correctly, if it not been used before.  To do this, you will first need to sync the Pi to a ntp server via the network.  Then, use the hwclock command to sync the RTC by entering the following command:

hwclock -w

You can read the RTC again by entering:

hwclock -r

 

The final result can be seen here where the RTC is seen plugged in vertically into a female header on the controller board:

RTC plugged into controller board