# https://wokwi.com/projects/443315705910393857
from machine import Pin, Timer
import time
pins_segment = [None] * 8
pins_digit = [None] * 8
# 共陽數碼管段碼(gfedcba 順序)
digit_codes = {
0: 0b11000000, 1: 0b11111001, 2: 0b10100100, 3: 0b10110000, 4: 0b10011001,
5: 0b10010010, 6: 0b10000010, 7: 0b11111000, 8: 0b10000000, 9: 0b10010000,
}
def segmentize(num):
return (
num % 10, (num // 10) % 10, (num // 100) % 10, (num // 1000) % 10,
(num // 10000) % 10, (num // 100000) % 10, (num // 1000000) % 10, (num // 10000000) % 10
)
#Timer Function Callback
def TimerTick(t):
global counter, led
counter += 1
led.toggle()
# 定義引腳(段腳 + 位選腳)
for i in range(8):
pins_segment[i] = Pin(i, Pin.OUT) # a, b, c, d, e, f, g, dp
for i in range(8):
pins_digit[i] = Pin(i+8, Pin.OUT) # 位8(最左側數碼管)/位1(最右側數碼管)
# 要顯示的數位:
counter = 12345678
led = Pin('LED', Pin.OUT)
tim0 = Timer()
# tim0.init(period=200, mode=Timer.PERIODIC, callback=TimerTick)
tim0.init(freq=5, mode=Timer.PERIODIC, callback=TimerTick)
try:
while True:
digits_to_show = segmentize(counter)
for digit_idx in range(8): # 遍歷4個數碼管
# 步驟1:關閉所有位選(避免串擾)
for pin in pins_digit:
pin.off() # 共陽數碼管,off為低電平,關閉
# 步驟2:設置當前數碼管的段碼
code = digit_codes[digits_to_show[digit_idx]]
for i in range(7): # 處理a - g段(共7段)
pins_segment[i].value((code >> i) & 1)
pins_segment[7].value(1) # dp默認不亮(高電平)
# 步驟3:打開當前位元選,顯示該數碼管
pins_digit[digit_idx].on() # 共陽數碼管,on為高電平,點亮
# 掃描間隔(視覺暫留,可調整)
# time.sleep_us(500)
time.sleep_ms(500)
except KeyboardInterrupt:
# 中斷時關閉所有引腳
for pin in pins_segment + pins_digit:
pin.off()