---
disqus: ahb0222
GA : G-VF9ZT413CG
---
# Micropython NTP指針時鐘 OLED SSD1306
> [color=#40f1ef][name=LHB阿好伯, 2022/06/04][:earth_africa:](https://www.facebook.com/LHB0222/)
###### tags: `Micropython` `創客`
[TOC]
![](https://hackmd.io/_uploads/H1zzP1Yu9.jpg)
```python=
from machine import Pin, I2C, SoftI2C
import ssd1306
import time
import gfx
import math
'''
網路及NTP設定
'''
from machine import RTC
rtc = RTC()
import ntptime
from wifi_manager import WifiManager
# 初始化
wm = WifiManager()
# 可以自定義AP的SSID和密碼:
wm = WifiManager('AHB', '12345678')
wm.connect()
def tw_ntp(host='clock.stdtime.gov.tw', must=False):
ntptime.NTP_DELTA = 3155644800 # UTC+8 的 magic number
ntptime.host = host
count = 1
if must:
count = 100
for _ in range(count):
try:
ntptime.settime()
except:
time.sleep(1)
continue
else:
return True
return False
tw_ntp()
# using default address 0x3C
# i2c = I2C(sda=Pin(23), scl=Pin(19)) #硬體 I2C
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=400000) #慧手科技套件腳位
#i2c = SoftI2C(scl=Pin(19), sda=Pin(23), freq=400000) # 軟體 I2C
display = ssd1306.SSD1306_I2C(128, 64, i2c)
graphics = gfx.GFX(128, 64, display.pixel)
display.invert(0) # 螢幕顏色正常
#display.invert(1) # 螢幕顏色反轉
# display.rotate(True) # 螢幕旋轉180度
display.rotate(False) # 螢幕旋轉0度
display.text('Hello, World~~~', 0, 0, 1)
display.show() # 螢幕顯示
display.fill(0) # 填充螢幕 0 = 全黑, 1 = 全亮
time.sleep(1)
display.show() # 螢幕顯示
graphics.circle(31, 31, 29, 1) #circle(x0, y0, radius半徑, color) (x0, y0) 座標表示圓的中心
display.show()
#刻度
for i in range(1,13):
angle = i * 30
graphics.line(31+math.trunc(27*math.sin(math.radians(angle))),
31-math.trunc(27*math.cos(math.radians(angle))),
31+math.trunc(29*math.sin(math.radians(angle))),
31-math.trunc(29*math.cos(math.radians(angle))), 1) #line(x0, y0, x1, y1, color)
display.show()
#fill_circle(x0, y0, radius, color) #填充圓
graphics.circle(31, 31, 1, 1)
display.show()
while True:
if(wm.is_connected() == True):
new_time = rtc.datetime()
print("{h} : {m} : {s}".format(h=new_time[4]%12, m = new_time[5], s =new_time[6]))
time.sleep_ms(950)
graphics.circle(31, 31, 29, 1)
#時針
h_angle = new_time[4]%12 * 30
graphics.line(31, 31,
31+math.trunc(15*math.sin(math.radians(h_angle))),
31-math.trunc(15*math.cos(math.radians(h_angle))), 1)
display.show()
#分針
m_angle = new_time[5] * 360/60
graphics.line(31, 31,
31+math.trunc(25*math.sin(math.radians(m_angle))),
31-math.trunc(25*math.cos(math.radians(m_angle))), 1)
display.show()
display.fill_rect(53, 56, 17, 10, 0)
display.text(str(new_time[6]), 53, 56, 1) # 繪製文字(test, x, y, colour) colour=1為亮, 0 為滅
display.show() # 螢幕顯示
if new_time[6] == 59:
graphics.fill_circle(31, 31, 25, 0) #填充圓
graphics.circle(31, 31, 1, 1)
graphics.circle(31, 31, 29, 1)
```
![](https://hackmd.io/_uploads/rJbEIJFu9.jpg)
🌟全文可以至下方連結觀看或是補充
全文分享至
https://www.facebook.com/LHB0222/
https://www.instagram.com/ahb0222/
有疑問想討論的都歡迎於下方留言
喜歡的幫我分享給所有的朋友 \o/
有所錯誤歡迎指教
# [:page_with_curl: 全部文章列表](https://hackmd.io/@LHB-0222/AllWritings)
![](https://i.imgur.com/nHEcVmm.jpg)