Using Python to Control Servo Motors
local graph
Chapter 10 — Using Python to Control Servo Motors
Section titled “Chapter 10 — Using Python to Control Servo Motors”Using Python to Control Servo Motors
Section titled “Using Python to Control Servo Motors”We’ve been experimenting with simple geared rotation motors for the wheels and sensors. However, robots have moving parts, such as limbs or sensor mounts, that do more than drive around. In this chapter, we’ll look at how to make parts of the robot that articulate using servo motors.
Servo motors can make precise and repeatable motions, which are vital for moving sensors, robot legs, or arms to a known position. Servo motors are useful for engineers to predict robot behavior, so a robot can repeat things in automation or move limbs to accurately respond to what their sensors are instructing them. Raspberry Pi or add-on boards can control servo motors. We will explore these motors, connect them to our robot, link them to the MQTT message bus, and then use these motors to attach a pan-and-tilt mechanism. The mechanism behaves as a head for movable sensors.
In this chapter, we will cover the following topics:
- What are servo motors?
- Positioning a servo motor with Raspberry Pi
- Controlling servo motors via MQTT
- Attaching the pan-and-tilt mechanism to the robot
- Creating servo motor behaviors
Technical requirements
Section titled “Technical requirements”You will require the following to try the experiments in this chapter. See Appendix A*: Shopping for Robot Parts* for specific part, tool, and link recommendations. Prepare the following:
- The robot with the Raspberry Pi from Chapter 9, Avoiding Obstacles with Distance Sensors
- A screwdriver set, including a small Phillips screwdriver
- Miniature spanner set and flat long-nosed pliers
- M2.5 Nylon bolts and nuts from a standoff kit
- A digital caliper
- A pencil
- Masking/painter’s tape
- A pin vise with M2.5 and smaller bits
- An assembled two-axis mini pan-and-tilt kit with servo motors
You can download the example project and code for this book by following the instructions in the Download the example code files section in the Preface of this book.
This chapter’s code files are included in the downloadable code bundle.
What are servo motors?
Section titled “What are servo motors?”Servo motors, or servomechanism motors, are used on robots to position joints in arms, grippers, legs, and sensor mounts. A DC motor or gear motor rotates continuously, but controlling its exact position requires additional sensors. In contrast, a servo motor has a restricted range; however, it can be given a specific angle to turn to and will (to some degree of accuracy) try to hold that position. Code can control these angles or make a sequence of them.
Let’s see some servo motors:

Figure 10.1 – A small selection of servo motors
Figure 10.1 – A small selection of servo motors
Servos come in many sizes, from the very small at around 20–30 mm (shown in Figure 10.1) to those large enough to move heavy machinery.
There are a few kinds of servo motor—those controlled by Pulse Width Modulation (PWM) and those controlled by a serial bus. While the latter are more capable, they are also more expensive, so we will be focusing on the PWM-controlled servo motors throughout this chapter.
Figure 10.2 shows some robots using servo motors:

Figure 10.2 – A small selection of servo motors in robots
Figure 10.2 – A small selection of servo motors in robots
As the figure shows, servo motors can be a versatile way to extend your robots. Each robot pictured uses them a little differently:
- 1 servo motor: Tankbot: The turret has a servo motor, circled in the image, which moves the sensors and electronics.
- 5 servo motors: Armbot: Each joint in the arm is positioned by servo motors. Two motors work through levers and are close to the base of the arm, and one turns the base. Another rotates the wrist of the arm, and the last one can open and close the grippers.
- 18 servo motors: Spiderbot: Spiderbot has 18 servo motors, with each leg having 3 motors, to position a foot and knee and rotate forward and backward.
- 19 s ervo motors: NE-Five: The amazing NE-Five robot was built by Keegan Neave of Neave Engineering. It uses many servo motors, with two arms, each using eight servo motors. It uses three in the neck and a linear actuator with feedback to change the body position.
These robot examples show how servo motors enable robots to do something more interesting than just drive around—they can turn their heads, move their arms, walk with legs, or even grasp and manipulate objects.
Now that you’ve seen where you might use servo motors, let’s prepare a servo motor, plug it in, and make it move.
Positioning a servo motor with Raspberry Pi
Section titled “Positioning a servo motor with Raspberry Pi”The pan-and-tilt kit you bought will have come with two PWM-controlled servo motors. See the I / O p ins section in Chapter 2, Exploring Robot Building Blocks – Code a nd Electronics, for a detailed explanation of PWM.
In this section, we’ll see the motors you have, how to connect one of the servo motors to your robot, and how to use code to control it.
The pan-and-tilt mechanism
Section titled “The pan-and-tilt mechanism”Your servo motors will be part of a p an - and -t ilt mechanism that serves as this robot’s head, moving sensors in different directions. It moves sensors (or anything else) through two axes.
See the following figure:

