import machine
from sh1107 import SH1107_I2C
import time
import math
# I2C 初始化
i2c = machine.I2C(0, scl=machine.Pin(17), sda=machine.Pin(16), freq=400000)
display = SH1107_I2C(128, 128, i2c, address=0x3C, rotate=0)
display.sleep(False)
display.contrast(255)
center_x, center_y = 64, 64
def draw_filled_circle(display, x, y, r, c):
"""手動繪製填充圓形替代 fill_circle"""
display.circle(x, y, r, c)
for i in range(1, r):
a = int(math.sqrt(r*r - i*i))
display.hline(x-a, y+i, a*2, c)
display.hline(x-a, y-i, a*2, c)
def draw_background(display):
display.fill(0)
display.circle(center_x, center_y, 63, 1)
# 60 分鐘/秒點點
for i in range(60):
x = round(center_x + math.sin(math.radians(i * 6)) * 60)
y = round(center_y - math.cos(math.radians(i * 6)) * 60)
display.pixel(x, y, 1)
# 小時刻度線
for i in range(12):
if i % 3 != 0:
x1 = round(center_x + math.sin(math.radians(i * 30)) * 54)
y1 = round(center_y - math.cos(math.radians(i * 30)) * 54)
x2 = round(center_x + math.sin(math.radians(i * 30)) * 46)
y2 = round(center_y - math.cos(math.radians(i * 30)) * 46)
display.line(x1, y1, x2, y2, 1)
# 數字標記(調整字體位置)
display.text('12', 57, 12, 1)
display.text('3', 108, 67, 1)
display.text('6', 57, 116, 1)
display.text('9', 5, 67, 1)
# 細指針(秒針)- 簡化版
def draw_hand_thin(display, angle, length_long, length_short):
x1 = round(center_x + math.sin(math.radians(angle)) * length_long)
y1 = round(center_y - math.cos(math.radians(angle)) * length_long)
x2 = round(center_x + math.sin(math.radians(angle + 180)) * length_short)
y2 = round(center_y - math.cos(math.radians(angle + 180)) * length_short)
display.line(x1, y1, x2, y2, 1)
# 用小圓圈替代 fill_circle
display.circle(x2, y2, 3, 1)
# 粗指針(分針、時針)- 簡化版
def draw_hand_bold(display, angle, length_long, length_short, dot_size):
x1 = round(center_x + math.sin(math.radians(angle)) * length_long)
y1 = round(center_y - math.cos(math.radians(angle)) * length_long)
x2 = round(center_x + math.sin(math.radians(angle)) * length_short)
y2 = round(center_y - math.cos(math.radians(angle)) * length_short)
display.line(center_x, center_y, x2, y2, 1)
display.circle(x1, y1, dot_size, 1) # 端點圓圈
display.circle(x2, y2, dot_size, 1)
# 移除 triangle,改用粗線條效果
# 主迴圈
seconds = minutes = hours = 10
while True:
draw_background(display)
# 繪製指針
draw_hand_bold(display, minutes * 6, 48, 15, 2) # 分針
draw_hand_bold(display, (hours % 12) * 30 + (minutes / 2), 32, 15, 2) # 時針
draw_hand_thin(display, seconds * 6, 56, 4) # 秒針
# 中心圓盤
display.fill_rect(center_x-4, center_y-4, 9, 9, 0) # 黑色中心
display.circle(center_x, center_y, 4, 1)
display.show()
time.sleep(1)
seconds += 1
if seconds >= 60:
seconds = 0
minutes += 1
if minutes >= 60:
minutes = 0
hours += 1