Saturday, March 16, 2013

C Code to Access a Chronodot I2C Real-Time Clock from a Raspberry Pi

The Chronodot is an I2C real-time clock module based on the DS3231 chip that I've used with a couple Arduino aand Netduino projects. In looking into how to start doing some C or C++ programming on the RPi, I found this post at Binnery that shows how to work with a DS1307 RTC from a C program.  The same code works with the Chronodot with only slight modification.

Connections


Chronodot   RPi 
GND         GND
VCC         5V0
SCL         SCL0 (GPIO3)
SDA         SDA0 (GPIO2)

The Raspberry Pi has built-in 1k pull-up resistors on the SDA and SCL lines. These are sufficient for the Chronodot, so no external pull-up resistors are needed.

Code


The C code by Andre Wussow is available from GitHub. There is only one line that needs to be change so the code will work with the Raspberry Pi Model B. Model B uses /dev/i2c-1 as the I2C bus rather than /dev/i2c-0 :

Change line  56 from

if ((deviceHandle = open("/dev/i2c-0", O_RDWR)) < 0) {

to

if ((deviceHandle = open("/dev/i2c-1", O_RDWR)) < 0) {

To add leading zeros appropriately to the date and time data (and rearrange the date), I also modified lines 94 - 95 (but this is not strictly necesary):

printf("Date: %02x-%02x-%02x\n", month, day, year);
printf("Time: %02x:%02x:%02x\n", hours, minutes, seconds);

I compiled the code using the following command at the command line on the Pi:

  gcc rtc_ds1307.c -ortc_ds1307.c 

Run the code at the command line like this -

  ./rtc_ds1307

This prints out the current time and date from the Chronodot.

2 comments:

  1. First of all, Thanks a lot for such a gr8 and useful tutorial. It was an awesome example to understand RTC using C.
    very useful for me and going to try it this weekend. Many Thanks for sharing your knowledge.

    Warm Regards
    Brijesh

    ReplyDelete
    Replies
    1. Hi Brijesh -

      I'm glad you found it useful.

      --Brad

      Delete