from machine import Pin, PWM
from time import sleep
# Set up PWM on GP15 (Adjust pin number if needed)
servo = PWM(Pin(15))
servo.freq(50) # Standard servo frequency (50 Hz)
# Function to move servo to a specific angle
def set_servo_angle(angle):
min_duty = 1000 # Microseconds for 0 degrees
max_duty = 9000 # Microseconds for 180 degrees
duty = int(min_duty + (angle / 180) * (max_duty - min_duty))
servo.duty_u16(duty) # Set PWM duty cycle
sleep(.5) # Small delay for movement
# Test: Move servo from 0° to 180° and back
while True:
for angle in range(0, 181, 10): # 0° to 180° ,181 is used to include the 180, else upto 170 will only be considered.
set_servo_angle(angle)
for angle in range(180, -1, -10): # 180° back to 0°
set_servo_angle(angle)
""" while True:
set_servo_angle(130)
pass """
""" duty = int(min_duty + (angle / 180) * (max_duty - min_duty)) mapping
angle in between maximum and minimum range. angle/180 normaize the value 0/180=0,90/180=0.5
and 180/180=1. It is multiplied by max_duty - min_duty. min_duty is the offset """
"""Raspberry Pi (excluding Pico): The hardware PWM on most Raspberry
Pi models (like the Pi 3, 4, etc.) typically offers a resolution of 10 bits.
This means you have 1024 possible levels for the duty cycle (2^10 = 1024).
Raspberry Pi Pico: The Raspberry Pi Pico has a 16-bit PWM resolution,
giving you 65536 possible levels for the duty cycle (2^16 = 65536).
This allows for much finer control over the PWM signal."""