import machine
import utime
# Pin Definitions
SEGMENT_PINS = [0, 1, 2, 3, 4, 5, 6, 7] # a-g, dp segments
DIGIT_PINS = [11, 10, 9, 8] # Digit select pins
BUTTON_PIN = 16 # Push button
POT_PIN = 26 # Potentiometer ADC input
# 7-segment patterns for digits 0-9 (common cathode)
DIGIT_PATTERNS = [
[0,0,0,0,0,0,1,1], # 0
[1,0,0,1,1,1,1,1], # 1
[0,0,1,0,0,1,0,1], # 2
[0,0,0,0,1,1,0,1], # 3
[1,0,0,1,1,0,0,1], # 4
[0,1,0,0,1,0,0,1], # 5
[0,1,0,0,0,0,0,1], # 6
[0,0,0,1,1,1,1,1], # 7
[0,0,0,0,0,0,0,1], # 8
[0,0,0,0,1,0,0,1] # 9
]
class SevenSegmentDisplay:
def __init__(self):
self.segments = [machine.Pin(p, machine.Pin.OUT) for p in SEGMENT_PINS]
self.digits = [machine.Pin(p, machine.Pin.OUT) for p in DIGIT_PINS]
self.clear()
def clear(self):
self.buffer = [(0, False)] * 4 # Initialize with all digits off
def refresh(self):
for digit in range(4):
# Turn off all digits
for d in self.digits:
d.value(0)
# Set segments for current digit
num, dp = self.buffer[digit]
for seg in range(7):
self.segments[seg].value(DIGIT_PATTERNS[num][seg])
self.segments[7].value(0 if dp else 1) # Decimal point
# Enable current digit
self.digits[digit].value(1)
utime.sleep_us(2000) # Display each digit for 2ms
self.digits[digit].value(0)
def show_voltage(self, voltage):
# Format voltage as 0.000 to 3.300
text = "{:04.3f}".format(min(3.300, max(0.000, voltage)))
self.buffer = []
for i, c in enumerate(text.replace(".", "")):
self.buffer.append((int(c), i == 3)) # 4th position is decimal point
class Voltmeter:
def __init__(self):
self.display = SevenSegmentDisplay()
self.pot = machine.ADC(machine.Pin(POT_PIN))
self.button = machine.Pin(BUTTON_PIN, machine.Pin.IN, machine.Pin.PULL_UP)
self.last_press = 0
self.button.irq(trigger=machine.Pin.IRQ_FALLING, handler=self._button_handler)
self.display.clear()
def _button_handler(self, pin):
# Debounce with 200ms threshold
current_time = utime.ticks_ms()
if utime.ticks_diff(current_time, self.last_press) > 200:
self.last_press = current_time
self._update_display()
def _update_display(self):
# Read and display voltage for 2 seconds
voltage = self.pot.read_u16() * 3.3 / 65535
self.display.show_voltage(voltage)
print("Voltage:", voltage, "V")
# Display for 2 seconds
start = utime.ticks_ms()
while utime.ticks_diff(utime.ticks_ms(), start) < 2000:
self.display.refresh()
# Clear display
self.display.clear()
def run(self):
print("Potentiometer Voltmeter Ready")
while True:
self.display.refresh()
utime.sleep_ms(10)
# Start the application
if __name__ == "__main__":
voltmeter = Voltmeter()
voltmeter.run()