from machine import Pin, ADC, PWM
import time
pot = ADC(Pin(34))
pot.atten(ADC.ATTN_11DB)
pot.width(ADC.WIDTH_12BIT)
servo = PWM(Pin(32))
servo.freq(50)
MIN_US = 500
MAX_US = 2500
PERIOD_US = 20000
leds = [Pin(pin, Pin.OUT) for pin in [14, 27, 25]]
btn_on = Pin(12, Pin.IN, Pin.PULL_UP)
btn_off = Pin(13, Pin.IN, Pin.PULL_UP)
def angle_to_duty(angle):
angle = max(0, min(180, angle))
pulse = MIN_US + (MAX_US - MIN_US) * angle / 180
return int(pulse * 65535 / PERIOD_US)
def read_pot_smooth(samples=10):
total = 0
for _ in range(samples):
total += pot.read()
time.sleep_ms(2)
return total // samples
def update_leds(angle):
leds[0].value(1 if angle >= 60 else 0)
leds[1].value(1 if angle >= 120 else 0)
leds[2].value(1 if angle >= 180 else 0)
def turn_off_leds():
for led in leds:
led.value(0)
servo_on = False
last_angle = -1
while True:
print(servo_on)
if not btn_on.value():
servo_on = True
time.sleep_ms(300) # debounce
if not btn_off.value():
servo_on = False
servo.deinit() # stop servo signal
turn_off_leds()
time.sleep_ms(300)
if servo_on:
adc_value = read_pot_smooth()
angle = int(adc_value * 180 / 4095)
if angle != last_angle:
servo.init(freq=50)
servo.duty_u16(angle_to_duty(angle))
update_leds(angle)
last_angle = angle
time.sleep_ms(40)