Monday, March 4, 2013

Reading Time & Date from a Chronodot (DS3231) with a Maple Mini

This simple example shows how to read the current date and time from a Chronodot v. 2.1 real-time clock module (based on the DS3231 chip). The Chronodot connects to the Maple Mini via I2C (using the Wire library).

The sample below reads the current date and time from the Chronodot, does some simple formatting, and prints the result to the USBSerial console.

Connections:

Chronodot      Maple Mini
GND            GND
VCC            VCC
SCL            I2C1 SCL (pin 16) - with 10k Ohm pull-up resistor
SDA            I2C1 SDA (pin 15) - with 10k Ohm pull-up resistor

Code:

#include <Wire.h>

int addr = 0x68; // 0x68 is DS3231 I2C device address

void setup(){
  Wire.begin(15, 16); // Connected to i2c1
}

void loop() {
  // Send request to receive data starting at register 0
  Wire.beginTransmission(addr); 
  Wire.send(0);                 // start at register 0
  Wire.endTransmission();
  Wire.requestFrom(addr, 7);    // request 7 bytes (seconds, minutes, hours, day, 
                                // date, month, year)
  while(Wire.available())
  { 
    int seconds = bcdToDec(Wire.receive()); 
    int minutes = bcdToDec(Wire.receive()); 
    int hours = bcdToDec(Wire.receive());   
    int day = bcdToDec(Wire.receive());    // Not used in example
    int date = bcdToDec(Wire.receive());   // Day of month
    int month = bcdToDec(Wire.receive());
    int year = bcdToDec(Wire.receive());
    printDateTime(month, date, year, hours, minutes, seconds);
    delay(1000);
  }
}

void printDateTime(int month, int date, int year, int hours, 
    int minutes, int seconds) 
{
    if(month < 10)
      SerialUSB.print('0');
    SerialUSB.print(month);  
    SerialUSB.print('/');
    if(date < 10)
      SerialUSB.print('0');   
    SerialUSB.print(date);
    SerialUSB.print('/');
    SerialUSB.print(year);
    SerialUSB.print(' '); 
    if(hours < 10)
      SerialUSB.print('0');   
    SerialUSB.print(hours);   
    SerialUSB.print(':');
    if(minutes < 10)
      SerialUSB.print('0');    
    SerialUSB.print(minutes);
    SerialUSB.print(':');
    if(seconds < 10)
      SerialUSB.print('0');
    SerialUSB.println(seconds);  
}

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

2 comments:

  1. Can anyone tell me how to do this on raspberry pi using python smbus module ??

    ReplyDelete
    Replies
    1. Hi Abdul-Rauf -

      I have put together a quick example on my Raspberry Pi blog at http://bradsrpi.blogspot.com/2013/04/reading-time-date-from-chronodot-using.html. I hope this helps.

      Delete