Figure 10.3 – A pan-and-tilt mechanism
Figure 10.3 – A pan-and-tilt mechanism
The preceding figure shows the pan-and-tilt assembly suggested in the purchase list. The intent is to move the base with respect to the head. The system has two axes, in this case controlled by servo motors:
- The tilt axis positions the head to look up or down
- The pan axis positions the head to rotate left or right
Each axis has been indicated in the diagram, along with the servo motor. Each servo motor has a set of wires coming from it. In the next section, we are temporarily going to connect the pan servo motor to servo port 1 to demonstrate controlling a servo motor. We will connect both servo motors later.
Connecting the servo motor
Section titled “Connecting the servo motor”Ensure your robot is powered down. We’ll temporarily connect one servo motor to the robot electronics.
The Inventor HAT Mini has a block of pins for controlling PWM servo motors:

Figure 10.4 – Plugging a servo into the Inventor HAT Mini
Figure 10.4 – Plugging a servo into the Inventor HAT Mini
F igure 10.4 shows a servo motor on the left, with the signal, power, and ground pins indicated. The signal pin can be orange, white, or yellow.
The power pin is usually red. The ground pin may be brown or black.
On the right is the Inventor HAT Mini. It has the servo block indicated on the board, and I’ve highlighted it in the preceding figure. The block also has S, +, and – symbols, for signal, power, and ground, respectively. This first servo motor will be the pan motor.
The servo block also has a servo number indicated above each connector.
Ensure the black wire is connected next to the minus symbol.
Check this wiring carefully. Mistakes here can damage the parts.
Now that you have wired this motor in, we need to write some code to test it.
Writing code for turning a servo
Section titled “Writing code for turning a servo”The servo motor is connected to the Inventor HAT Mini. We can use the functions of the same Inventor HAT library we used to control the wheel motors in Chapter 6, Drive and Turn – Moving Motors with MQTT and Python.
Let’s build it. Create the robot/tests/test_servomotor.py file:
from time import sleepimport atexitimport inventorhatmini
board = inventorhatmini.InventorHATMini()servo = board.servos[0]
def stop_servo(): servo.disable()atexit.register(stop_servo)
servo.enable()servo.value(40)sleep(2)servo.value(60)sleep(2)servo.value(0)sleep(2)servo.value(-60)sleep(2)The imports are familiar, and we set up the Inventor HAT board object the same way as in Chapter 6, Drive and Turn – Moving Motors with MQTT and Python. We create a shortcut for controlling the first servo motor in the servo variable.
Like our motors test, we need to ensure we turn off the servo by disabling it if anything goes wrong; the atexit handler does this with servo.disable.
We then enable the servo, which may make it jump to the middle position if it wasn’t already there. It jumps to position 40—meaning 40 degrees to the robot’s left—and holds that position for two seconds.
You will need to stop the Inventor HAT service to run this test. Power up the robot and wait for the green light to show. Then use the following commands from your computer:
$ pyinfra inventory.py -- deploy/update_code.py$ pyinfra inventory.py systemd.service service=inventor_hat_service running=false _sudo=true$ pyinfra inventory.py exec -- sudo robotpython robot/tests/test_servomotor.pyThese commands do the following:
- Send updated code, including the tests, to the robot.
- Stop the Inventor HAT service so our test can use the Inventor HAT instead.
- Run our test. It must use
sudoto access the hardware.
You should now see the servo motors move. The preceding servo value settings can be adjusted safely to anywhere between +70 and -70, and perhaps a little further. However, if you hear any buzzing noises or feel any heat in the servo, you have gone beyond the limit and should adjust it down again. We will add code later to protect against this damage.
You can rerun the tests with new code by using the preceding update_code and exec commands. These moves are a little jerky. Can we make it smoother?
Smoother movements
Section titled “Smoother movements”We can also make smoother movements using a technique called linear interpolation, often shortened to LERPing. This can be made with a loop. Let’s update robot/tests/test_servomotor.py from the servo.enable line onward:
servo.enable()start_position = -70end_position = 60steps = 100total_time = 1.0time_per_step = total_time / stepsmovement_per_step = (end_position - start_position) / stepscurrent_position = start_position
for n in range(steps): servo.value(current_position) current_position += movement_per_step sleep(time_per_step)Use the same command line as previously to update this on the robot and run it, and you should see the servo motor first jump to a start position, then make a smooth sweep between positions.
A smooth movement has a starting position and an end position. We want to make that smooth movement over a particular period of time. As the computer cannot make infinitely small movements, we must choose a number of steps. The more steps we take, the smoother the movement will be, but there’s a limit to this.
We calculate how much we should move and how long we should wait between each sleep.
When setting out calculations in code, use descriptive variable names and comments—being descriptive helps you understand your code and check whether the math makes sense. You read code many times after writing it, so this principle applies to any variable or function name.
The for loop keeps track of the current_position, setting the position, adding on the movement per step in each cycle, and then waiting for the right amount of time.
Let’s check that we have the servo movement tests up and running.
Troubleshooting
Section titled “Troubleshooting”There are a few problems you may see at this point:
- If you detect any heat, it’s likely that the servo motor wiring isn’t correct. Immediately unplug the servo motors and double-check the wiring.
- If you see the
AttributeError: 'InventorHATMini' object has no attribute 'ioe'error, ensure that you have run the precedingsystemd.servicecommand. The Inventor HAT service and this test don’t like to share access. - If nothing happens at all, check that your power supply is adequate—low batteries will cause servo motors to misbehave.
- If the servo is making a lot of noise (buzzing) or jittering, first ensure you are within +/-70 degrees. Also, ensure you have an adequate power supply.
- Check all code for mistakes.
- If you are using another library or motor board, beware that they may use a 0 to 180 degree scale with 90 degrees as the neutral position.
- If you see juddering, check the batteries, although the pan axis can judder on this pan-tilt design.
You now have test code demonstrating servo motor control. How does this work? Let’s take a look inside a servo motor, so we can see why it seeks a position this way.
Looking inside a servo
Section titled “Looking inside a servo”Inside a servo motor, there is a controller, a DC motor, a gearbox (usually with a stop), and a sensor. These motors have a built-in feedback system, as shown in *Figure 10.*5:

