Notes About Working with Various Arduino & Netduino Microcontroller Boards

Thursday, November 29, 2012

Using a Chronodot v.2.1 with Arduino Leonardo or Arduino Due to Get Time & Date

Last summer I posted about using the Netduino to get the time and date from a Chronodot, but I didn't post any code for working with the Arduino. The snippet of sample code available on the Macetech page linked from Adafruit is a bit outdated, so I am posting an updated example that works with the Arduino Leonardo and the Arduino Due. 

I have connected the Chronodot's VCC to the 3.3V pin on the Arduino and GND to GND. The SDA and SCL pins on the Chronodot are connected to the pins on the Arduino with the same labels. On the Arduino Due, note that there are SDA1 and SCL1 pins that are separate from the SDA and SCL pins; again, this example assumes connects to SDA and SCL. I have used 10k pull-up resistors on the SDA and SCL lines. 

This example uses I2C to read the date and time from the Chronodot 2.1 and prints the correctly formatted result to the serial console.

#include <Wire.h>

char buffer[25]; // Holds formatted result from sprintf()
void setup()
  // clear /EOSC bit
  // Sometimes necessary to ensure that the clock
  // keeps running on just battery power. Once set,
  // it shouldn't need to be reset but it's a good
  // idea to make sure.
  Wire.beginTransmission(0x68); // address DS3231
  Wire.write(0x0E);             // select register
  Wire.write(0b00011100);       // write register bitmap, bit 7 is /EOSC
void loop()
  // Wait for user to open serial console
  while (!Serial) ;
  // send request to receive data starting at register 0
  Wire.beginTransmission(0x68); // 0x68 is DS3231 device address
  Wire.write(0);                // start at register 0
  Wire.requestFrom(0x68, 7);    // request 7 bytes (seconds, minutes, hours, day, 
                                // date, month, year)
    int seconds = bcdToDec(; 
    int minutes = bcdToDec(; 
    int hours = bcdToDec(;   
    int day = bcdToDec(;    // Not used in example
    int date = bcdToDec(;
    int month = bcdToDec(;
    int year = bcdToDec(;
    // Format code %02d = 2-digit base-10 number with leading 0 
    // if needed for padding
    sprintf(buffer, "%02d/%02d/%02d %02d:%02d:%02d", month, date, year, hours, 
      minutes, seconds);

// Convert binary coded decimal to decimal
byte bcdToDec(byte val)
  return ( (val/16*10) + (val%16) );

1 comment:

  1. The first sketch working with due and chronodot. Thank you Brad!
    (you also should iclude the temperature function, if possible)