#include <Wire.h>
#include <RTClib.h> // Include the RTClib library
const int clock = 3; // Clock pin for the 7-segment display
const int data = 2; // Data pin for the 7-segment display
// 7-segment display digit encoding (0-9)
uint8_t digits[] = { 0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f };
RTC_DS3231 rtc; // Create an RTC object for DS3231
void setup() {
pinMode(clock, OUTPUT);
pinMode(data, OUTPUT);
// Start the Serial Monitor for debugging
Serial.begin(9600);
// Initialize the RTC
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}
// Check if the RTC lost power
if (rtc.lostPower()) {
Serial.println("RTC lost power, setting the time!");
// Set the RTC to the compile time (this is for the first time setting)
rtc.adjust(DateTime(F(_DATE), F(TIME_)));
}
// Initialize the display
start();
writeValue(0x8c); // Set brightness
stop();
clearDisplay();
}
void loop() {
// Get the current time from the RTC
DateTime now = rtc.now();
// Add 36 seconds to the current time
now = now + TimeSpan(0, 0, 0, 36); // Add 36 seconds (TimeSpan(hours, minutes, seconds, days))
// Extract hours, minutes, and seconds
uint8_t hours = now.hour();
uint8_t minutes = now.minute();
uint8_t seconds = now.second();
// Update display every second
writeDigits(hours, minutes, seconds);
// Delay for 1 second to simulate real-time updates
delay(1000); // Delay for 1 second before the next loop
}
// Write digits to the 7-segment display
void writeDigits(uint8_t hours, uint8_t minutes, uint8_t seconds) {
uint8_t first = digits[hours / 10];
uint8_t second = digits[hours % 10] | 0x80; // Keep colon always on
uint8_t third = digits[minutes / 10];
uint8_t fourth = digits[minutes % 10];
write(first, second, third, fourth);
}
// Clear the display
void clearDisplay() {
write(0x00, 0x00, 0x00, 0x00);
}
// Write data to the display
void write(uint8_t first, uint8_t second, uint8_t third, uint8_t fourth) {
start();
writeValue(0x40); // Set to auto-increment mode
stop();
start();
writeValue(0xc0); // Address command
writeValue(first);
writeValue(second);
writeValue(third);
writeValue(fourth);
stop();
}
// Send start signal
void start() {
digitalWrite(clock, HIGH);
digitalWrite(data, HIGH);
delayMicroseconds(5);
digitalWrite(data, LOW);
digitalWrite(clock, LOW);
delayMicroseconds(5);
}
// Send stop signal
void stop() {
digitalWrite(clock, LOW);
digitalWrite(data, LOW);
delayMicroseconds(5);
digitalWrite(clock, HIGH);
digitalWrite(data, HIGH);
delayMicroseconds(5);
}
// Write a single byte to the display
bool writeValue(uint8_t value) {
for (uint8_t i = 0; i < 8; i++) {
digitalWrite(clock, LOW);
delayMicroseconds(5);
digitalWrite(data, (value & (1 << i)) >> i);
delayMicroseconds(5);
digitalWrite(clock, HIGH);
delayMicroseconds(5);
}
digitalWrite(clock, LOW);
delayMicroseconds(5);
pinMode(data, INPUT);
digitalWrite(clock, HIGH);
delayMicroseconds(5);
bool ack = digitalRead(data) == 0;
pinMode(data, OUTPUT);
return ack;
}