ELEGOO MEGA · LESSON 19
Real Time Clock Module
Print calendar time from an identified RTC once per second.
Use I2C clock registers and distinguish setting time from keeping time.
DS1307
Parts List
- ELEGOO Mega 2560 R3 is a 5 V ATmega2560 AVR board with many I/O pins and four hardware UARTs for control systems with several peripherals. Long ELEGOO-branded Mega PCB with USB-B and barrel connector, ATmega2560 marking, extended side headers and a large double-row digital header at the end. Read printed Mega labels; its SPI hardware placement is not the same numeric pins as an Uno.
- A USB-A to USB-B cable carries USB power and, when its data conductors are present, a host/device data link. USB-A plug and square USB-B plug. Inspect the plug shape; micro-USB is not USB-C, and USB-B is the squarer device connector.
- DS1307 keeps calendar time with a watch crystal and backup supply while the main controller is off. PCB with DS1307 IC marking, watch crystal and coin-cell holder; verify the actual carrier and battery arrangement. Read the IC; a coin-cell holder alone does not identify the clock.
- Male-to-female jumper leads make removable point-to-point connections for low-current prototype signals. Pin at one end and socket at the other. Check intact insulation and snug contacts before use.
Assembly
- Read the actual chip marking and select its matching project.
- Remove the coin cell for this first powered test; connect the four labeled pins and leave SQW/32K unconnected.
- Open Monitor at 9600 baud. The default program sets build time after every reset.

Reviewed connections
| From | To | Note |
|---|---|---|
| Mega D20 | RTC SDA | I2C data |
| Mega D21 | RTC SCL | I2C clock |
| Mega 5 V / GND | RTC VCC / GND | Only a carrier rated for a 5 V VCC input; battery removed |
Source-reviewed wiring. Hardware not bench-tested; firmware uploads have not been performed.
Code
PlatformIO configuration
[env:mega]
platform = atmelavr@5.3.0
board = megaatmega2560
framework = arduino
monitor_speed = 9600
Open PlatformIO Monitor at 9600 baud after Upload. Close Monitor before another Upload if the port is busy.
// ELEGOO Lesson 19, DS1307 variant: set from build time and print once per second.
#include <Arduino.h>
#include <Wire.h> // I2C uses Mega SDA=D20 and SCL=D21, with addressed transactions.
#include <stdio.h> // sscanf splits the compiler's date/time text into numbers.
#include <string.h>
const uint8_t RTC_ADDRESS = 0x68;
const bool SET_TIME_ON_START = true; // Like the supplied sketch: resets time on EVERY reset.
bool rtcReady = false;
// RTC registers use BCD: each decimal digit occupies four bits, rather than binary.
uint8_t toBcd(uint8_t value) { return (value / 10) * 16 + value % 10; }
uint8_t fromBcd(uint8_t value) { return (value >> 4) * 10 + (value & 0x0F); }
bool setBuildTime() {
char monthName[4];
unsigned int day, year, hour, minute, second;
if (sscanf(__DATE__, "%3s %u %u", monthName, &day, &year) != 3 ||
sscanf(__TIME__, "%u:%u:%u", &hour, &minute, &second) != 3) return false;
const char months[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
uint8_t month = 1;
while (month <= 12 && strncmp(monthName, months + (month - 1) * 3, 3) != 0) ++month;
if (month > 12 || year < 2000 || year > 2099) return false;
// Calendar arithmetic produces 1=Sunday..7=Saturday for the day-of-week register.
const uint8_t offsets[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
unsigned int y = year - (month < 3 ? 1 : 0);
const uint8_t weekday = (y + y / 4 - y / 100 + y / 400 + offsets[month - 1] + day) % 7 + 1;
// Writing seconds with bit 7 clear starts the DS1307 oscillator (CH=0).
// Register 0 starts seven clock fields. Send exactly seven bytes, not alarm/control data.
Wire.beginTransmission(RTC_ADDRESS);
Wire.write(0x00);
Wire.write(toBcd(second)); Wire.write(toBcd(minute)); Wire.write(toBcd(hour));
Wire.write(toBcd(weekday)); Wire.write(toBcd(day)); Wire.write(toBcd(month));
Wire.write(toBcd(year - 2000));
return Wire.endTransmission() == 0; // A bool result reports whether the chip acknowledged.
}
void setup() {
Serial.begin(9600);
Wire.begin();
Wire.setClock(100000); // DS1307 standard-mode I2C; also suitable for DS3231.
Wire.beginTransmission(RTC_ADDRESS);
rtcReady = Wire.endTransmission() == 0;
if (rtcReady && SET_TIME_ON_START) rtcReady = setBuildTime();
Serial.println("Initialize DS1307");
}
void loop() {
if (!rtcReady) {
Serial.println("RTC not detected or time-setting failed");
delay(1000);
return; // Finish this loop call; do not wait forever inside an I2C driver.
}
Wire.beginTransmission(RTC_ADDRESS); Wire.write(0x00);
if (Wire.endTransmission(false) != 0 || Wire.requestFrom(RTC_ADDRESS, uint8_t(7)) != 7) {
Serial.println("Incomplete RTC read"); delay(1000); return;
}
uint8_t raw[7];
for (uint8_t i = 0; i < 7; ++i) raw[i] = Wire.read();
// The bit masks remove mode flags before decoding. Handle existing 12-hour clocks too.
const uint8_t hour = (raw[2] & 0x40) ?
fromBcd(raw[2] & 0x1F) % 12 + ((raw[2] & 0x20) ? 12 : 0) : fromBcd(raw[2] & 0x3F);
Serial.print("Raw data: "); Serial.print(2000 + fromBcd(raw[6]));
Serial.print('-'); Serial.print(fromBcd(raw[5] & 0x1F));
Serial.print('-'); Serial.print(fromBcd(raw[4]));
Serial.print(' '); Serial.print(hour);
Serial.print(':'); Serial.print(fromBcd(raw[1] & 0x7F));
Serial.print(':'); Serial.println(fromBcd(raw[0] & 0x7F));
delay(1000);
}
Source: SOURCE_RECONCILED. Compile: COMPILE_VERIFIED. Hardware: NOT_TESTED. Upload: NOT_PERFORMED.
Expected behavior
Raw data lines advance about once per second. The initial value is the compiler host’s date/time, not network time; upload delay and timezone may differ. Missing/incomplete I2C reads print an error.
Experiments & Challenges
- After setting time once, change SET_TIME_ON_START to false and rebuild so reset no longer rewrites the clock.
Troubleshooting
- No clock: check D20/D21, exact chip selection and 0x68; do not substitute DS1302.