Figure 10.5 – The servo motor control loop
The servo motor takes a requested position as an input. The controller compares this input position with a position sensor attached to the motor shaft. The difference between the expected and actual values is known as the error. The goal of the controller is to drive the motor until the error reduces to zero. Until the input signal stops, the controller will continue to detect position feedback from the motor, holding or moving the motor into the expected position.
How do we communicate with this servo motor controller?
Sending input positions to a servo motor
Section titled “Sending input positions to a servo motor”The servo motors in our robot use PWM signals, since at the time of writing, this type is cheap and easy to interface with. Let’s take a closer look at how PWM encodes servo motor control information. Recall that PWM is a square wave, with the on and off states. The frequency is kept constant; this is usually expressed in cycles-per-second or Hertz. The length in time of each pulse encodes the position information for the servo controller. These pulses repeatedly cycle, with a period or frequency. A shorter pulse is a lower value, and a longer pulse is a higher value.
See the following figure for a demonstration:

Figure 10.6 – PWM for servo motors
Figure 10.6 – PWM for servo motors
*Figure 10.*6 is divided into three panels, showing how varying the pulse width changes the servo motor position.
The frequency is 50 H z, or 20 ms per cycle.
On the left, the pulse width is 1.5 milliseconds; that is, the signal is on for 1.5 ms, then off until the next cycle. The servo motor interprets this as the middle position, which is 0 degrees for our Inventor HAT Mini library. The bottom panel shows how this looks on the pan-and-tilt mechanism in a top-down view.
The middle panel shows 90 degrees, counterclockwise, with a pulse width of 1 millisecond. The pulse is shorter, but only by quite a small degree here. The pan-and-tilt turns 90 degrees counterclockwise.
The right panel shows -90 degrees, a turn clockwise, with a pulse width of 2 milliseconds. The pulse is a little longer. These pulse variations are far more subtle than those used to control the DC motors.
Note that in all three cases, the cycle length does not change.
Some types of servo have additional outputs from their internal position sensor, and a growing selection now have two-way serial bus connections, allowing very precise control and feedback. Armbot uses servo motors with open feedback, and NE-Five uses servo motors with a data bus.
Now that we’ve moved our motors and learned how they talk, it’s time to give them networked control—using MQTT.
Controlling servo motors via MQTT
Section titled “Controlling servo motors via MQTT”Like the other systems in our robot, we are going to connect the servo motor control to the MQTT bus, so our phone app and other robot behaviors can use it.
Let’s see a system design for how this fits with our existing robot designs.
System design
Section titled “System design”The Inventor HAT Mini board connects to both the wheel and servo motors on this robot. Because the Inventor HAT library links directly to a single board, and the Inventor HAT service already manages the motors MQTT topic, servo control should also be added here.
The architecture for what we will change in this chapter should look quite familiar:

