import machine
import time
# SEGMENT PINS → GP0–GP7 (A to DP)
SEGMENT_PINS = [
machine.Pin(0, machine.Pin.OUT), # A
machine.Pin(1, machine.Pin.OUT), # B
machine.Pin(2, machine.Pin.OUT), # C
machine.Pin(3, machine.Pin.OUT), # D
machine.Pin(4, machine.Pin.OUT), # E
machine.Pin(5, machine.Pin.OUT), # F
machine.Pin(6, machine.Pin.OUT), # G
machine.Pin(7, machine.Pin.OUT), # DP
]
# DIGIT PINS (REVERSED ORDER) → GP11 to GP8 (DIG1–DIG4)
DIGIT_PINS = [
machine.Pin(11, machine.Pin.OUT), # DIG1 (leftmost)
machine.Pin(10, machine.Pin.OUT), # DIG2
machine.Pin(9, machine.Pin.OUT), # DIG3
machine.Pin(8, machine.Pin.OUT), # DIG4 (rightmost)
]
# BUTTON + ANALOGUE
BUTTON_PIN = 16
ADC_PIN = 26
# Segment map for 0-9 (A to G)
SEGMENT_MAP = {
0: 0b00111111, # A B C D E F
1: 0b00000110, # B C
2: 0b01011011, # A B D E G
3: 0b01001111, # A B C D G
4: 0b01100110, # B C F G
5: 0b01101101, # A C D F G
6: 0b01111101, # A C D E F G
7: 0b00000111, # A B C
8: 0b01111111, # All
9: 0b01101111, # A B C D F G
}
display_value = 0.0 # Global voltage to show
def read_analogue_voltage(pin):
adc = machine.ADC(pin)
raw_value = adc.read_u16()
voltage = (raw_value / 65535) * 3.3
return round(voltage, 3)
def handle_button_interrupt(pin):
global display_value
display_value = read_analogue_voltage(ADC_PIN)
print("Button pressed! Voltage =", display_value)
button = machine.Pin(BUTTON_PIN, machine.Pin.IN, machine.Pin.PULL_UP)
button.irq(trigger=machine.Pin.IRQ_FALLING, handler=handle_button_interrupt)
def display_digit(digit_value, digit_index):
segment_value = SEGMENT_MAP.get(digit_value, 0)
for pin in SEGMENT_PINS:
pin.value(1) # OFF (Common Anode)
for i in range(7):
if segment_value & (1 << i):
SEGMENT_PINS[i].value(0) # ON
for pin in DIGIT_PINS:
pin.value(1) # All OFF
DIGIT_PINS[digit_index].value(0) # Enable current digit
def scan_display(timer):
global display_value
voltage_str = "{:.3f}".format(display_value).replace(".", "")
# Pad to 4 digits manually (NO ljust)
while len(voltage_str) < 4:
voltage_str += "0"
voltage_str = voltage_str[:4]
digits = [int(d) for d in voltage_str]
for i in range(4):
display_digit(digits[i], i)
time.sleep(0.002)
for i in range(4):
display_digit(digits[i], i)
time.sleep(0.002)
def enable_display_timer():
display_timer = machine.Timer()
display_timer.init(period=5, mode=machine.Timer.PERIODIC, callback=scan_display)
def setup():
enable_display_timer()
if __name__ == '__main__':
setup()
while True:
time.sleep(1)