#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <RTClib.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
Adafruit_SSD1306 oled(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1); // create SSD1306 display object connected to I2C
RTC_DS1307 rtc;
String time;
String date;
void setup() {
Serial.begin(9600);
if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
while (true);
}
delay(2000);
oled.clearDisplay();
oled.setTextSize(1);
oled.setTextColor(WHITE);
oled.setCursor(0, 10);
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
Serial.flush();
while (true);
}
// rtc.adjust(DateTime(F(_DATE_), F(_TIME_))); // Comment or remove this line
time.reserve(10);
date.reserve(12);
}
void loop() {
DateTime now = rtc.now();
if (now.isValid()) {
// Adjust for Philippines time zone (UTC+8)
now = now + TimeSpan(8, 0, 0, 0);
time = "";
time += now.hour();
time += ':';
time += now.minute() < 10 ? "0" : "";
time += now.minute();
time += ':';
time += now.second();
date = "";
date += now.day();
date += '/';
date += now.month();
date += '/';
date += now.year();
oled.clearDisplay();
oled.setTextSize(1);
oled.setCursor(0, 0);
oled.println("Time");
oledDisplayCenter(time, 20);
oled.setTextSize(1);
oled.setCursor(0, 40);
oled.println("Date");
oledDisplayCenter(date, 50);
oled.display();
}
delay(1000);
}
void oledDisplayCenter(String text, int yPosition) {
int16_t x1;
int16_t y1;
uint16_t width;
uint16_t height;
oled.getTextBounds(text, 0, 0, &x1, &y1, &width, &height);
oled.setCursor((SCREEN_WIDTH - width) / 2, yPosition);
oled.println(text);
}