KevsRobots Learning Platform
By Kevin McAleer, 3 Minutes
A servo is a motor that turns to a position you choose and holds it there, which makes it perfect for robot arms, legs and pan-tilt heads. In this lesson you’ll wire one up and control it with PWM.
A servo has three wires:
The servo reads the pulse width: a pulse is sent 50 times a second, and its length sets the angle. For an SG90, about 0.5ms is 0°, 1.5ms is 90° and 2.5ms is 180°.
VBUS (5V from USB, physical pin 40)GNDGP18 (physical pin 24). Any GPIO pin will workOne small servo is fine from USB power. For more than one, or bigger servos, use a separate 5V supply and connect its ground to the Pico’s ground.
At 50Hz each cycle lasts 20ms, and duty_u16() covers that whole 20ms with 0 to 65535. So 1ms is about 65535 / 20 = 3277.
from machine import Pin, PWM
from time import sleep
servo = PWM(Pin(18))
servo.freq(50)
def set_angle(angle):
pulse_ms = 0.5 + (angle / 180) * 2.0 # 0.5ms to 2.5ms
servo.duty_u16(int(pulse_ms * 65535 / 20))
for angle in (0, 90, 180, 90):
set_angle(angle)
sleep(1)
servo.deinit()
servo.freq(50) sends 50 pulses per second, which is what servos expectset_angle() turns an angle into a pulse width, then into a duty valueservo.deinit() stops the signal, so the servo relaxesCheck your servo’s range
Servos vary. If yours buzzes or strains at 0° or 180°, narrow the range, for example 1.0ms to 2.0ms.
Use a potentiometer (lesson 9) to set the servo angle, so turning the knob turns the servo.
Quick quiz 1 of 2
What sets a servo’s position?
Quick quiz 2 of 2
At 50Hz, roughly what duty_u16() value gives a 1.5ms pulse?
You can use the arrows ← → on your keyboard to navigate between lessons.
Comments