#include <RTClib.h>

RTC_DS3231 rtc;

// Pin definitions for 7-segment control
const int bcdPins[] = {12, 13, 14, 15};   // BCD inputs A, B, C, D
const int enablePins[] = {16, 17, 18, 19}; // Common anode/cathode control for 4 displays
const int colonPin = 10; // Pin controlling colon (:)

// Timing variables
unsigned long lastUpdate = 0;
const unsigned long updateInterval = 1000; // 1-second updates

// Current time for display (HH:MM)
int currentTime[] = {0, 0, 0, 0}; // Example: 12:34 -> {1, 2, 3, 4}

void setup() {
  Serial.begin(9600);

  // Initialize RTC module
  if (!rtc.begin()) {
    Serial.println("RTC module not found. Check wiring.");
    while (1); // Halt if RTC is not detected
  }

  // Set RTC time manually (comment this line after the first upload to avoid overwriting time)
  rtc.adjust(DateTime(2025, 1, 8, 11, 02, 00)); // Set to specific time: YYYY, MM, DD, HH, MM, SS

  // Set up 7-segment display pins
  for (int i = 0; i < 4; i++) {
    pinMode(bcdPins[i], OUTPUT);
    pinMode(enablePins[i], OUTPUT);
    digitalWrite(enablePins[i], LOW); // Turn off all displays initially
  }
  pinMode(colonPin, OUTPUT); // Set colon pin as output
  digitalWrite(colonPin, LOW); // Turn colon off initially
}

void loop() {
  // Update time from RTC every second
  if (millis() - lastUpdate >= updateInterval) {
    updateTime();
    lastUpdate = millis();
  }

  // Multiplexing: Display HH:MM on 7-segment
  for (int i = 0; i < 4; i++) {
    // Set BCD pins for the current digit
    setBCD(currentTime[i]);

    // Enable the current display
    digitalWrite(enablePins[i], HIGH);
    delay(2); // Short delay for persistence

    // Disable the current display
    digitalWrite(enablePins[i], LOW);
  }

  // Blink colon every second
  digitalWrite(colonPin, (millis() / 500) % 2);
}

// Update the current time from RTC
void updateTime() {
  DateTime now = rtc.now();
  currentTime[0] = now.hour() / 10; // Tens place of hours
  currentTime[1] = now.hour() % 10; // Units place of hours
  currentTime[2] = now.minute() / 10; // Tens place of minutes
  currentTime[3] = now.minute() % 10; // Units place of minutes

  // Debugging: Print time to Serial Monitor
  Serial.print("Current Time: ");
  Serial.print(currentTime[0]);
  Serial.print(currentTime[1]);
  Serial.print(':');
  Serial.print(currentTime[2]);
  Serial.println(currentTime[3]);
}

// Set BCD pins based on the number to display
void setBCD(int number) {
  for (int i = 0; i < 4; i++) {
    digitalWrite(bcdPins[i], (number >> i) & 0x01);
  }
}
74LS47Breakout
GND5VSDASCLSQWRTCDS1307+