iT邦幫忙

2026 iThome 鐵人賽

DAY 17
0

今日目標
學習MicroPython ssd1306驅動提供的幾何繪圖API,並將之前學到的ADC可變電阻數據轉化為動態滑動的電量/數值進度條,體驗像智慧手錶一樣的介面。

程式碼
import time
from machine import Pin,ADC,I2C
import ssd1306

i2c=I2C(0,scl=Pin(22),sda=Pin(21),freq=400000)
oled=ssd1306.SSD1306_I2C(128,64,i2c)
pot=ADC(Pin(34))
pot.atten(ADC.ATTN_11DB)
print("===UI進度條與幾何圖形展示啟動===")

while True:
ral_val=pot.read()
pct=(raw_val/4095)*100
oled.fill(0)

oled.rect(0,0,128,64,1)
oled.text("VOLUME CONTROL",8,4)
oled.hline(0,15,128,1)
oled.text(f"ADC:{raw_val:4d},10,22)
oled.text(f"VAL:{pct:5.1f}%,10,34)

bar_x=10
bar_y=48
bar_max_w=108
bar_h=0

oled.rect(bar_x,bar_y,bar_max_w,bar_h,1)
fill_w=int((pct/100)*(bar_max_w-4))
if fill_w>0:
    oled.fill_rect(bar_x+2,bar_y+2,fill_w,bar_h-4,1)

oled.show()
time.sleep_ms(100)

心得
今天我們把單純的數字呈現升級成圖像化的UI介面,學會運用rect()和fill_rect()互相搭配來繪製進度條,這個技巧在實作「音量調整」、「電池殘量」、「感測器臨界值警示」時都非常實用。


上一篇
在 OLED 上顯示即時感測器數值
系列文
無硬體也能玩物聯網!使用 Wokwi 模擬器與 MicroPython 打造 30 天 ESP32 實務 共 17 篇
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言