#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 date;
String time;
void setup() {
Serial.begin(9600);
// initialize OLED display with address 0x3C for 128x64
if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
while (true);
}
delay(1000); // wait for initializing
oled.clearDisplay(); // clear display
oled.setTextSize(2); // text size
oled.setTextColor(WHITE); // text color
// SETUP RTC MODULE
if (! rtc.begin()) {
Serial.println("Couldn't find RTC");
Serial.flush();
while (true);
}
// automatically sets the RTC to the date & time on PC this sketch was compiled
// rtc.adjust(DateTime(2024, 11, 20, 9, 3, 0)); // Format: yyyy, mm, dd, hh, mm, ss
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
time.reserve(10); // to avoid fragmenting memory when using String
}
void loop() {
int16_t x1;
int16_t y1;
uint16_t width;
uint16_t height;
// Clear the OLED display
oled.fillScreen(BLACK);
DateTime now = rtc.now();
// Format tanggal dengan leading zero
date = "";
// Tambahkan leading zero untuk hari
if (now.day() < 10) date += "0";
date += now.day();
date += "/";
// Tambahkan leading zero untuk bulan
if (now.month() < 10) date += "0";
date += now.month();
date += "/";
date += now.year();
// Format waktu dengan leading zero
time = "";
// Tambahkan leading zero untuk jam
if (now.hour() < 10) time += "0";
time += now.hour();
time += ':';
// Tambahkan leading zero untuk menit
if (now.minute() < 10) time += "0";
time += now.minute();
time += ':';
// Tambahkan leading zero untuk detik
if (now.second() < 10) time += "0";
time += now.second();
// Print the date and time to the OLED display
oled.getTextBounds(date, 0, 0, &x1, &y1, &width, &height);
oled.setCursor((SCREEN_WIDTH - width) / 2, (SCREEN_HEIGHT + height) / 2);
oled.println(date);
oled.getTextBounds(time, 0, 0, &x1, &y1, &width, &height);
oled.setCursor((SCREEN_WIDTH - width) / 2, (SCREEN_HEIGHT - 3*height) / 2);
oled.print(time);
oled.display();
}
Loading
ssd1306
ssd1306