Real time clocks

Theory

A “real time clock” is a clock that keeps the date and time. It is essential for data loggers where measurements need to be logged against the time of day.

Real time clocks are typically powered by coin cell batteries, allowing the time to be preserved even if the main power is removed. Your Arduino will stop, but the clock will keep ticking, and when the power comes back, your Arduino will be able to read the correct date and time.

Wiring

Insert the coin cell battery (if needed), and plug the data logger shield into your Arduino.

Setting the time

// Install RTClib

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

DS1307 rtc;

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

void loop() {
}

Reading back the time

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

DS1307 rtc;
void setup() {
  // put your setup code here, to run once:
  
  Serial.begin(9600);
  Wire.begin();
  rtc.begin();
}

void loop() {
  // put your main code here, to run repeatedly:
  char buf [] = "DD/MM/YYYY hh:mm:ss";
  DateTime now = rtc.now();
  now.format(buf);
  Serial.println(buf);

  delay(1000);
}

Now unplug your Arduino and plug it back in. Check that the time stays correct.


This work is licensed under a Creative Commons Attribution 4.0 International License. For comments or corrections, please contact [email protected].