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()
{
  Wire.begin();
  Serial.begin(9600);
  // 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
  Wire.endTransmission();
}
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.endTransmission();
  Wire.requestFrom(0x68, 7);    // request 7 bytes (seconds, minutes, hours, day, 
                                // date, month, year)
  while(Wire.available())
  { 
    int seconds = bcdToDec(Wire.read()); 
    int minutes = bcdToDec(Wire.read()); 
    int hours = bcdToDec(Wire.read());   
    int day = bcdToDec(Wire.read());    // Not used in example
    int date = bcdToDec(Wire.read());
    int month = bcdToDec(Wire.read());
    int year = bcdToDec(Wire.read());
    // 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);
        
    Serial.println(buffer);
  }
  delay(1000);
}

// 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!
    Regards,Mike
    (you also should iclude the temperature function, if possible)

    ReplyDelete