#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <RTClib.h> // RTC library
#define OLED_RESET 4 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(128, 64, &Wire, OLED_RESET);
RTC_DS1307 rtc; // Create RTC object
#define C_X 63
#define C_Y 31
void setup() {
// 初始化 OLED
display.begin(SSD1306_SWITCHCAPVCC, 0x3c); // Address 0x3C for 128x64
display.display();
delay(1000);
display.clearDisplay();
// 初始化 RTC
if (!rtc.begin()) {
display.println("Couldn't find RTC");
display.display();
while (1);
}
if (!rtc.isrunning()) {
display.println("RTC is NOT running!");
// 設定時間 (只需執行一次後可註解掉)
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
// 畫時鐘刻度
display.drawCircle(C_X, C_Y, 31, SSD1306_WHITE);
for (int i = 0; i < 360; i += 30) {
float t = 90 - i;
float theta_r = t * (PI / 180.0);
float x1 = C_X + 23 * cos(theta_r);
float y1 = C_Y - 23 * sin(theta_r);
float x2 = C_X + 27 * cos(theta_r);
float y2 = C_Y - 27 * sin(theta_r);
display.drawLine(x1, y1, x2, y2, SSD1306_WHITE);
}
display.display();
}
void loop() {
// 清除顯示畫面
display.clearDisplay();
// 取得 RTC 當前時間
DateTime now = rtc.now();
int h = now.hour();
int m = now.minute();
// 畫時鐘框架和刻度
display.drawCircle(C_X, C_Y, 31, SSD1306_WHITE);
for (int i = 0; i < 360; i += 30) {
float t = 90 - i;
float theta_r = t * (PI / 180.0);
float x1 = C_X + 23 * cos(theta_r);
float y1 = C_Y - 23 * sin(theta_r);
float x2 = C_X + 27 * cos(theta_r);
float y2 = C_Y - 27 * sin(theta_r);
display.drawLine(x1, y1, x2, y2, SSD1306_WHITE);
}
// 顯示時間文字
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 30);
display.print(h);
display.print(":");
display.print(m);
// 繪製時針
float t = 90 - (h % 12) * 30 - m * 0.5;
float theta_r = t * (PI / 180.0);
float x = C_X + 15 * cos(theta_r);
float y = C_Y - 15 * sin(theta_r);
display.drawLine(C_X, C_Y, x, y, SSD1306_WHITE);
// 繪製分針
t = 90 - m * 6;
theta_r = t * (PI / 180.0);
x = C_X + 25 * cos(theta_r);
y = C_Y - 25 * sin(theta_r);
display.drawLine(C_X, C_Y, x, y, SSD1306_WHITE);
// 顯示畫面
display.display();
delay(1000);
}