Raspberry Pi: Adding a Real-Time Clock on Raspbian Stretch [UPDATED]

In a previous article, I described how to install a DS3231 real-time clock (RTC) in Raspbian Jessie – the following is an updated set of instructions for Stretch.

First, a brief summary: The Raspberry Pi does not have the necessary hardware to keep track of the current date and time when it’s powered off.  When it powers on, the system date is reset to January 1, 1970.  Raspbian has a “fake” clock service that, well, fakes it.  This is not very accurate, and as such, the system relies on internet connectivity to synchronize its clock correctly.  Once the network comes up and ntpd can synchronize the clock, it stays accurate from then on.

If you have an application that relies on accurate time, or you are using a Pi in an environment without internet access, you can purchase an RTC for your raspberry Pi.  Adafruit has one here, or you can purchase Chinese knockoffs from eBay for about $2.  The part number is DS3231.  Mine look like this:

Installed on the Pi (top left, on the GPIO pins):

Install the Software

You’ll need two packages: i2c-tools and python-smbus. We install the adjtimex command to check something later on. To install:

Configure the Device

Append the following to /boot/config.txt – this tells the system to load the real-time clock driver for a DS3231.

Then, go into the raspi-config utility by typing

You’ll see a screen that looks like this:

Screen Shot 2015-10-29 at 9.03.49 PM

Select Advanced Options, then I2C.  Select Yes to enable it, and Yes to automatically load the kernel module.

Configure udev to set the system time from the RTC when the device appears:

Reboot the system.

Finally, check to see if the device is available by running i2cdetect -y 1

You should see something like this:

The “UU” is located at the i2c address of the clock module.

Cleanup

Raspbian by default includes a fake hardware clock, which we don’t need anymore because we have a real one.  Remove the package and service:

Notes

If you run ntpd to sync the time to the internet, it will automatically update the hardware clock every 15 minutes.

The timedatectl command will show the status of the RTC if installed (note lines 3 and 7):

Run the adjtimex –print command and look at the status:

Note that the status (line 6) is 8193 which means ntpd will update the hardware clock every 11 minutes (according to this comment).

Credits

Many thanks to various users on the Raspberry Pi forums and Stack Exchange.

Also thanks to dfries on the raspberry pi forums with this post.