from machine import Pin, Timer, ADC, PWM
import time
# -------------------------------
# Pin Setup
# -------------------------------
DIGIT_START = 7 # First digit select pin (digits at pins 7,8,9,10)
DOT_PIN = 11 # Pin for decimal point
SEGMENT_PINS = list(range(7)) # Segment pins A-G (GPIO 0 to 6)
# -------------------------------
# Segment Codes for Numbers 0-9
# -------------------------------
SEGMENT_CODES = [
0xC0, # 0
0xF9, # 1
0xA4, # 2
0xB0, # 3
0x99, # 4
0x92, # 5
0x82, # 6
0xF8, # 7
0x80, # 8
0x90 # 9
]
# -------------------------------
# Global Variables
# -------------------------------
display_value = 10 # Start at 10
# -------------------------------
# ADC and PWM Setup
# -------------------------------
reading = ADC(26)
led_pwm = PWM(Pin(27))
led_pwm.freq(1000)
# -------------------------------
# Functions
# -------------------------------
def update_display_value(timer):
global display_value
read = reading.read_u16()
display_value = int((3.3 * read / 65535) * 1000) # Scale the value to a range of 0-99
print(f"Display Value: {display_value}") # Print the current value for debugging
def show_digit(number, position, show_dot=False):
"""Display a single digit on the given position."""
code = SEGMENT_CODES[number]
# Set segments (A-G) on pins 0-6 according to the code bits.
for i in range(7):
segment_state = (code >> i) & 1
Pin(i, Pin.OUT).value(segment_state)
# Set the decimal point (active LOW)
Pin(DOT_PIN, Pin.OUT).value(0 if show_dot else 1)
# Enable the selected digit by turning its corresponding pin ON.
Pin(DIGIT_START + position, Pin.OUT).on()
def scan_display():
"""Continuously update the display by scanning all digits."""
global display_value
number = display_value
for i in range(3, -1, -1):
digit = number % 10 # Get the current digit (least significant digit)
show_dot = (i == 0) # Optional: show decimal point on rightmost digit only
show_digit(digit, i, show_dot)
time.sleep(0.02) # Short delay for multiplexing persistence
Pin(DIGIT_START + i, Pin.OUT).off() # Disable the digit after displaying
number //= 10 # Move to the next digit
def setup():
"""Initialize all digit select and dot pins to a known state."""
for i in range(4):
Pin(DIGIT_START + i, Pin.OUT).value(0)
Pin(DOT_PIN, Pin.OUT).value(1)
def control_led_brightness():
"""Control LED brightness based on the potentiometer value."""
# Read potentiometer value (ADC)
pot_value = reading.read_u16()
# Map potentiometer value to the duty cycle (range 0-65535)
led_pwm.duty_u16(pot_value) # Use PWM to control brightness (0-65535)
# -------------------------------
# Main Loop
# -------------------------------
def main():
setup()
# Create a Timer to update the display value every 1000 milliseconds (1 second)
Timer().init(period=1000, mode=Timer.PERIODIC, callback=update_display_value)
while True:
scan_display() # Update the 7-segment display
control_led_brightness() # Adjust LED brightness based on potentiometer value
# Run the program
main()