To control the position of a 9g servo motor using the PWM output of Raspberry Pi Pico and change its angle when a push-button is pressed.
Buy Basic Raspberry Pi Pico Kit
Items Required:
Raspberry Pi Pico 1
9g Servo Motor (SG90 or similar) 1
Push Button 1
330O Resistor (for button debouncing, optional) 1
Breadboard 1
Jumper Wires As needed
USB Micro B Cable 1
External Power Source (5V, optional) 1 (if needed)
Note: For longer runtimes or under load, power the servo from external 5V and connect GND to Pico’s GND to avoid current issues.
Connections:


Code:
from machine import Pin, PWM
from time import sleep
# Set up PWM Pin for servo control
servo_pin = machine.Pin(0)
servo = PWM(servo_pin)
# Set Duty Cycle for Different Angles
max_duty = 7864
min_duty = 1802
half_duty = int(max_duty/2)
#Set PWM frequency
frequency = 50
servo.freq(frequency)
try:
while True:
#Servo at 0 degrees
servo.duty_u16(min_duty)
sleep(2)
#Servo at 90 degrees
servo.duty_u16(half_duty)
sleep(2)
#Servo at 180 degrees
servo.duty_u16(max_duty)
sleep(2)
except KeyboardInterrupt:
print("Keyboard interrupt")
# Turn off PWM
servo.deinit()
Result:
When the code runs, the servo rotates to 0°, pauses, then to 90°, pauses, and finally to 180°, and keeps repeating this cycle.