Arduino Modules – Real Time Clock Setup (DS3231)

A Real Time Clock module gives the ability for an Arduino to keep track of the current time, and be able to track time even when the device loses power. Many libraries for Clock Modules are surprisingly difficult to implement, but the one from Rinky-Dink is very easy.

Notes:

  • Make sure to recomment out time setting code, and reupload code once clock has been set. If you do not the Arduino will reset the clock to the time you configured every time it loses power.
  • Make sure to buy batteries for your Clock Modules

Libraries:

Functional Parts in the Project:

#include <DS3231.h>

// Init the DS3231 using the hardware interface
DS3231  rtc(SDA,SCL);

void setup()
{
  Serial.begin(115200);

  rtc.begin();
  
// The following lines can be uncommented to set the date and time
  //rtc.setDOW(WEDNESDAY);     // Set Day-of-Week to SUNDAY
  //rtc.setTime(11, 23, 0);     // Set the time to 12:00:00 (24hr format)
  //rtc.setDate(13, 5, 2020);   // Set the date to January 1st, 2014
}

void loop()
{
  //Day of Week
  Serial.print(rtc.getDOWStr());
  Serial.print(" ");
  
  //Date
  Serial.print(rtc.getDateStr());
  Serial.print(" -- ");

  //Time
  Serial.println(rtc.getTimeStr());
  
  //Unix Time
  Serial.println(rtc.getUnixTime(rtc.getTime()));
  
  delay (1000);
}

Extra Credit with I2C LCD Screen

#include <DS3231.h>
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7);

DS3231  rtc(6, 7);

void setup()
{
  Serial.begin(115200);

  lcd.begin(20, 4);
  lcd.setBacklightPin(3, POSITIVE);
  lcd.setBacklight(HIGH);

  rtc.begin();

  //The following lines can be uncommented to set the date and time
  //rtc.setDOW(WEDNESDAY);     // Set Day-of-Week to SUNDAY
  //rtc.setTime(12, 0, 0);     // Set the time to 12:00:00 (24hr format)
  //rtc.setDate(1, 1, 2014);   // Set the date to January 1st, 2014
}

void loop()
{
  //Day of Week
  Serial.print(rtc.getDOWStr());
  Serial.print(" ");

  //Date
  Serial.print(rtc.getDateStr());
  Serial.print(" -- ");

  //Time
  Serial.println(rtc.getTimeStr());

  //Unix Time
  Serial.println(rtc.getUnixTime(rtc.getTime()));

  //LCD Print Out
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print(rtc.getDateStr());
  lcd.setCursor(0, 1);
  lcd.print(rtc.getTimeStr());
  lcd.setCursor(0, 2);
  lcd.print(rtc.getUnixTime(rtc.getTime()));

  delay (1000);
}

Be the first to comment

Leave a Reply