import machine
import math
import time
from machine import Pin
# Pin and constant definitions
LED_PIN = 16 # Pin for LED
POT_PIN = 26 # Pin for Potentiometer (Analog Input)
SEVEN_SEGMENT_PINS = [0, 1, 2, 3, 4, 5, 6, 7] # Segment pins for 7-segment display
DISPLAY_PINS = [8, 9, 10, 11] # Display selection pins
# Constants
ADC_RANGE = 65535 # Maximum ADC value (16-bit)
LED_THRESHOLD = 2.5 # Threshold voltage for LED
# Hex values for 7-segment display digits (0-9) and decimal point (.)
SEGMENTS = [
0x3F, # 0
0x06, # 1
0x5B, # 2
0x4F, # 3
0x66, # 4
0x6D, # 5
0x7D, # 6
0x07, # 7
0x7F, # 8
0x6F, # 9
]
DECIMAL_POINT = 0x80 # Hex value for turning on the decimal point
# Initialize pins
led = Pin(LED_PIN, Pin.OUT)
pot = machine.ADC(Pin(POT_PIN)) # Potentiometer
pot.atten(machine.ADC.ATTN_0DB) # Set full-scale voltage (0-3.3V)
pot.width(machine.ADC.WIDTH_12BIT) # Set ADC resolution to 12 bits (0-4095)
# Display pins
segment_pins = [Pin(pin, Pin.OUT) for pin in SEVEN_SEGMENT_PINS]
display_select_pins = [Pin(pin, Pin.OUT) for pin in DISPLAY_PINS]
# Function to read potentiometer and convert to voltage
def read_pot():
adc_value = pot.read() # Read raw ADC value
voltage = (adc_value / ADC_RANGE) * 3.3 # Convert to voltage (0-3.3V)
return voltage
# Function to display a digit on the 7-segment display
def display_digit(digit, display_index, decimal_point=False):
# Turn off all displays
for pin in display_select_pins:
pin.value(0)
# Set segment pins for the digit
segments = SEGMENTS[digit]
if decimal_point:
segments |= DECIMAL_POINT # Add the decimal point to the segments
for i in range(7):
segment_pins[i].value((segments >> i) & 1)
# Turn on the selected display
display_select_pins[display_index].value(1)
# Function to display the voltage on the 7-segment display
def display_voltage(voltage):
voltage_str = "{:.2f}".format(voltage) # Format voltage with 2 decimal places
for i, char in enumerate(voltage_str):
if char == '.':
# Do not display anything for decimal point
continue
else:
decimal_point = (i == 2) # Display decimal point after the second digit
display_digit(int(char), i, decimal_point)
# Main loop
def main():
while True:
voltage = read_pot() # Read the voltage from the potentiometer
print(f"Potentiometer Voltage: {voltage:.2f}V")
# Display the voltage on the 7-segment display
display_voltage(voltage)
# Turn LED on if voltage exceeds threshold, otherwise turn off
if voltage >= LED_THRESHOLD:
led.value(1) # Turn LED on
else:
led.value(0) # Turn LED off
time.sleep(0.1) # Delay to update the display
# Run the main loop
main()