Arduino: Real-Time Clock Module (DS3231)

Real-Time Clock module running over I2C. You will need to give it a CR2032 battery so it retains the time when the power is removed from the Arduino.

DEVICENANO
GNDGround
VCC+5V/+3.3V
SCLA5
SDAA4

You will need to install the “RTClib” library in the Arduino IDE.

How to Set Time

Before use you need to set the time on the RTC. This script will pull the time from your computer and use it to configure the RTC.

#include <Wire.h>
#include "RTClib.h"

RTC_DS3231 rtc;

void setup() {
  Wire.begin();
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}

void loop() {

}

This has a couple problems: it uses whatever timezone your computer is using, and it creates a delay of however long it took your computer to compile and upload the sketch (in my case about six seconds.)

How to Read Time

#include <Wire.h>
#include "RTClib.h"

RTC_DS3231 rtc;

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

void loop() {
  
    DateTime now = rtc.now();
    
    Serial.println("Current Date & Time: ");
    Serial.print(now.year(), DEC);
    Serial.print('-');
    Serial.print(now.month(), DEC);
    Serial.print('-');
    Serial.print(now.day(), DEC);
    Serial.print(" ");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();
    Serial.print("Unix Time: ");
    Serial.println(now.unixtime());
    Serial.println();
    delay(1000);
}
This entry was posted in Arduino and tagged . Bookmark the permalink.