from machine import Pin, ADC, PWM
import time
# --- Setup ---
# Initialize the potentiometer on ADC pin 26
pot = ADC(26)
# Initialize the servo motor on PWM pin 15 and set its frequency to 50Hz
servo = PWM(Pin(15))
servo.freq(50)
# Define the GPIO pins for the 5 LEDs and initialize them as outputs
led_pins = [2, 3, 4, 5, 6]
leds = [Pin(p, Pin.OUT) for p in led_pins]
def set_angle(angle):
"""
Converts a 0-180 degree angle to the corresponding PWM duty cycle.
Calculates the pulse width in microseconds and converts it to a 16-bit duty value.
"""
min_us = 500
max_us = 2500
us = min_us + (angle / 180) * (max_us - min_us)
duty = int((us / 20000) * 65535)
servo.duty_u16(duty)
# --- Main Loop ---
while True:
# Read the potentiometer value (0 to 65535)
value = pot.read_u16()
# 1. Servo Control: Map the potentiometer value to an angle (0-180 degrees)
angle = int((value / 65535) * 180)
set_angle(angle)
# 2. LED Control: Divide the range into 5 segments to determine how many LEDs to turn on
# Using floor division (//) to get a result between 0 and 5
num_leds_on = value // 13107
# Ensure the number of LEDs doesn't exceed 5
if num_leds_on > 5:
num_leds_on = 5
# Loop through the LED list to turn them on or off based on the calculated count
for i in range(5):
if i < num_leds_on:
leds[i].value(1) # Turn LED on
else:
leds[i].value(0) # Turn LED off
# Small delay to keep the system responsive
time.sleep(0.05)