Figure 10.7 – Adding servo motors to MQTT
Figure 10.7 – Adding servo motors to MQTT
The preceding architecture diagram shows the p hone, network, and Raspberry Pi aspects of the system.
We will be modifying the Inventor HAT service to accept servo motor topics:
motors/servo/pan/position, with a payload for the position in degrees: Move servo motor 0 (which we’ll use for panning) to the given positionmotors/servo/tilt/position: Move servo motor 1 to the given positionmotors/servo/pan/stop: Stop/disable servo motor 0motors/servo/tilt/stop: Stop/disable servo motor 1
Naming the topics this way means that if we moved the servo motors to different positions or had a controller with different handling for servo motors, we would not need to change the client code to move them.
We will be adding a circle head behavior later in the chapter to control the movement automatically. We make use of the launcher and web server, but do not modify them in this chapter.
In the control interface, we will start by adding a servo control page (with links in the menu), then later a page to start/stop our circle head demonstration behavior.
With the system design clear, let’s build the Inventor HAT service changes.
Adding servo motors to the Inventor HAT service
Section titled “Adding servo motors to the Inventor HAT service”We will add the new topic handlers for this. The code here should not be too surprising, as we’ll use the same method as the previous servo motor test with our existing Inventor HAT service in robot/inventor_hat_service.py. Commit any code changes you have before getting into this section.
Start by adding variables for the two servo motors, as shown in the highlighted lines:
left_motor = board.motors[1]right_motor = board.motors[0]pan = board.servos[0]tilt = board.servos[1]The pan and tilt variables name the servo motors in much the same way that we have for the left and right wheel motors. Let’s add the position MQTT handler—this can be after the variables:
def set_servo_position(servo, client, userdata, msg): position = float(msg.payload) servo.value(position)
def set_pan(client, userdata, msg): set_servo_position(pan, client, userdata, msg)
def set_tilt(client, userdata, msg): set_servo_position(tilt, client, userdata, msg)This function has a servo parameter as well as the usual MQTT message parameters. It takes the client message and decodes a (floating) number from it. It then sets the servo’s position to the passed value. We then create small helper functions for each motor.
We also need to stop the servo motors:
def stop_servo(servo): if servo.is_enabled(): servo.disable()
def stop_pan(client=None, userdata=None, msg=None): stop_servo(pan)
def stop_tilt(client=None, userdata=None, msg=None): stop_servo(tilt)The stop function has only a servo parameter; the two helpers functions under it also have MQTT settings.
We also need to ensure these motors stop when all the motors stop. Find the stop_motors function and add the following highlighted lines:
def stop_motors(client=None, userdata=None, msg=None): left_motor.stop() right_motor.stop() stop_pan() stop_tilt()This function can make use of the preceding stop functions.
Finally, we need to link up the handlers. In the code section containing callbacks, add the highlighted lines:
client.message_callback_add("motors/wheels", set_motor_wheels)client.message_callback_add("motors/servo/pan/position", set_pan)client.message_callback_add("motors/servo/pan/stop", stop_pan)client.message_callback_add("motors/servo/tilt/position", set_tilt)client.message_callback_add("motors/servo/tilt/stop", stop_tilt)client.message_callback_add("all/stop", stop_motors)We can test this. Upload this code using the pyinfradeploy_services script again. At this point, I recommend connecting the second servo motor to the Inventor HAT Mini.
Now you can send testing MQTT messages. I chose to use Mosquitto on the Raspberry Pi to send them:
$ mosquitto_pub -u robot -P robot -t motors/servo/pan/position -m "25"$ mosquitto_pub -u robot -P robot -t motors/servo/pan/position -m "-65"$ mosquitto_pub -u robot -P robot -t motors/servo/tilt/position -m "10"$ mosquitto_pub -u robot -P robot -t motors/servo/tilt/position -m "-50"$ mosquitto_pub -u robot -P robot -t motors/servo/pan/position -m "0"$ mosquitto_pub -u robot -P robot -t motors/servo/tilt/position -m "0"Don’t forget, you’ll need to use your own MQTT user/passwords here. You should see your servo motors moving, but if not, let’s troubleshoot.
Troubleshooting
Section titled “Troubleshooting”If your servo motors are not moving when you send the test messages, check the following things:
- First, ensure the servo motor tests in the Positioning a servo motor with Raspberry Pi section work.
- Use
journalctl ‑u inventor_hat_serviceto see whether there are any error messages from the service. Add the‑fflag to follow it. - Ensure you’ve used your own MQTT usernames/passwords.
- Ensure your topic spellings match.
- Errors in payloads will need the Inventor HAT restarted. We’ll address that in the following section.
- Any buzzing or jitter can be a sign that the position is too far from the middle.
This code can also crash with an OSError sometimes. We need to make it a bit more robust.
Making the Inventor HAT service more robust
Section titled “Making the Inventor HAT service more robust”The Inventor HAT service can crash, and you then need to restart it. Accidental payload mistakes or I2C communication errors all make it more likely to crash.
Try running mosquitto_pub ‑u robot ‑P robot ‑t motors/servo/tilt/position ‑m "‑5 0" to see it crash. The journal will show a value error, and the whole service will be dead. We want it to show errors, but not exit the service.
Let’s make the set_servo_position function in robot/inventor_hat_service.py more resilient:
def set_servo_position(servo, client, userdata, msg): try: position = float(msg.payload) servo.value(position) except OSError: print("Error: Failed to set servo position") except ValueError: print("Error: Invalid position value")This version of the code will mean the service will carry on when it encounters problems with the servo motor or the value sent. If you deploy this, it should work as before, but an incorrect message will not cause the service to break. The occasional OSError from the servo also won’t cause it to break.
You can send any position between -90 and 90, but the pan axis has physical limits beyond 70, which can cause servos to get hot and damaged, and the tilt is even more restricted. We’ll fix that in calibration. Let’s first make it a bit easier to control by adding a phone page for it.
Adding a servo control phone page
Section titled “Adding a servo control phone page”We are going to reuse and adapt the manual drive design for this.
Copy robot_control/manual_drive.html to robot_control/servo_control.html. Update the titles and headings.
Then we need to update the joystick stickData handling function within the robot_control/servo_control.html joystick section:
function(stickData) { const pan = Math.min(90, Math.max(-90, stickData.x)); const tilt = Math.min(90, Math.max(-90, stickData.y)); console.log(pan, tilt); mqttClient.publish("motors/servo/pan/position", JSON.stringify(pan)); mqttClient.publish("motors/servo/tilt/position", JSON.stringify(-tilt));}Here, we’ve replaced the calculations for driving the wheel motors with those for the servo motors. First, we restrict what we send so it is between -90 and 90 degrees on each.
We then log our pan-tilt values so we can see the positions in the JavaScript console.
The last two lines publish motor positions for each servo axis via MQTT. Notice that the tilt value is published negated; this aligns pushing up on the joystick with tilting up on the tilt mechanism. We have to convert the numbers to JSON format to send them.
The next thing we’ll need is to add an entry for this into the main menu in robot_control/index.html:
<li><a href="servo_control.html">Servo control</a></li>We can now deploy services, load the robot menu, and select this servo control page. Like any new page, I recommend trying it in the browser first, with the JavaScript console open. You can then try it on the phone.
You should be able to move the head around with the joystick. If you have any issues, check the JavaScript code, along with the previous troubleshooting steps.
When you let go of the stick, the servo motors should return to the zero positions. But those zero positions might not be facing the front and center of the pan-and-tilt mechanism. In the next section, we’ll calibrate to ensure they match up.
Physically calibrating your servos
Section titled “Physically calibrating your servos”When you test the motors, you may find that position 0 does not have the front of the pan-and-tilt head facing forward from the pan-and-tilt base (the slightly longer end). It’s easy for an assembled pan-and-tilt hat (or one you have built yourself) to be slightly off.
The process of calibration is intended to compensate for this. We can adjust the physical servo alignment for differences above 5 degrees. If the zero points for both motors have less than a 5-degree error, then you can skip to the next section.
Keep the robot powered up for this part. You will need a screwdriver, and you will need to carefully ensure the screws go back where they came from.
The following diagram shows how to adjust the base:

