Accessing the Real-Time Clock from the Raspberry Pi

You can can talk to the Real-time clock (RTC) from both the Raspberry Pi and the Arduino (though try not to do it at the same time!) over the 12c bus.

These instructions describe the setup of the RTC under older Non-Jessie Raspbian. If you are using Sleepy Pi 2 head over to this page instead.

Install and Enable the I2C Tools

First of all you need to add the following two lines to the /etc/modules file using nano. You need root privileges to do this so use:

and add:

It should then look a bit like this:

modules-file-i2c-450

 

You will need to reboot for the changes to take effect.

You now need to install the i2c tools by typing the following into a Terminal window such as LXTerminal (make sure you are connected to the internet as these are downloaded and installed from the Repository).

Detect your RTC

Once the i2c tools have been installed you can see if you can see the RTC by typing the following command in LXTerminal:

This works for the latest models of Raspberry Pi’s. If you have one of the earlier 256Mb ones, then the i2c bus was slightly different and you need the following command instead:

In either case you should see the following in LXTerminal:
i2cdetect of the RTC from LXTerminal

 

The RTC will be detected with the address 0x68. If you are running Sleepy Pi 2, there will be another device shown on address 0x24 (which is a GPIO expander).

Note: just about all RTC’s have the same i2c address of 0x68!

Access your RTC

First of all to check that the RTC is working we can manually type the necessary magic incantations from LXTerminal and see if we can read / write the clock.

For Sleepy Pi 1 type the following lines:

For Sleepy Pi 2 use these lines instead (there is a different RTC on Sleepy Pi 2)

(in both cases, if you have an original 256Mb Pi then replace “i2c-1” with “i2c-0”)

Which should give you something like this:

RTC Setup in LXTerminal

 

Set the Right Time on the RTC

The easiest way to do this is to first setup the right time on the Raspberry Pi and then transfer that to the RTC.

To set the time on the Raspberry Pi just connect it to the internet via either the Ethernet connection or by Wi-Fi. It will automatically sync itself to an internet time service. To check that the time is correct type “date” on the command line and the current time will be displayed.

Once you have set the time on the Raspberry Pi you can now transfer it to the RTC with the following command:

Set the Time at Startup

If we want to set the time at startup then we first need to add the RTC kernel module to the /etc/modules using either nano, so we get:

etc/modules files with ds-1374 module added

To set the clock automatically when the Raspberry Pi boots you can edit the /etc/rc.local file using nano as follows:

adding the lines above the “exit 0”. A hat tip goes to AndyD for this from this forum thread.

Back to Top

Site design & build by FUB Software