Friday, 8 March 2013
Raspberry Pi and Real Time Clock DS1307
The Raspberry Pi doesn't have a real-time clock (RTC) buit-in, the reason seems to be to keep it as affordable as possible. In most cases this won't make a difference, once the Pi can reach the Internet it simply updates the time from one of the time servers in the pool (perhaps mine ;-)
The problem comes in with being offline for whatever reason but still requiring the time to always be accurate (or very close) for certain applications, such as business transaction handling etc
The easiest answer being to add a RTC to the Pi using the GPIO pins, I used the Adafruit kit (soldering required) for the Arduino boards as a local retailer had stock of it by some miracle.
Basically if you have the kit from Adafruit or something similar the below may help you (at your own risk, ;-), the circuit isn't very complicated but you need to remember not to add the the two 2.2KΩ resistors in this kit for it to work on the Pi.
Additionally you can insert the capacitor and crystal any direction you want, the chip half moon needs to match with the board (see my board and RTC in the picture above)
1. VCC output needs to be connected to the 5.0V pin number 2 of the Pi
2. GND output needs to be connected to the GND pin number 6 of the Pi
3. SDA output needs to be connected to the SDA0 pin number 3 of the Pi
4. SCL output needs to be connected to the SCL0 pin number 5 of the Pi
You can view the pin layout on the Pi on hobbytronics.co.uk
1. You can skip the SQW (square-wave output) as it won't be used in this configuration.
2. Will keep time for 5 years but may gain or lose as much as 2 seconds per day
3. accurate and temperature compensated chip - DS3231 or NXP PCF2127AT
I use Raspbian 2013-02-09-wheezy-raspbian.img on my Pi so these instructions may differ on your setup or version of Raspbian, all the commands assume root user, remember sudo before the command if required:
Install the required tools to do testing:
1. apt-get update
2. apt-get install i2ctools
Testing your RTC from Linux:
1. Run the command: modprobe i2c-dev; modprobe i2c-bcm2708; modprobe rtc-ds1307
2. Run: echo ds1307 0x68 > /sys/class/i2c-adapter/i2c-1/new_device
3. Run: i2cdetect -y 1
4. You should see a 68 appear under row 8 column 60, if not the RTC may not be connected properly or something may be wrong on the RTC/Pi board.
5. The hwclock command should output a date (may be very inaccurate)
Ensure your Pi's time is correct and set it if need be, then you need to sync the time to your RTC by running: hwclock -w
hwclock -r should now return the correct time from your RTC
Add the following to your /etc/rc.local to sync your systems software time to the time your RTC has:
echo ds1307 0x68 > /sys/class/i2c-adapter/i2c-1/new_device
Once the Pi goes online the time sync will simply update this for you to the most accurate time.
Good Luck and Enjoy!