Previously we looked at motor control but for our robot there is another type of actuator that we need to drive, and those are Servos.
Servos
Servos are another kind of motor, but they are actually easier to use than regular motors with the Pi, because they have built-in controllers. There is one problem, however, which we will get to in a moment.
We can choose between the regular kind of servo, where the servo can be told to move to a position or angle, and then there are the continuous kind where instead of angle, the same instruction controls speed and direction.
Problem?
Rather than tell you about it, let me show you :)
Wire up a servo with the power connected to 5v, the ground connected to a GND, and the signal connected to Pin 18.
We will be using the chips pin numbers so refer to the Pinout.xyz guide here:
from gpiozero import AngularServo
from time import sleep
servo = AngularServo(18, min_angle=-42, max_angle=44)
while True:
servo.min()
sleep(1)
servo.mid()
sleep(1)
servo.max()
sleep(1)
servo.angle = 40
sleep(1)
servo.angle = 20
sleep(1)
servo.angle = 0
sleep(1)
servo.angle = -20
sleep(1)
servo.angle = -40
This code will work but ill likely find the motion is stuttery. This is because of the Raspberry Pi being a fully-fledged computer rather than a microcontroller. Instead of just doing one thing at a time, the Pi has a multi-tasking operating system that has to do many things all at once.
Raspberry Pi Jitter Solution
Fortunately for us, a generous soul from the UK has ported a low-level library for us to use.
sudo pip3 pigpio
and run sudo pigpiod
Add the following code then check out the difference:
import pigpio
from time import sleep
# connect to the
pi = pigpio.pi()
# loop forever
while True:
pi.set_servo_pulsewidth(18, 0) # off
sleep(1)
pi.set_servo_pulsewidth(18, 1000) # position anti-clockwise
sleep(1)
pi.set_servo_pulsewidth(18, 1500) # middle
sleep(1)
pi.set_servo_pulsewidth(18, 2000) # position clockwise
sleep(1)
Much more stable, right?
What now?
As we have seen, other than the power limitations, the Pi can be a capable physical computing device, but for anything more in-depth I like to split the responsibilities of hardware control versus processing.