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|
Download the source code and compile it with
cc rtc-pi.c -o rtc-pi
Edit: This code and tutorial were written at a time when only one edition of Raspberry Pi (the 1) was out there. For the newer Pi-es which added extra GPIO pins and rearranged some of the existing ones, the code may required adjusting to address the correct pins, as mentioned in the comments below.
Then you can run
sudo rtc-pi YYYYMMDDhhmmss
to set the time and
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:
# saving date/time to RTC module
/usr/sbin/rtc-pi `date +"%Y%m%d%H%M%S"`
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)