// 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);
}
