Using a DS1302 Real Time Clock module on Raspberry PI

The hardware

rapsberrypi_rtcmodule_ds1302I’ve got a “DS1302 Serial Real Time Clock with Battery” very cheap off eBay (for under 2$) which I’ve set up as a backup Real Time clock module on my Raspberry.

Hooking it up is pretty straightforward. You’ll need power (3V), ground and 3 GPIO pins (which are hard-coded in the C++ program and rather difficult to change).

The pinout is detailed below:

Raspberry Pi DS1302 Module
not connected VCC1 / VBAT
*this pin is connected to the module’s battery
and should not be used
3V (pins 1 or 17) VCC2
GND (pins 6, 9, 14, 20 or 25) GND
GPIO #27 (pin 13)
*GPIO #21 (same pin) on PI rev1
GPIO #18 (pin 12) DAT
GPIO #17 (pin 11) RST


The software

Download the program and compile it with

cc rtc-pi.c -o rtc-pi

Then you can run

sudo rtc-pi YYYYMMDDhhmmss

to set the time and

sudo rtc-pi

to read the time from the module and set it to system clock

Syncing PI clock with module

A RTC module would be useless on the PI without using it to retrieve the right clock at the right time. And the PI needs a clock the most at boot.

The simplest method would be to edit /etc/rc.local and add a call to the compiled rtc-pi binary.

But to read a valid clock from the module we require it to have the correct time set beforehand. For this we can use the same binary to save the correct time (obtained most likely via NTP) on a previous shutdown.

For this, create a new file (let’s call it savetime) in /etc/init.d with the following content:

Then symlink this file in /etc/rc0.d

ln -s /etc/init.d/savetime /etc/rc0.d/K01savetime

rc0.d is the folder for scripts called at runlevel 0 (shutdown/restart)


Additional information: (1)


  1. Hi,

    Thanks for the tutorial. I connected the RTC , copied the c file to RPi and ran the code sudo rtc-pi YYYYMMDDhhmmss. It seemed to work well. But when i tried sudo rtc-pi , it gave error
    Read UNIX timestamp from RTC: -1
    Unable to change the system time. Did you run the program as an administrator?
    The operation returned the error message “Invalid argument”

    Can you help me with this?

  2. I coyped the rtc-pi .c to my RPi sd card but when I type cc rtc-pi.c -o rtc-pi in my RPi model A+ is tells me there is no file or directory

  3. Thanks for the pointer to e-bay for inexpensive TOY clocks.

    I reviewed the software and it appears to create a bus conflict when reading the TOY registers. It also
    has other issues.

    I have written a replacement, but until my hardware arrives, it is simulated but untested.

    Meantime, beware.

  4. Pingback: Nokia 5110 Bildschirm und DS1302 an einem Raspberry Pi « Keules Blog

Leave a Reply