Try Embedded

Real-time clock

Keep the date and time with a DS1307 real-time clock over I²C, using RTClib.

Sensors · Intermediate

In a real product: Data logger (Industrial): A real-time clock timestamps every reading.

A microcontroller loses track of time when it resets or loses power. A real-time clock (RTC) chip keeps counting on its own (on a coin cell, on real hardware), so the board can always ask it the date and time.

What you'll learn

  • The I²C bus: two wires (SDA and SCL) shared by many devices, each with an address
  • Using RTClib to read and set a DS1307
  • Formatting a date and time with snprintf()

How it works

On the Uno, I²C is on A4 (SDA) and A5 (SCL). The DS1307 answers at address 0x68. Its registers hold the seconds, minutes, hours, day, date, month and year in BCD (each decimal digit in 4 bits).

rtc.begin() checks the chip is there. If its clock is not running, rtc.adjust() sets it to the time the sketch was compiled. rtc.now() reads all the registers at once and returns a DateTime, which the loop prints every second.

Try this

  • Show the time on an LCD to make a desk clock.
  • Add an alarm: light an LED at a set time.
  • Set the part's initTime to a date you choose, and see the clock start from it.

sketch.ino

// A DS1307 real-time clock on I2C (A4 = SDA, A5 = SCL), read with RTClib.
#include <RTClib.h>

RTC_DS1307 rtc;
const char *DAYS[7] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};

void setup() {
  Serial.begin(9600);
  if (!rtc.begin()) {
    Serial.println("No RTC found");
    while (true) {}
  }
  if (!rtc.isrunning()) rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}

void loop() {
  DateTime now = rtc.now();
  char text[24];
  snprintf(text, sizeof text, "%04d-%02d-%02d %02d:%02d:%02d",
           now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second());
  Serial.print(DAYS[now.dayOfTheWeek()]);
  Serial.print(' ');
  Serial.println(text);
  delay(1000);
}

Lessons behind it