import machine
import time
seg_start = 0
adc_pin = 26
btn_pin = 16
num_digits = 4
samples = 1
decimals = 3
adc_max = float((2 ** 16) - 1)
btn_delay = 50
hex_map = [
0x40, 0x79, 0x24, 0x30, 0x19, 0x12, 0x02, 0x78,
0x00, 0x10, 0x08, 0x03, 0x46, 0x21, 0x06, 0x0E,
0x7F
]
curr_val = 0
seg_pins = []
dig_pins = []
adc = None
btn = None
digit = num_digits - 1
t = None
last_val = -1
last_btn = 0
def read_val(adc):
global curr_val, last_val
val = sum(adc.read_u16() for _ in range(samples)) // samples
volt = round((val / adc_max) * 3.3, decimals)
if volt != last_val:
last_val = volt
to_display = int(volt * (10 ** decimals))
if to_display > (10 ** num_digits - 1):
to_display = 10 ** num_digits - 1
if curr_val != to_display:
curr_val = to_display
clear_display()
return volt
def stop_disp():
global t
t.deinit()
def start_disp():
global t
t.init(period=4, mode=machine.Timer.PERIODIC, callback=show_next)
def show_next(timer):
global digit, curr_val
val = int(abs(curr_val) // (10 ** digit)) % 10
draw(val, digit, digit == decimals and decimals != 0)
digit = (digit - 1) % num_digits
def draw(val, pos, dot=False):
if val < 0 or val >= len(hex_map):
return
for p in dig_pins:
p.value(0)
bits = hex_map[val]
for i in range(7):
seg_pins[i].value((bits >> i) & 1)
seg_pins[7].value(not dot)
if pos == -1:
for p in dig_pins:
p.value(1)
elif 0 <= pos < num_digits:
dig_pins[pos].value(1)
def clear_display():
global digit
stop_disp()
digit = num_digits - 1
draw(16, -1)
time.sleep(0.1)
start_disp()
def setup():
global seg_pins, dig_pins, adc, btn, t
dig_pins = [machine.Pin(i, machine.Pin.OUT) for i in range(seg_start + 8, seg_start + 8 + num_digits)]
for p in dig_pins:
p.value(0)
seg_pins = [machine.Pin(i, machine.Pin.OUT) for i in range(seg_start, seg_start + 8)]
for p in seg_pins:
p.value(1)
adc = machine.ADC(adc_pin)
btn = machine.Pin(btn_pin, machine.Pin.IN, machine.Pin.PULL_UP)
t = machine.Timer()
start_disp()
if __name__ == '__main__':
setup()
while True:
if btn.value() == 0:
now = time.ticks_ms()
if now - last_btn > btn_delay:
last_btn = now
v = read_val(adc)
if v is not None:
print(f"Voltage: {v} V")
time.sleep(0.1)