from machine import Pin
import time
# ===============================
# Slide switch
# ===============================
RUN_SW = Pin(18, Pin.IN, Pin.PULL_UP)
# 0 = ON (Program 1)
# 1 = OFF (Program 2)
# ===============================
# Digit pins (LEFT → RIGHT)
# ===============================
DIG1 = Pin(14, Pin.OUT)
DIG2 = Pin(15, Pin.OUT)
DIG3 = Pin(16, Pin.OUT)
DIG4 = Pin(17, Pin.OUT)
digits_pins = [DIG1, DIG2, DIG3, DIG4]
# ===============================
# Segment pins (a b c d e f g dp)
# ===============================
pins = [
Pin(6, Pin.OUT), # a
Pin(7, Pin.OUT), # b
Pin(8, Pin.OUT), # c
Pin(9, Pin.OUT), # d
Pin(10, Pin.OUT), # e
Pin(11, Pin.OUT), # f
Pin(12, Pin.OUT), # g
Pin(13, Pin.OUT) # dp
]
# ===============================
# Common cathode patterns
# ===============================
digits = [
[1,1,1,1,1,1,0,0], # 0
[0,1,1,0,0,0,0,0], # 1
[1,1,0,1,1,0,1,0], # 2
[1,1,1,1,0,0,1,0], # 3
[0,1,1,0,0,1,1,0], # 4
[1,0,1,1,0,1,1,0], # 5
[1,0,1,1,1,1,1,0], # 6
[1,1,1,0,0,0,0,0], # 7
[1,1,1,1,1,1,1,0], # 8
[1,1,1,1,0,1,1,0], # 9
]
# ===============================
def all_digits_off():
for d in digits_pins:
d.value(1)
# ===============================
def show_digit(num):
for i in range(7):
pins[i].value(digits[num][i])
# ===============================
# PROGRAM 1: Cube display
# ===============================
def program_1():
for n in range(2, 17):
if RUN_SW.value() == 1:
return
cube = n * n * n
s = "{:04d}".format(cube)
end = time.ticks_add(time.ticks_ms(), 1000)
while time.ticks_diff(end, time.ticks_ms()) > 0:
if RUN_SW.value() == 1:
return
for i in range(4):
all_digits_off()
show_digit(int(s[i]))
digits_pins[i].value(0)
time.sleep_ms(5)
digits_pins[i].value(1)
# ===============================
# PROGRAM 2: Digit-by-digit count
# ===============================
def program_2():
digit_order = [DIG1, DIG4, DIG2, DIG3]
for dig in digit_order:
if RUN_SW.value() == 0:
return
dig.value(0)
for num in range(9):
if RUN_SW.value() == 0:
return
show_digit(num)
time.sleep_ms(800)
dig.value(1)
# ===============================
# MAIN LOOP
# ===============================
all_digits_off()
while True:
# Switch ON → Program 1
if RUN_SW.value() == 0:
program_1()
# Switch OFF → Program 2
else:
program_2()