from machine import Pin, ADC
import time
# Segment pins (Common Anode: active LOW)
SEGMENTS = {
'a': Pin(0, Pin.OUT),
'b': Pin(1, Pin.OUT),
'c': Pin(2, Pin.OUT),
'd': Pin(3, Pin.OUT),
'e': Pin(4, Pin.OUT),
'f': Pin(5, Pin.OUT),
'g': Pin(6, Pin.OUT),
'dp': Pin(7, Pin.OUT)
}
# Digit control pins (right to left)
DIGITS = [
Pin(11, Pin.OUT), # Rightmost
Pin(10, Pin.OUT),
Pin(9, Pin.OUT),
Pin(8, Pin.OUT) # Leftmost
]
# Common anode segment patterns (0=ON, 1=OFF)
NUMBERS = {
0: {'a':0, 'b':0, 'c':0, 'd':0, 'e':0, 'f':0, 'g':1},
1: {'a':1, 'b':0, 'c':0, 'd':1, 'e':1, 'f':1, 'g':1},
2: {'a':0, 'b':0, 'c':1, 'd':0, 'e':0, 'f':1, 'g':0},
3: {'a':0, 'b':0, 'c':0, 'd':0, 'e':1, 'f':1, 'g':0},
4: {'a':1, 'b':0, 'c':0, 'd':1, 'e':1, 'f':0, 'g':0},
5: {'a':0, 'b':1, 'c':0, 'd':0, 'e':1, 'f':0, 'g':0},
6: {'a':0, 'b':1, 'c':0, 'd':0, 'e':0, 'f':0, 'g':0},
7: {'a':0, 'b':0, 'c':0, 'd':1, 'e':1, 'f':1, 'g':1},
8: {'a':0, 'b':0, 'c':0, 'd':0, 'e':0, 'f':0, 'g':0},
9: {'a':0, 'b':0, 'c':0, 'd':0, 'e':1, 'f':0, 'g':0}
}
# ADC Inputs
adc0 = ADC(26) # Slide potentiometer
adc1 = ADC(27) # Photoresistor
adc2 = ADC(28) # NTC Thermistor
# Globals
current_value = 0 # in millivolts (e.g., 3300 = 3.3V)
last_interrupt_time = 0 # for debouncing
# Display single digit
def display_digit(pos, num, show_dp=False):
pattern = NUMBERS.get(num, NUMBERS[0])
for seg, pin in SEGMENTS.items():
if seg == 'dp':
pin.value(0 if show_dp else 1) # Active LOW
else:
pin.value(pattern.get(seg, 1))
for i, d in enumerate(DIGITS):
d.value(1 if i == pos else 0)
# Display full number with optional decimal
def display_number(value):
# Format: 3300 → "3300" (3.300V)
str_val = "{:0>4}".format(value)[-4:]
digits = [int(c) for c in str_val]
for i in range(4):
show_dp = (i == 0) # show decimal after 1st digit (3.300)
display_digit(i, digits[i], show_dp)
time.sleep(0.002)
DIGITS[i].value(0)
# Detect active input and read voltage in millivolts
def read_active_sensor_mv():
val0 = adc0.read_u16()
val1 = adc1.read_u16()
val2 = adc2.read_u16()
threshold = 1000
# Convert raw to millivolts: 3.3V → 3300mV
def to_mv(raw): return int((raw / 65535) * 3300)
if val0 > threshold:
return to_mv(val0)
elif val1 > threshold:
return to_mv(val1)
elif val2 > threshold:
return to_mv(val2)
else:
return 0
# Interrupt handler
def button_handler(pin):
global current_value, last_interrupt_time
now = time.ticks_ms()
if time.ticks_diff(now, last_interrupt_time) > 200:
last_interrupt_time = now
current_value = read_active_sensor_mv()
print("Button pressed! Measured:", current_value, "mV")
# Setup button interrupt
button = Pin(16, Pin.IN, Pin.PULL_UP)
button.irq(trigger=Pin.IRQ_FALLING, handler=button_handler)
# Main loop
while True:
display_number(current_value)