#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <RTClib.h>
// OLED Display setup
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
// RTC setup
RTC_DS1307 rtc;
void setup() {
// Start the Serial Monitor
Serial.begin(9600);
// Initialize OLED display
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}
display.display();
delay(2000); // Wait for 2 seconds
display.clearDisplay();
// Initialize RTC
if (!rtc.begin()) {
Serial.println(F("Couldn't find RTC"));
while (1);
}
// Check if the RTC is running
if (!rtc.isrunning()) {
Serial.println(F("RTC is NOT running! Setting the time..."));
rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); // Set the RTC to compile time
}
}
void loop() {
// Get current time
DateTime now = rtc.now();
// Format time as HH:MM:SS
int hour = now.hour();
int minute = now.minute();
int second = now.second();
// Clear the display
display.clearDisplay();
// Set text size and color
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
// Display time on OLED
display.setCursor(0, 0);
display.print(F("Time: "));
display.print(hour < 10 ? "0" : ""); // Display leading zero for hours < 10
display.print(hour);
display.print(F(":"));
display.print(minute < 10 ? "0" : ""); // Display leading zero for minutes < 10
display.print(minute);
display.print(F(":"));
display.print(second < 10 ? "0" : ""); // Display leading zero for seconds < 10
display.print(second);
// Update the display
display.display();
delay(1000); // Update every second
}