19. DS1307 RTC & Formatted Text
Keep calendar time through power loss and format it for displays.
Learning outcomes
- Distinguish millis from an RTC
- Wire a DS1307 on I2C
- Set time once and preserve it
- Format fixed-width date/time text
Parts and preparation
Uno, DS1307 RTC module, suitable backup cell, and RTClib by Adafruit (see Libraries box).
Before power: inspect wiring, confirm supply voltage and ensure all connected circuits share GND.
Libraries for this lesson
In Arduino IDE 2 open Tools → Manage Libraries…. Search by the Library Manager name and install the package by the exact author below. Similar names from other authors can use different APIs and will break the example.
| Include | Library Manager name | Author | Install note |
|---|---|---|---|
Wire.h | Wire | Arduino | Built into the Arduino core. No Library Manager install required. |
RTClib.h | RTClib | Adafruit | Install via Library Manager. Choose Adafruit, not similarly named RTC packages. |
RTC purpose
millis measures uptime and resets with power. An RTC tracks calendar date/time and uses a backup cell while main power is absent.
DS1307
The DS1307 communicates over I2C and runs from a 32.768 kHz crystal. It is less accurate than temperature-compensated devices such as DS3231.
Setting time
Set the RTC once from compile time, then comment out that adjustment and upload again. Repeated adjustment makes time jump back on every reset.
Formatting
snprintf writes formatted text into a bounded character buffer. %02d pads a number to two digits.
Wiring and safe build sequence

- RTC VCC -> 5 V
- RTC GND -> GND
- RTC SDA -> A4
- RTC SCL -> A5
- Install the correct backup cell with correct polarity
Worked sketch
Download .ino sketch#include <Wire.h>
#include <RTClib.h>
RTC_DS1307 rtc;
char line[24];
void setup() {
Serial.begin(9600);
if (!rtc.begin()) {
Serial.println("RTC not found");
while (true) { delay(100); }
}
// Run once if required, then comment and upload again:
// rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
void loop() {
DateTime now = rtc.now();
snprintf(line, sizeof(line), "%02d/%02d/%04d %02d:%02d:%02d",
now.day(), now.month(), now.year(),
now.hour(), now.minute(), now.second());
Serial.println(line);
delay(1000);
}How the code works
- sizeof(line) prevents snprintf from writing beyond the buffer.
- The failure message distinguishes wiring/address faults from display faults.
Test and record evidence
Practical evidence checklist
Common faults and checks
- Use an I2C scanner to confirm the RTC address.
- Replace/check the backup cell if time resets.
- Do not leave rtc.adjust active.
Check your understanding
Q1. Why not use millis as a clock?
Show answer
It measures uptime only and resets after power loss/reset.
Q2. Why comment rtc.adjust after setting?
Show answer
Otherwise each reset overwrites the RTC time.