Figure 10.8 – Adjusting the pan servo position
Figure 10.8 – Adjusting the pan servo position
The preceding figure shows the parts needed to adjust the base position. If the adjustments are relatively large (above 5 degrees), turn the pan-tilt head upside down and locate the Spline b olt on the base.
Unscrew this and keep the bolt somewhere safe. The figure shows a S ervo horn bolted to the base, which transmits the servo movement to the base. In its center is the S ervo horn spline, which has teeth around it for friction. Separate the P an - tilt upper assembly from the S ervo horn.
Now, reinsert the S ervo motor spline closer to the correct alignment to ensure that the neutral position of the servo motor matches the head facing forward. Because these splines have a fixed number of teeth, you might not be able to get it 100%. We’ll account for this in software later.
When you have it as close as you can to the middle and pushed firmly onto the spline, bolt this back in place.
Check whether the tilt alignment of the T ilt servo is outside 5 degrees. If so, repeat the same process for the Tilt servo:

Figure 10.9 – Reference diagram for calibrating the tilt servo
Figure 10.9 – Reference diagram for calibrating the tilt servo
The preceding diagram indicates parts of the pan-and-tilt assembly involved in calibrating the tilt part of the mechanism. Each part is labeled.
We will be partly separating the left and right arms of the tilt mechanism. The diagram shows the parts fully separated for illustrative purposes, but this will be easier if you only pull them apart enough to clear the splines.
Use the following process:
- Identify and unscrew the two L eft arm bolts.
- Locate the T ilt servo and the T ilt spline bolt on the right of the mechanism. Remove this bolt also.
- Be sure to keep the two sets of bolts apart as they are different.
- Identify the T ilt horn spline.
- Gently separate the two halves far enough for the T ilt horn spline to clear the tilt servo spline. Pushing between the T ilt horn spline and the servo body works well for this.
- Align the tilt mechanism. You may need to move the joystick and release it to bring it back to 0.
- Gently push the right arm back into place, ensuring the splines interlock.
- Bolt the spline into place.
- Put the L eft arm bolts back in.
You have now calibrated the servo hardware. Before we do any fine adjustments in software, we can attach it to the robot.
Attaching the pan-and-tilt mechanism to the robot
Section titled “Attaching the pan-and-tilt mechanism to the robot”The mechanism needs to become part of the robot. We need to both attach it physically and wire it in place so that the motor controller can send signals to it. Please power the robot down for this part. We will need to make a few holes in the chassis to bolt it into. Let’s see the dimensions for the holes:

