import machine
import time
# Initialize the timer
tim = machine.Timer(0)
# Initialize the PWM channel
pwm = machine.Pin(4)
servo = machine.PWM(pwm,50,0)
# Define the pulse width range
min_pulse_width = 500
max_pulse_width = 2400
# Define the servo angle range
min_angle = 0
max_angle = 180
# Define a function to set the servo angle
def set_servo_angle(angle):
# Calculate the pulse width from the angle
#pulse_width = int((max_pulse_width - min_pulse_width) * angle / (max_angle - min_angle) + min_pulse_width)
pulse_width =(int)(((angle/180*(2400-500))+500)/20000*1023)
# Set the duty cycle
print(pulse_width)
servo.duty(pulse_width)
# Define a function to move the servo back and forth
def move_servo():
# Move the servo from 0 to 180 degrees
for angle in range(0, 181):
set_servo_angle(angle)
time.sleep(0.5)
# Move the servo from 180 to 0 degrees
for angle in range(180, -1, -1):
set_servo_angle(angle)
time.sleep(0.01)
move_servo()