from machine import Pin, PWM
import time
# Define the GPIO pin connected to the servo motor
SERVO_PIN = 18 # Change this if your servo is connected to a different pin
# Set up PWM on the specified pin
pwm = PWM(Pin(SERVO_PIN))
pwm.freq(50) # Set frequency to 50Hz (standard for servos)
def set_servo_angle(angle):
"""
Function to set the servo angle.
Converts angle (0-180 degrees) to duty cycle for PWM.
"""
duty_cycle = int((angle / 180 * 5000) + 2500) # Convert angle to duty cycle (in microseconds)
pwm.duty_u16(duty_cycle) # Set duty cycle
time.sleep(0.3) # Give the servo time to reach the desired angle
try:
while True:
# Rotate the servo from 0 to 180 degrees
for angle in range(0, 181, 10):
set_servo_angle(angle)
# Rotate the servo back from 180 to 0 degrees
for angle in range(180, -1, -10):
set_servo_angle(angle)
except KeyboardInterrupt:
# If the user presses Ctrl+C, stop the PWM signal
pwm.deinit()
print("Program terminated")