Figure 10.10 – Pan-and-tilt attachment dimensions
Figure 10.10 – Pan-and-tilt attachment dimensions
The figure shows the dimensions for our parts; it is not to scale. The Pan - and - tilt base holes have a distance of 28 mm horizontally and 32 mm along the vertical side. The holes are 2 mm or M2 in diameter.
The next panel shows where we will put holes in the chassis. We’ve made the holes 22 mm vertically from the front of the robot, so adding another 32 mm takes it to 54 mm for the rear set of holes. There are 28 mm between the holes horizontally. With a chassis width of 126 mm, we can do the calculations:
(126 - 28)/2 = 49.00 mm
We need to add 49 mm from the side to account for this and keep it in the middle. You can use your digital caliper to confirm my measurements.
Let’s see how to use our tools to mark out the holes:

Figure 10.11 – Cutting pan-and-tilt mounting holes
Figure 10.11 – Cutting pan-and-tilt mounting holes
The photos show how we mark out the holes. The chassis has a large hole, designed for a larger servo motor. Although there are pan-and-tilt mechanisms that fit this, I’ve elected to use a cheaper, smaller one in our build.
Let’s see the steps for this:
- Because the chassis is black plastic, pencil marks won’t appear very clearly. So, we cover the sides of this hole with masking tape, which we can then leave marks on.
- We then use the caliper and pencil to mark where the holes will be. First, we mark 22 mm from the front on both sides.
- Next, we mark 54 mm from the front on both sides.
- Then, we mark 49 mm in from each side, which should form a cross over the original pencil marks.
- You should now have four crosses marked, ready for drilling.
- Drill using the pin vise with a 1 mm bit first, then use a 2 mm bit to widen them.
- When the holes are drilled, pull the tape off.
- You should now have four holes ready to mount the pan-and-tilt mechanism.
Once the holes are made, you can bolt the pan-and-tilt base onto the robot with 4 x 2.5 mm bolts and nuts. They will be a bit tricky to get in, but the large hole under this in the chassis should help with the nuts. You may need to pan the head to the side to get the screwdriver in above too. You should now have the pan-and-tilt head bolted in facing forward.
Congratulations! Your robot is ready, and the hardware setup is complete. We have some code to drive the servo motors; let’s fine-tune that and create a behavior with it.
In the next section, we will make a behavior that uses these to make circles.
Creating servo motor behaviors
Section titled “Creating servo motor behaviors”Like other behaviors, those interacting with the pan-and-tilt will signal via MQTT. There will also be a circle head page on the web/phone interface to start and stop this behavior.
But first, a little fine-tuning.
Fine-tuning the servo motors
Section titled “Fine-tuning the servo motors”As you may have observed, even with our calibration, the servo motors on this robot might not line up 100% forward due to the teeth on the connecting splines. We can account for this tiny difference in software. Since it will be the same difference for all behaviors, we’ll do so in the Inventor HAT service.
Open robot/inventor_hat_service.py and locate the set_servo_position function, then add the highlighted changes:
def set_servo_position(servo, client, userdata, msg, fine_tune=0): try: position = float(msg.payload) + fine_tune servo.value(position) except OSError: print("Error: Failed to set servo position") except ValueError: print("Error: Invalid position value")This code will let us use a fine-tuned value, optionally, with the set_servo_position function. It is simply an offset to add to the proposed zero position.
First, let’s set the pan to 0 with MQTT messages from SSH (you can see examples in the Adding servo motors to the Inventor HAT service section previously). Now you can see whether there’s a small offset. Now try setting a small value (between -3 and 3) to see whether you can get it dead ahead. When you have this value, add fine-tuning to set_pan using your own value:
def set_pan(client, userdata, msg): set_servo_position(pan, client, userdata, msg, fine_tune=3)I’ve used 3 here, which means that every servo position message will get this 3 added to it.
We can now repeat the process for set_tilt:
def set_tilt(client, userdata, msg): set_servo_position(tilt, client, userdata, msg, fine_tune=0)I was lucky in that 0 lines up already for my tilt motor, so you may not need a value at all for either if it’s good enough. Use the deploy/deploy_services.py PyInfra script to update this. Now, when you move the head to 0, it will be facing exactly forward.
Let’s use this in our behavior.
Circling the pan-and-tilt head
Section titled “Circling the pan-and-tilt head”In this section, we make the pan-and-tilt head move in small circles of around 30 degrees. This behavior demonstrates the mechanism and the parts of the code to talk to it. The code creates a repeating animated kind of behavior that uses a time base—a current time. We use the time base to draw the circle. Create the robot/circle_head_behavior.py file:
import timeimport mathfrom common.mqtt_behavior import connect, publish_json
class CircleHeadBehavior: def __init__(self): self.seconds_per_circle = 10 self.radians_per_second = (2 * math.pi) / self.seconds_per_circle self.radius = 50
def start(self): client = connect(start_loop=False) client.loop_start() while True: frame_in_radians = time.time() * self.radians_per_second pan_position = self.radius * math.sin(frame_in_radians) tilt_position = self.radius * math.cos(frame_in_radians) publish_json(client, "motors/servo/pan/position", pan_position) publish_json(client, "motors/servo/tilt/position", tilt_position) time.sleep(0.05)
behavior = CircleHeadBehavior()behavior.start()We start the circle head behavior by importing the time, math, and mqtt libraries. We then put the behavior in a class.
This class defines some parameters for our circle: how many seconds it takes per circle and the radius of our circle.
The math functions work in radians. A full circle of radians is 2 times pi. We divide that by seconds_per_circle to make a multiplier that we call radians_per_second.
In each frame, we get the current time in seconds and multiply it by radians_per_second to get the current angle in radians for any time.
The formula for drawing a circle is to make one axis the cosine of the angle times the radius, and the other the sine of the angle times the radius.
We then feed each value to the servo motors and sleep a little.
Finally, the main part of the file starts this behavior up.
We need to deploy this as a service. In deploy/deploy_services.py, add the following:
code = files.put( name="Update circle_head code", src="robot/circle_head_behavior.py", dest="robot/circle_head_behavior.py")deploy_service("circle_head", "robot/circle_head_behavior.py", False, common.changed or code.changed)We also need an HTML page for it under robot_control/circle_head.html:
{% extends "robot_control/page.html.j2" %}{% block title %}Circle head{% endblock %}{% block content %} <button id="start">Start circling head</button> <button id="stop">Stop circling head</button> <script type="module"> import { connect, publish_when_clicked } from './mqtt_client.js'; let mqttClient = connect();
publish_when_clicked(mqttClient, "start", "launcher/start", "circle_head"); publish_when_clicked(mqttClient, "stop", "launcher/stop", "circle_head"); </script>{% endblock %}Finally, we need to add an entry in the menu for it:
<li><a href="circle_head.html">Circle head</a></li>If you now rerun deploy services, load the page, and click the S tart button, it should start to circle, with a 50-degree deflection and a period of 10 seconds per circle. You can change those numbers to vary the animation.
Troubleshooting
Section titled “Troubleshooting”If this does not run, please try the following:
- Ensure you were able to test the servos as shown in the Writing code for turning a servo section. There is no need to disassemble the pan-and-tilt mechanism for this, but please make sure you have made a servo move with the code there and followed the troubleshooting instructions in that section.
- Use
journalctlto look for problems in bothcircle_head_behaviorandinventor_hat_service. - Ensure that you have checked for typos in your code.
- If the motors move to an extreme position, you may have missed the step to calibrate them.
- If a servo refuses to move at all, check that it has been plugged in the right way, ensuring that G corresponds to the black servo wire, V corresponds to the red wire, and S to the yellow signal wire from the servo. The robot code has assumed that the servo motors are plugged into channels 0 and 1 of the motor control board.
- Ensure that there are no breaks in the wires or their insulation. I have seen a batch of servo motors of this type with wire problems and had to return them. You should not be able to see any bare patches of wire.
- Ensure that the connectors are pushed in firmly. If they are loose here, then a signal may not be getting to the servo motors.
- Low batteries will make a servo jitter or fail to reach a set point.
This is an entry-level, inexpensive pan-and-tilt system. Like all aspects of building the robot, investing more time in tuning or refining or more money into a more expensive pan-and-tilt mechanism will make this system’s movement smoother. Exceptionally smooth pan-and-tilt mechanisms can cost hundreds of dollars.
You should now be able to troubleshoot the common problems seen with running this circle servo motor behavior and see the head making small and slow circles. We will be able to use this system in a later chapter to look at faces.
Summary
Section titled “Summary”In this chapter, you have learned about servo motors, how to control them with your motor controller, and how they work. You’ve built a pan-and-tilt mechanism with them and added code to control that mechanism over MQTT. Finally, you’ve demonstrated all of the parts with the circling behavior.
You will be able to use the code you’ve seen to control other servo motor systems, such as robot arms. The animation style techniques can be useful for smooth movement and circular motions. I used a system a little like this when controlling the 18 motors in Spiderbot’s legs.
In the next chapter, we will look at another way to observe and react to the world with encoders. These sensors will detect wheel rotations on our robot to determine how our robot is moving.
Challenges
Section titled “Challenges”Here are some ways you could build this further:
- You could combine the manual drive and servo control pages into a single page, perhaps designed for landscape usage, that allows you to operate both.
- Consider how you might build other servo-based extensions. A robot arm needs at least four servos, but a simple gripper/grabber can use the two additional channels our robot has left.
- Look around at kits for a gripper, a design with a pincer, and perhaps an up/down control.
- How would you write the code for this gripper? What MQTT topics would you add?
- What demo behavior would you make for this gripper?
- A gripper might move too violently when just given a different position to be in. How would you make a slower smooth movement?
Servo motors can add a lot of flexibility and fun to a robot build, but with more sensors, we can get the robot to respond to the world too!
Further reading
Section titled “Further reading”To find out more about the topics covered in this chapter, here are some suggestions:
- I recommend looking at the SG90 servo motor data sheet (http://www.ee.ic.ac.uk/pcheung/teaching/DE1_EE/stores/sg90_datasheet.pdf) for information about their operation.
- The Adafruit guide to the pan-and-tilt mechanism (https://learn.adafruit.com/mini-pan-tilt-kit-assembly) has a set of assembly instructions. They are in a slightly different order from mine but may give a different perspective if calibrating this is proving to be tricky.