# from machine import Pin , PWM , ADC
# import time
# servo = PWM(Pin(0) , freq=50)
# pot = ADC(Pin(34))
# pot.atten(ADC.ATTN_11DB)
# pot.width(ADC.WIDTH_12BIT)
# def angle_to_duty(servo,angle):
# min_duty = 20
# max_duty = 120
# duty = min_duty + (max_duty - min_duty) * (angle / 180)
# servo.duty(int(duty))
# def map_value(x, in_min, in_max, out_min, out_max):
# return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
# while True:
# pot_value = pot.read()
# intmd_value = map_value(pot_value,0,4095,0,180)
# angle_to_duty(servo,intmd_value)
# time.sleep(0.05)
from machine import Pin, PWM, ADC
from time import sleep
# Define pins
servo_pin = 17 # GPIO pin to which the servo is connected
potentiometer_pin = 34 # ADC pin to which the potentiometer is connected
# Set up PWM for servo
frequency = 50 # Frequency in Hz (50Hz for standard servo motors)
servo_pwm = PWM(Pin(servo_pin), freq=frequency)
# Set up ADC for potentiometer
adc = ADC(Pin(potentiometer_pin))
adc.atten(ADC.ATTN_11DB) # Full range: 3.3V
adc.width(ADC.WIDTH_10BIT) # 12-bit resolution
def set_servo_angle(pwm, angle):
min_duty = 20
max_duty = 120
duty = min_duty + (max_duty - min_duty) * (angle / 180)
pwm.duty(int(duty))
def map_value(x, in_min, in_max, out_min, out_max):
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
try:
while True:
# Read the potentiometer value (0-4095)
pot_value = adc.read()
# Map the potentiometer value to an angle (0-180 degrees)
angle = map_value(pot_value, 0, 1023, 0, 180)
# Set the servo angle
set_servo_angle(servo_pwm, angle)
# Small delay to avoid flooding the servo with commands
sleep(0.05)
except KeyboardInterrupt:
# Deinitialize the PWM to turn off the servo
servo_pwm.deinit()