from machine import Pin, PWM
from time import sleep
# Define the GPIO pin connected to the servo signal wire
servo_pin = Pin(13, Pin.OUT)
# Configure PWM for the servo
# Frequency: 50 Hz (standard for servos)
# Duty cycle range: 0 to 1023 (10-bit resolution)
pwm = PWM(servo_pin, freq=50)
# Function to set the servo angle
def set_servo_angle(angle):
# Map the angle (0° to 180°) to the duty cycle range (20 to 120)
# For most servos:
# 0° = 20 (0.5 ms pulse width)
# 90° = 77 (1.5 ms pulse width)
# 180° = 120 (2.5 ms pulse width)
duty = int(20 + (angle / 180) * 100)
pwm.duty(duty)
# Move the servo arm back down smoothly from 90° to 0°
for angle in range(90, -1, -1): # Start at 90°, end at 0°, decrement by 1°
set_servo_angle(angle)
sleep(0.02) # Add a small delay for smooth movement (20ms)
sleep(5)
for angle in range(0, 91, 1): # Start at 90°, end at 0°, decrement by 1°
set_servo_angle(angle)
sleep(0.02) # Add a small delay for smooth movement (20ms)
# Keep the program running
while True:
sleep(1) # Do nothing