from machine import Pin, PWM, ADC
import time
servo = PWM(Pin(15))
servo.freq(50)
pot = ADC(Pin(26))
# Servo Duty Limits (0.5ms to 2.5ms roughly)
MIN_DUTY = 1000 # 0 degrees
MAX_DUTY = 9000 # 180 degrees
# Jitter prevention
threshold = 150 # Only move if the change is greater than this
last_duty = 0
def map_range(value, in_min, in_max, out_min, out_max):
"""Maps a value from one range to another."""
return (value - in_min) * (out_max - out_min) // (in_max - in_min) + out_min
print("Servo Control Initialized. Turn the potentiometer!")
while True:
# 1. Read the raw ADC value (0 to 65535)
adc_val = pot.read_u16()
# 2. Map the ADC value to the Servo Duty Cycle
duty = map_range(adc_val, 0, 65535, MIN_DUTY, MAX_DUTY)
# 3. Check if the change is large enough to warrant a move (prevents jitter)
if abs(duty - last_duty) > threshold:
# Clamp duty to be safe
duty = max(MIN_DUTY, min(MAX_DUTY, duty))
servo.duty_u16(duty)
last_duty = duty
# 4. Small delay to let the CPU breathe
time.sleep(0.02)