Servos
Angles, speed, what a servo can and cannot do.
Do this lesson in the simulatorEverything so far has been about moving the whole robot. This module is about the two small motors on top of it, the servos, and the attachments they drive: a gripper that holds a ping-pong ball, and a kicker that sends it away.
What a servo is
A servo is a motor that goes to an angle and holds it. You do not tell it how fast to spin; you tell it where to be, between 0 and 180 degrees, and it gets there and stays. Inside is a small motor, a gearbox and a sensor, with a controller like the ones in Module 3 keeping the angle where you asked.
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
# servo 0 to 0 degrees
servo(0, 0)
# pause 0.5 s (the robot keeps doing what it was told)
wait(0.5)
# servo 0 to 180 degrees
servo(0, 180)
# pause 0.5 s (the robot keeps doing what it was told)
wait(0.5)
# servo 0 to 90 degrees
servo(0, 90)
print("servo 0 is at 90")
BugBot has two: servo 0 works the gripper, servo 1 the kicker. The robot does not need to move for any of this.
They take time
A hobby servo turns about 60 degrees in a tenth of a second. Ask for 180 and read the position straight away and it is not there yet, which is why wait sits between the moves above. The gripper() and kick() commands in the next lessons do that waiting for you.
Sweeping
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
for angle in range(0, 181, 30):
servo(0, angle)
print("servo 0 at", angle)
# pause 0.3 s (the robot keeps doing what it was told)
wait(0.3)
for angle in range(180, -1, -30):
servo(0, angle)
# pause 0.3 s (the robot keeps doing what it was told)
wait(0.3)
range(0, 181, 30) counts 0, 30, 60 ... 180: the third number is the step. Back down again with a negative step.
What a servo cannot do
A normal one cannot spin round and round: 0 to 180 is the whole range. (The kicker's servo is the other kind, a continuous-rotation servo, which lesson 7.4 explains.) It cannot push harder than its small gearbox allows: ask a gripper to close on something too big and the servo strains, gets hot, and eventually strips its gears. And it cannot tell you what it touched. The gripper lessons work round all three.
Task: servo sweep
Move servo 0 to 0, 45, 90, 135 and 180 in turn, printing servo 0 at <angle> each time. Do not drive.
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
# servo 0 to 90 degrees
servo(0, 90)
print("servo 0 at", 90)
Challenges
- Sweep servo 1 the same way.
- Wave: swing servo 0 between 60 and 120 five times.
- Write
slowly(index, angle)that moves a servo to an angle in steps of 5 degrees with a short wait between each.