🐘 Tutorial 21 - Servo
A Servo is a small device that is used to control the position of an object with high precision. It typically consists of a small motor, a gear train, and a control circuit that is used to command the motor to rotate to a specific angle. Servos are widely used in various applications such as robotics, remote-controlled toys, and industrial automation.
The main advantage of a Servo is its ability to rotate to a specific angle with high accuracy and repeatability. The control circuit of a Servo typically uses a closed-loop feedback mechanism to monitor the actual position of the motor shaft and adjust it as necessary to reach the desired position. This makes Servos ideal for applications where precise positioning is required.
Servos can be controlled using a variety of methods, including analog signals, pulse-width modulation (PWM), and serial communication protocols. In the case of the Raspberry Pi Pico, PWM signals can be used to control a Servo. By varying the duty cycle of the PWM signal, the angle of the Servo can be adjusted.
Overall, Servos are versatile and reliable devices that are widely used in various applications that require precise positioning. Their ability to rotate to a specific angle with high accuracy and repeatability make them an essential component in many electronic projects.
Components Needed
Component | Quantity |
---|---|
Raspberry Pi Pico W | 1 |
Micro USB Cable | 1 |
Breadboard | 1 |
Wires | Several |
Servo | 1 |
Fritzing Diagram
Code
import machine
import utime
servo = machine.PWM(machine.Pin(15))
servo.freq(50)
def interval_mapping(x, in_min, in_max, out_min, out_max):
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
def servo_write(pin,angle):
pulse_width=interval_mapping(angle, 0, 180, 0.5,2.5)
duty=int(interval_mapping(pulse_width, 0, 20, 0,65535))
pin.duty_u16(duty)
while True:
for angle in range(180):
servo_write(servo,angle)
utime.sleep_ms(20)
for angle in range(180,-1,-1):
servo_write(servo,angle)
utime.sleep_ms(20)