Jump to content

Using a DS3231 RTC With a Raspberry Pi

From Squirrel's Lair
Revision as of 12:25, 2024 April 10 by Hal (talk | contribs) (Page Creation)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


  • Cargo:


  • Categories:
  • Default form


Up until the Raspberry Pi 5, Pi stock boards didn't come with built-in RTC hardware (and the Pi 5 needs an external battery for its RTC). Normally this isn't a problem because they will attempt to sync with an NTP server periodically, but that's not possible if they don't have a network connection or the connection is particularly locked down.

Adding an external RTC to the Pi is relatively simple, there are many different models out there, some of which are in HAT format, some connect directly to and cover just a few pins, and some need to be connected by wires to the appropriate pins.

The DS3231 is a relatively accurate device that is quite popular. It communicates with the Pi over the I2C bus.

To set up the Pi so the DS3231 is used: - Ensure the Pi is up to date - Run raspi-config and select "Interface Options", then "I2C", and select "Yes" to enable the I2C interface. - Install python3-smbus i2c-tools - Reboot - Edit the /etc/modules file, add "rtc-ds1307" to the bottom of the file. - Shut down the Pi and remove power. - Connect the DS3231 to the Pi (NOTE: These are pin numbers, not GPIO numbers!): - DS3231 VCC to Pi Pin 1 (3v3) - DS3231 SDA to Pi Pin 3 (SDA) - DS3231 SCL to Pi Pin 5 (SCL) - DS3231 GND to Pi Pi 6 (GND) Some DS3231 modules are built to drop directly onto the GPIO pins but check the pinouts first just in case. - Re-check connections - Apply power and boot the Pi - Run i2cdetect -y 1 - If you see a "68" appear in the chart, the DS3231 and Pi are communicating. If not, make sure the I2C bus is enabled and the pins are connected properly. - Edit the /boot/firmware/config.txt file and add the following line to the end of the file: dtoverlay=i2c-rtc,ds3231 - Reboot the Pi - Run i2cdetect -y 1 - If you see a "UU" in place of where the "68" was, the DS3231 driver is working. If not, check the previous steps. - Remove the fake-hwclock package so it won't interfere with the RTC (sudo apt remove fake-hwclock). - Clear the fake-hwclock references from the startup scripts with update-rc.d -f fake-hwclock remove - Edit the following file /lib/udev/hwclock-set - Comment out the following block of three lines: - if [ -e /run/systemd... - exit 0 - fi - Ensure the current time on the Pi is correct and either connect it to a network to sync or set it manually. - Write the current time to the DS3231 with sudo hwclock -w - Shut down the Pi and remove power and any network connection. - Wait 5 minutes. - Power up the Pi and once it boots check the time. If everything is working properly, the time should be correct without a network connection.