from machine import Pin, PWM
import time
# Initialize PWM on GPIO 15 with a frequency of 50 Hz (standard for servos)
servo = PWM(Pin(15), freq=50)
# Function to set the angle of the servo motor
def set_angle(angle):
# Convert the angle (0 to 180 degrees) to the corresponding duty cycle (0 to 1023)
# The formula ensures that the duty cycle is proportionate to the angle
duty = int((angle / 180.0) * 1023)
# Set the duty cycle of the PWM signal to control the servo position
servo.duty(duty)
# Infinite loop to sweep the servo back and forth
while True:
# Sweep the servo from 0 to 180 degrees
for angle in range(0, 181, 1): # Increment the angle from 0 to 180
set_angle(angle) # Set the servo to the current angle
time.sleep(0.01) # Small delay to allow the servo to move to the position
# Sweep the servo from 180 to 0 degrees
for angle in range(180, -1, -1): # Decrement the angle from 180 to 0
set_angle(angle) # Set the servo to the current angle
time.sleep(0.01) # Small delay to allow the servo to move to the position