Here’s a step-by-step guide to adding and configuring an RTC (Real-Time Clock) module (like the DS3231 or PCF8523) to your Raspberry Pi:
What You’ll Need
- RTC Module (e.g., DS3231 or PCF8523 – both are highly accurate).
- Raspberry Pi (any model with I²C pins).
- Battery Holder & Coin Cell Battery (CR2032, typically).
- Jumper Wires (female-to-female for most HATs/modules).
- Optional: Soldering iron (if your module isn’t pre-soldered).
Step 1: Connect the RTC Module
Wiring (I²C Connection)
Note: Some modules use 5V, but most RTCs (like DS3231) work fine at 3.3V. Double-check your module’s datasheet!
Step 2: Enable I²C on the Pi
- Open the Raspberry Pi terminal and run:
bash
sudo raspi-config
Navigate to:
Interfacing Options → I2C → EnableReboot the Pi:
bash
sudo reboot
Step 3: Verify the RTC is Detected
After rebooting, check if the RTC is visible on the I²C bus:
bash
sudo i2cdetect -y 1
You should see the RTC’s address (e.g., 0x68 for DS3231 or 0x51 for PCF8523).
Step 4: Configure the Kernel to Use the RTC
- Edit the boot config file:
bash
sudo nano /boot/config.txt
- Add one of these lines (depending on your RTC module):
For DS3231:
text
dtoverlay=i2c-rtc,ds3231
For PCF8523:
text
dtoverlay=i2c-rtc,pcf8523
- Save (Ctrl+X, then Y, then Enter) and reboot:
bash
sudo reboot
Step 5: Sync System Time to the RTC
- Check if the RTC is recognized:
bash
sudo hwclock -r
If the time is wrong, set it manually (skip if using NTP first).
- Sync System Time → RTC (if Pi has internet/NTP):
bash
sudo hwclock -w
This writes the Pi’s current time (from NTP) to the RTC.
- Sync RTC → System Time on Boot (for offline use): Edit /etc/rc.local (before exit 0):
bash
sudo hwclock -s
exit 0
Step 6: Test the RTC
- Disconnect the Pi from power (and internet).
- Wait a few minutes, then power it back on.
- Run:
bash
timedatectl
The time should still be correct (synced from the RTC).
Troubleshooting
No I²C device detected?
- Check wiring (SDA/SCL swapped? Bad connections?).
- Verify the RTC module isn’t defective.
hwclock fails?
- Ensure the correct dtoverlay is set in /boot/config.txt.
- Try reinstalling the RTC kernel module:
bash
sudo apt install --reinstall i2c-tools
Why This Works
- The RTC keeps time while the Pi is off using the coin cell battery.
- On boot, the Pi loads the time from the RTC (if no NTP is available).
- Linux treats the RTC as a hardware clock (/dev/rtc0).
Optional: Automatic NTP Sync (Hybrid Setup)
If the Pi occasionally connects to the internet, you can sync the RTC to NTP periodically:
- Install ntpdate:
bash
sudo apt install ntpdate
- Create a cron job to update the RTC daily:
bash
sudo crontab -e
Add:
text
0 3 * * * /usr/sbin/ntpdate -u pool.ntp.org && /sbin/hwclock -w
Now your Raspberry Pi has persistent timekeeping, even offline!
Top comments (0)