#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_DS3231 rtc;
String time;
void setup() {
Serial.begin(9600);
// initialize OLED display with address 0x3C for 128x64
if(!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
delay(2000); // wait for initializing
oled.clearDisplay(); // clear display
oled.setTextSize(1); // text size
oled.setTextColor(WHITE); // text color
oled.setCursor(0, 5); // position to display
// SETUP RTC MODULE
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
Serial.flush();
for(;;);
}
// automatically sets the RTC to the date & time on PC this sketch was compiled
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
time.reserve(10); // to avoid fragmenting memory when using String
}
void Display(String text) {
int16_t x;
int16_t y;
uint16_t WIDTH;
uint16_t HEIGHT;
oled.getTextBounds(text, 0, 0, &x, &y, &WIDTH, &HEIGHT);
// display on horizontal and vertical center
oled.clearDisplay(); // clear display
oled.setCursor((SCREEN_WIDTH - WIDTH) / 2, (SCREEN_HEIGHT - HEIGHT) / 2);
oled.println(text); // text to display
oled.display();
}
void loop() {
DateTime now = rtc.now();
time = "";
time += now.hour();
time += ':';
time += now.minute();
time += ':';
time += now.second();
Display(time);
}