Skip to content
ImagineWorld

Drive and Turn – Moving Motors with MQTT and Python

node_idnode-book_learn-robotics-programming_chapter-06-drive-and-turn-moving-motors-with-mqtt-and-python
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num6
chapter_titleDrive and Turn – Moving Motors with MQTT and Python
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 6 — Drive and Turn – Moving Motors with MQTT and Python

Section titled “Chapter 6 — Drive and Turn – Moving Motors with MQTT and Python”

Drive and Turn – Moving Motors with MQTT and Python

Section titled “Drive and Turn – Moving Motors with MQTT and Python”

In the previous chapter, we learned how to build the robot chassis, wire in motors, and power it.

In this chapter, we will take the robot we built in the last chapter and build the Python code to make the motors move. We’ll see how to use motors to steer our robot, and how our code will get the robot moving! We will learn about MQTT, and how to use it to bridge between the physical robot and its behavior code, reducing the impact of hardware changes. The MQTT layer serves as a foundation for all our robot behaviors, and we will finish by programming a small set path following behavior to demonstrate using MQTT.

We will cover the following topics in this chapter:

  • Using Python to test robot motors
  • Steering a robot
  • Making an MQTT service for the main breakout
  • Troubleshooting
  • Following a path with MQTT

To complete the experiments in this chapter, you will require the following:

  • A computer with access to the internet
  • The code built for Chapter 4*,* Protecting Robot Code with Git.
  • The chassis built in Chapter 5*,*Building Robot Basics – Wheels, Power, and Wiring.
  • A 2-meter-by-2-meter flat space for the robot to drive on.

Be prepared to stop your robot from driving over the edges if you use a table! It’s best to use the floor. Have a small box around to lift the robot so its wheels are off the ground while testing.

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.

Before we get stuck in and do fancy things with the motors, we need to get them set up and test them. This way, we can make sure they work and iron out any problems.

We need to download the library to work with the motor board we have chosen. Many robot parts, apart from the simplest ones, have an interface library to control the motors and other devices on the board. We’ll use PyInfra to install it.

We are going to set up the I2C bus and Python libraries for the Inventor HAT Mini.

The Raspberry Pi uses I2C to connect to this Inventor HAT Mini. I2C buses let you send and receive data and are flexible, so you can connect many devices to the same bus.

Let’s start with I2C in the file deploy/configure_pi.py:

from pyinfra.operations import server
server.shell("raspi-config nonint do_i2c 0", _sudo=True)

This uses a server.shell operation to run the raspi‑config tool, which configures Raspberry Pi hardware and boot. We use that to enable I2C, using the nonint parameter to do it in a non-interactive way. raspi-config is menu-driven, with the menu options numbered from 0 onward. Option 0 is to enable the I2C bus.

We then need pip to extend the Python packages on the Raspberry Pi. However, it is considered a bad idea to modify system packages, so we create a P ython virtual environment, or virtualenv. It is common to use the terms venv or P ython env for this. This lets us install what we need there, without interfering with the system.

Add the file deploy/virtual_env.py to prepare this:

from io import BytesIO
from pyinfra.facts.server import Home
from pyinfra import host
from pyinfra.operations import apt, pip, files
from deploy import base_packages
apt.packages(
name="Install python venv tool",
packages=["python3-venv"],
_sudo=True,
)
robot_venv = f"{host.get_fact(Home)}/robotvenv"
pip.venv(
name="Robot python virtual environment",
path=robot_venv,
site_packages=True,
)

This starts with importing BytesIO, which we’ll use later for formatting a file, as well as some PyInfra facts and operations, and then ensures that we have prepared the base packages.

The script then installs the virtual env software. Then it combines get_fact(Home), to get the user home directory from the Pi, with the name robotvenv in an f-prefixed string, making a path for the virtual environment. This is stored in the variable robot_venv, which we use to create the virtual environment. We can use this variable when we need to reference the same environment.

We also need to make a convenient way to start Python in this virtual environment. Add this to deploy/virtual_env.py:

robotpython = f"""\
#!/bin/bash
{robot_venv}/bin/python3 $@
"""
files.put(
name="Create robotpython script",
src=BytesIO(robotpython.encode("utf-8")),
mode="755",
dest="/usr/local/bin/robotpython", _sudo=True,
)

This creates a small shell script that runs Python from the virtual env, with the $@ part passing all parameters onto that Python.

The file is deployed on the Raspberry Pi at /usr/local/bin/robotpython, with mode 755 to allow it to be run. The BytesIO object is a Pythonic way of turning some text into something file-like.

Let’s use this virtual environment to set up the HAT in deploy/deploy_inventor_hat_mini.py:

from deploy import virtual_env
from pyinfra.operations import apt, pip
apt.packages(
name = "Install smbus2",
packages = ["python3-smbus2"],
_sudo = True
)
pip.packages(
name="Install Inventor HAT mini",
packages=[
"inventorhatmini", "gpiodevice"
],
virtualenv=virtual_env.robot_venv,
)

This imports the virtual env we’ve set up, so it can use the variable for its path, and importing it will cause it to be installed. We install python3‑smbus2 as this is needed by the HAT library. SMBus is compatible with I2C, so they share this library. We then install the inventorhatmini package into this virtual env. We’ll be installing other packages here.

Let’s add these other deployments into deploy/deploy_all.py:

from deploy import \
base_packages, \
deploy_inventor_hat_mini, \
configure_pi, \
update_code

This replaces the deploy all file content instruction. We’ve removed update_packages from this, as we do not always want to update. But we have put in the base packages, Inventor HAT, I2C configuration, and code update. We will be extending this file later in the chapter.

Turn on the Raspberry Pi, powered from the mains adaptor, and run the following to make these changes:

pyinfra inventory.py -y deploy/deploy_all.py

This should give the ok result:

--> Results:
Groups: inventory / robots
[learnrob3.local] Changed: 4 No change: 0 Errors: 0

This shows that a number of changes have been made. Note that rerunning this would show Changed: 0 and No change: 4. Since we’ve configured the I2C on the Raspberry Pi, I recommend using SSH to the Raspberry Pi, then running sudo reboot to reboot with the changes.

We have enabled the I2C bus and installed libraries to talk to the HAT on this bus. Let’s log in and detect the HAT.

The Inventor HAT Mini is connected to the I2C bus we’ve connected. With I2C, we need a way to choose which device we are talking with. Just as with identifying houses along a road, an address allows us to specify which device we specifically want.

We should check that the Raspberry Pi can see the Inventor HAT Mini with sudo i2cdetect ‑y 1:

danny@learnrob3:~ $ sudo i2cdetect -y 1
0 1 2 3 4 5 6 7 8 9 a b c d e f
00: -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- 17 -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --

This scans the I2C bus 1 for devices attached to our Raspberry Pi. It shows numbers at the addresses if something is found. The device found at address 17 is the HAT.

If you cannot see this:

  • Power down the Raspberry Pi and carefully check that the Inventor HAT Mini has been plugged in.
  • Ensure that you have used deploy_all.py since adding the configure_pi code and import.
  • Ensure that you have rebooted since running deploy_all.py with configure_pi in it.

The addresses are hexadecimal, where each digit counts to 16, using the digits 0‑9, then letters A‑F instead of counting only 10 digits. It’s common convention when talking about hexadecimal numbers to prefix them with 0x, a zero, and a letter x.

We’ve used the i2cdetect tool to find our Inventor HAT Mini. This confirms first that it is connected and responding, and second that we have the right address, 0x17, for it. We can now start to send commands to it.

Test – demonstrating that the motors move

Section titled “Test – demonstrating that the motors move”

Our motors are connected, and we’ve detected the Inventor HAT along with the libraries to drive it. Let’s now make a test file to demonstrate that the motors work. Carry out the following steps:

  1. Create the folder named tests under robot. We can use this for any test code.
  2. Create a file there, robot/tests/test_motors.py, with the following content:
    from time import sleep
    import atexit
    import inventorhatmini
    board = inventorhatmini.InventorHATMini()
    left_motor = board.motors[1]
    right_motor = board.motors[0]
    def stop_motors():
    left_motor.stop()
    right_motor.stop()
    atexit.register(stop_motors)
    left_motor.enable()
    left_motor.speed(0.8)
    right_motor.enable()
    right_motor.speed(0.8)
    sleep(2)
  3. Run pyinfra inventory.py ‑y deploy/update_code.py to send this to the Raspberry Pi. Prop your robot up so the wheels aren’t in contact with the desk for this next step, as when it moves, it might not go in the direction you expect! Packaging from the robot electronics is good for this.
  4. To run this code, through SSH on the Pi, type the following:
    pi@learnrob3:~ $ sudo robotpython robot/tests/test_motors.py

Your robot motors should both turn. If this works, you can power down (sudo poweroff), switch to battery power, put the robot on the floor, and try it again.

You are now using sudo (super user do) to run your own commands. As the super user, the code is capable of writing to files that will stop the Raspberry Pi from functioning correctly. As such, it’s more important than ever to ensure your code and config are in git. sudo should only be used when needed.

The robot should now drive roughly forward. For reference, the battery is at the rear of the robot. It may move slightly to the side, but it should not be going backward, and both motors should be moving. This is a good place to git commit your work so far.

If you encounter any problems, refer to this troubleshooting chart:

SymptomLikely cause and solution
You see ImportError: No module named smbus2You may not have installed the required packages. Ensure you have followed the pyinfra steps above and resolved any errors with them.
You see errors resulting from the Python codePlease go back and carefully check that you have typed and uploaded the code above to the Raspberry Pi. Ensure you are running with sudo robotpython. Ensure that the pyinfra install steps work without errors.
One or both sides are going backwardThe motor wires are the wrong way. On the motor terminals only, swap the black and red wires. Refer to the Making connector cables section in Chapter 5, Building Robot Basics – Wheels, Power, and Wiring for help.
The light is on on the controller, but one or both motors are not moving.Please ensure that you’ve carefully stripped and folded over wires going into the WAGO connectors, as shown in the Making connector cables section in Chapter 5, Building Robot Basics – Wheels, Power, and Wiring.
No light on the motor controller and no movementPlease ensure that your battery is well charged.
Turning or veeringYou can expect some veer. If it is severe, ensure that both motors’ connections make firm contact and that neither the wheels nor the encoder disks are binding/caught on the chassis.

Table 6.1 – Troubleshooting chart

Your code should look like the version in the repository. In the repository, go to main/chapter‑6/1‑using‑python‑to‑test‑robot‑motors. To access the repository link, follow the steps in the Download the example code files section in the Preface.

Note that we will later be adding spinning and gentle turning to the robot.

By this point, you should have a robot that will drive forward, have seen it move, and have dealt with the preceding troubleshooting issues.

Now, our motors are moving and the robot drives using the test_motors.py code. But how does our motor test code really work? In this section, let’s take a closer look and understand this.

The first few lines of code here are imports:

from time import sleep
import atexit
import inventorhatmini

Imports are how Python code pulls in other libraries of code to use them. The inventorhatmini library is the one we installed for interacting with the HAT. The sleep function from the time library allows us to make a delay between starting and stopping motors. The atexit library will call something at exit, that is, when this program exits, which is a convenient way to handle how a program ends.

In the following lines, we connect the library to the HAT and the two motors:

board = inventorhatmini.InventorHATMini()
left_motor = board.motors[1]
right_motor = board.motors[0]

The first line here makes an InventorHATMini object and stores it in the variable board.

We then create shortcuts to access the motors, left_motor and right_motor, based on the board object. We need a function to stop these motors:

def stop_motors():
left_motor.stop()
right_motor.stop()
atexit.register(stop_motors)

We add the function stop_motors to stop each motor, and pass it into atexit.register(stop_motors), to guarantee that the motors will stop when Python exits, even when there are errors. Robots have a habit of driving off tables and into walls, which can damage the motors, motor controllers, and batteries, so it’s better to use atexit to stop the robot. See https://docs.python.org/3/library/atexit.html for details. We may also use this stop function in other ways later.

The next part drives the motors:

left_motor.enable()
left_motor.speed(0.8)
right_motor.enable()
right_motor.speed(0.8)
sleep(2)

The speed of the motors for this controller/library ranges from 0 to 1, so 0.8 is a little less than full speed, or 80% of the speed. We enable each motor and set their speed.

Finally, we ask the code to wait for 2 seconds, allowing the motors to drive forward for a while before stopping; otherwise, it would stop immediately.

Since we told it to stop the motors when the code exits, the motors stop after this delay.

We’ve now written and understood the code to test the motors. You’ve also seen it running. This confirms that you have a viable robot. You’ve learned the atexit trick to turn things off and about using a timer so that the robot has some time to run before exiting. Now, we will look at how we can use these motor speeds to steer the robot.

We’ve made the robot drive forward. But how do we steer it left or right? Let’s explore a few ways to steer robots. We can then settle on one that our robot will use and write some test code to demonstrate it.

The most common techniques for steering a wheeled vehicle (including a robot) fall into two major categories—steerable wheels and fixed wheels. We’ll look at these and their variants below.

In movable wheel designs, one or more wheels in a robot face in a different direction from the others. When the robot drives, the differently positioned wheel makes the robot turn. There are two common styles of movable wheel steering on a robot, as shown in Figure 6.1:

Figure 6.1 – Movable wheel steering types

Figure 6.1 – Movable wheel steering types

Figure 6.1 – Movable wheel steering types

The green arrows in Figure 6.1 show the direction of movement. The white arrows show changes to the shape of the robot and the angle of the wheels. Panel 1 shows the type of steering typically used in cars. When it is straight, the car goes forward. Panel 2 shows that the orientation of the front pair of wheels is changed by moving the lower bar. The car will turn in the direction of the wheels. This can be implemented as a rack-and-pinion using a tiny pinion gear, or with a linear actuator.

Another kind, shown in Panel 3, is articulated steering (also wagon-style steering or kart steering). To turn this, the whole front bar turns, which will steer the vehicle as shown in Panel 4. This is common in home-made racing karts.

There are other variants, including the following:

  • Robots with the ability to independently reorient wheels and drive sideways.
  • Ackermann steering, where the amount that each wheel rotates is different.

An example of articulated steering is the robot shown here in Figure 6*.*2. This was built by my son from the Unotron chassis by 4tronix, with an Arduino Nano controller:

Figure 6.2 – Wagon-style steering Unotron robot

Figure 6.2 – Wagon-style steering Unotron robot

Figure 6.2 – Wagon-style steering Unotron robot

The preceding pictures show the Unotron design, which uses a single-motor-driven rear wheel under the motor controller. A servo motor turns the whole front plate, steering the two front wheels, as shown in Panels A and B.

A chassis set up for movable wheel steering requires more moving parts and space to house it. Unotron is as simple as it gets. There is more complexity in other designs, which can lead to required maintenance. This is used in large earth-moving vehicles.

The distance needed to make a turn (known as the turning circle) or for robots with steerable wheel systems can be longer, as these must drive forward/backward to steer.

You require one large motor for the fixed axle, or you need complex mechanisms to distribute power across two motors. If the mechanism does not center after steering, then the robot veers. What are the other options, then?

Fixed-wheel steering is used frequently in robots, where the wheels’ axes are fixed in relation to the chassis. The relative speed of each wheel or set of wheels sets the direction of the robot. That is, the wheels do not turn from side to side; however, by one side going faster than the other, the robot can make turns. A typical use of this is known as skid steering, or differential steering, which is illustrated in the following diagram:

Figure 6.3 – Fixed-wheel steering or skid steering

Figure 6.3 – Fixed-wheel steering or skid steering

Figure 6*.*3 shows fixed-wheel steering in action. The white arrows show the relative speed of the motors. The green arrows show the direction of the robot. In Panel 1, the motors are going at the same speed, so the robot is driving straight forward.

In Panel 2, the motors on the right are going faster and the motors on the left are going slower. This results in the robot driving left and forward.

Steering this way has several advantages. Firstly, it is mechanically simple in that a drive motor per wheel is all that is needed to make turns. Skid steering allows a robot to turn on the spot, doing a full 360 degrees in a turning circle the width of the widest/longest part of the robot. If you intend to use tank tracks, you need this type of drive system.

There are some disadvantages to using this. When turning, a skid-steer system may drag wheels sideways, causing friction. Also, any minor differences in the motors, their gearing, or the controller output can result in a veer.

When positioning robot wheels, it’s important to consider the track width and wheelbase dimensions. See the following illustration:

Figure 6.4 – Wheel arrangements

Figure 6.4 – Wheel arrangements

Figure 6.4 – Wheel arrangements

The preceding figure shows wheel arrangements. With four or more wheels, as shown on the left of the preceding figure, you need to consider the length of the wheelbase versus the track width. If the wheelbase is longer, you’ll be pulling wheels at an angle away from the direction they drive in and will need more torque for steering. You usually need to make the track width wider.

With two wheels plus a castor, shown on the right of the preceding image, the wheelbase is effectively zero, as the robot would turn around the middle of the shared axis the wheels have. This is much simpler for a small robot, but might not be as effective on rough terrain. Since our robot is intended for use on indoor surfaces, this is the right choice. In this configuration, it may be more accurate to say it’s a differential drive than a skid steer.

The Mars rovers use a hybrid, with individually steered front and rear wheels, and each side driving in a skid-steer combination.

The controller we are using on our robot allows us to control two motor channels. However, with four motor channels, a builder could use four motors for special wheel types, known as Mecanum wheels:

Figure 6.5 – Mecanum wheels on the NE-Five robot

*Figure 6.*5 shows NE-Five, a robot created by Keegan Neave, which uses Mecanum wheels. These wheels allow skid-steering-style motions along with crabbing motions so that a robot can drive left or right without turning. Technically, this is still fixed-wheel steering.

These are amazingly flexible but mechanically complex, high maintenance, heavy, and a bit pricier than normal wheels. They are fun, however.

Let’s now see which of these steering styles we’ll use on our robot.

Our chassis uses two wheels plus a skid as a castor. As it has a driven wheel on each side, independently controlled, we can use differential steering. By varying the speed and direction of these wheels, we can steer our robot. We can also spin 360 degrees with it. The skid does have some friction, which could be upgraded with a ball or castor wheel to reduce this.

We can make the robot spin on the spot with one change to the previous code. Making one motor go back while the other goes forward spins the robot.

Let’s see how to do this, as follows:

  1. Find the following lines in test_motors.py (or in a copy, spin_robot.py):
    left_motor.enable()
    left_motor.speed(0.8)
    right_motor.enable()
    right_motor.speed(0.8)
  2. Modify this as follows so that one motor goes backward:
    left_motor.enable()
    left_motor.speed(0.8)
    right_motor.enable()
    right_motor.speed(-0.8)
  3. Use pyinfra with deploy/update_code.py to send it to the Raspberry Pi.
  4. SSH into the Pi and run this with sudorobotpython robot/tests/spin_robot.py, and your robot will now spin to the right. Swap the speed values on the left and right so the left is negative and the right is positive, and it spins the other way.
  5. What about less aggressive turns? We’ve used the same speed, 0.8, for each motor. We can make a gentler turn by making one of the speeds smaller than the other, like this (copy test_motors to robot/tests/gentle_turn.py):
    left_motor.enable()
    left_motor.speed(0.4)
    right_motor.enable()
    right_motor.speed(0.8)

Deploying and running this code makes the robot drive forward and turn gently to the left. You can experiment with the time to control how far the turn is, and the speeds to control how much it turns.

You’ve now seen how to steer robots, and practiced this with our robot, making it spin on the spot and drive forward while turning. In the next section, we’ll see how we can connect it to different robot behaviors.

Making an MQTT service for the main breakout

Section titled “Making an MQTT service for the main breakout”

For our robot to do interesting things, we will program it with behaviors, that is, with code to make it behave a certain way, for example, following a line. However, mixing up behavior code with underlying code to handle hardware differences is generally not a good idea. In this section, we’ll look at why, and how we will build such a service.

We’ll introduce MQTT, which stands for Message Queue Telemetry Transport, a system that can connect different programs running and sending/receiving messages with each other, either on the robot or from other devices, like a smartphone. One program or service can deal with motor topics.

When we chose our motor controller, we made trade-offs for our project. Breakouts and motor controllers may need to change or be different when we build our next robot. Although controlling the speed and direction of wheels is the same kind of operation, each controller does it slightly differently.

Making an interface service for a controller lets us use the same commands for different controllers. It can also simplify the underlying systems. We could create objects in code, or we could build services that talk to each other. Either way, this lets us change one part of the code without it making considerable changes in another, as illustrated in the following figure:

Figure 6.6 – Separating code concerns

Figure 6.6 – Separating code concerns

Figure 6.6 – Separating code concerns

In Figure *6.*6, Panel A illustrates a block of code that has different systems mixed into it. It’s hard to change; adding a new behavior or swapping the motor controller in this code would be quite tricky. It’s best to avoid mixing responsibilities in this way.

The code represented by Panel B shows separate systems interacting. They have a relationship where the B ehavior is in control of the M otor and S ensor interfaces.

Throughout the book, we will write many behaviors, and we can reuse services, perhaps extending them occasionally. After all, who wants to keep writing the same code? When you extend and make new behaviors, you can use this layer again too.

These services can be built to look the same from the outside on other robots, and our behaviors still work. Some robot builders use interfaces to swap real controllers for simulations of robots, to test complex behaviors. Let’s now look at how we connect the services.

MQTT is a system designed for sending small control or data messages between services or hardware, that is, lightweight messages.

MQTT works through a central broker, which clients (other programs) connect with. Those programs can be on the same computer or over a network, like a phone.

Programs can then listen, or subscribe, to certain sets of messages, or topics, for example, a /motors/wheels topic for setting the speed of a left motor. Other clients can then send or publish messages on this topic, for example, /motors/wheels with a payload of [0.8,0.4] signaling that the left motor should drive at 80% speed and the right at 40%.

There are some steps to getting this set up, but we can use PyInfra to deal with an MQTT broker, configure it, and set up Python libraries to use it. We can then test things out by publishing a test message.

Add the file deploy/deploy_mqtt.py with:

from pyinfra.operations import \
apt, systemd, server
mosquitto_packages = apt.packages(
name="Install mosquitto",
packages=[
"mosquitto",
"mosquitto-clients",
"python3-paho-mqtt"
],
present=True, _sudo=True)
mqtt_username = "robot"
mqtt_password = "robot"
if mosquitto_packages.changed:
server.shell(
f"mosquitto_passwd -c -b /etc/mosquitto/passwd {mqtt_username} {mqtt_password}",
_sudo=True)
files.file(
name="Ensure mosquitto password file exists",
path="/etc/mosquitto/passwd",
present=True,
user="mosquitto",
group="mosquitto",
_sudo=True
)
if mosquitto_packages.changed:
systemd.service(
name="Restart/enable mosquitto",
service="mosquitto",
running=True,
restarted=True,
daemon_reload=True,
_sudo=True,
)

This code starts by installing some packages. mosquitto (with two T’s) is our MQTT broker, letting MQTT clients send messages to each other. We install the test clients, mosquitto‑clients, along with the Python library paho‑mqtt.

Mosquitto needs a username and password for our code to connect with it. We’ve stored the state of the package install in a variable called mosquitto_packages, and if that has changed, we use a command to set the password. We need to ensure that Mosquitto owns this password file.

W arning: The MQTT passwords are currently in plain text and are a placeholder. Do not use real passwords in code put into git. We will look at securing this further in C hapter 18, Taking Your Robot Programming Skills Further.

Finally, we ensure that Mosquitto gets started when the Raspberry Pi starts and is restarted if things have changed. s ystemd is the Linux tool for managing services like Mosquitto and starting them. PyInfra is told to make sure it’s running and restarted if needed. This should also be added to deploy/deploy_all.py:

from deploy import \
base_packages, \
deploy_inventor_hat_mini, \
deploy_mqtt, \
configure_pi, \
update_code

Plug the Raspberry Pi into the power supply (not the battery) and run deploy_all again from your computer with pyinfra inventory.py deploy/deploy_all.py.

We should now be able to talk to it! For this, you will want two SSH windows or tabs open: one for sending messages and the other for seeing the results. Let’s set up a session on the Raspberry Pi to listen for messages. SSH in and type the command below to subscribe to messages:

mosquitto_sub -t "hello/#" -u robot -P robot -v

This command says to subscribe to an MQTT topic with ‑t hello/#, which means any message on any topic starting with hello. We use ‑v to show the full message topic.

There’s no output yet because it’s waiting for messages. Let’s send it one! Create another SSH session and try the following:

mosquitto_pub -t hello/robot -m "hello" -u robot -P robot

This publishes a message with the topic hello/robot and the message payload "hello".

When you run this, you should see this message in the subscribe window:

danny@learnrob3:~ $ mosquitto_sub -t "hello/#" -u robot -P robot -v
hello/robot hello

You can experiment and try different messages. When you are done, press Ctrl + C in the subscribe window to stop it.

Awesome, we’ve been able to send and receive messages. Let’s build something for our motors!

Our service will represent the Inventor HAT Mini and expose parts of its interface by subscribing to topics and accepting those messages.

The topics it will use are:

  • motors/wheels with a JSON payload of two numbers from -1.0 to 1.0, to set motor speeds for left and right
  • motors/stop with an empty payload to stop the motors
  • all/stop with an empty payload, to stop all activities

The service will also automatically stop the motors if there are no messages for 1 second, ensuring it will stop even if it loses contact.

We can use our design to build an MQTT client to the broker. Create the file robot/inventor_hat_service.py with the following:

import atexit
import json
import time
import inventorhatmini
import paho.mqtt.client as mqtt

Focusing on the new imports, we import json for a convenient way to decode/encode payloads and the paho.mqtt.client to connect with MQTT. We need some variables:

last_message = 0
board = inventorhatmini.InventorHATMini()
left_motor = board.motors[1]
right_motor = board.motors[0]

The last_message variable holds when we last received a message from MQTT. We’ll use this to time out when no new messages are received. We set up the Inventor HAT Mini board and convenient left/right motor variables. We need to handle updating the last_message variable:

def all_messages(client, userdata, msg):
global last_message
last_message = time.time()
print(f"{msg.topic} {msg.payload}")

The all_messages function handles debugging messages in our service, logging the topic and payload, as we saw with the mosquitto_sub command. It also updates last_message with the current time.

Let’s add a function to set motor wheel speeds:

def set_motor_wheels(client, userdata, msg):
left, right = json.loads(msg.payload)
left_motor.enable()
left_motor.speed(left)
right_motor.enable()
right_motor.speed(right)

This function decodes a JSON payload to get motor speeds and uses board functions to set them. We also need a function to stop the motors:

def stop_motors(client=None, userdata=None, msg=None):
left_motor.stop()
right_motor.stop()

This function uses the syntax =None for each of the message details, so they are optional, and we can reuse it for an atexit handler too. The motor service will connect to the MQTT bus, and will need to subscribe to topics when it has done so:

def on_connect(client, userdata, flags, rc):
print(f"Connected with result code {rc}")
client.subscribe("motors/#")
client.subscribe("all/#")

The on_connect function writes the result of a connection attempt and then subscribes our code to the motor and all topics. The # symbol matches anything after. We mentioned an atexit handler; let’s register that:

atexit.register(stop_motors)

We register stopping the motors at exit as we did before, so if anything goes wrong, the motors will stop. We also need to start setting up an MQTT client for this code:

mqtt_username = "robot"
mqtt_password = "robot"
client = mqtt.Client()
client.username_pw_set(mqtt_username, mqtt_password)
client.on_connect = on_connect

Here, we are setting up the MQTT client, giving it a username and password, and then wiring it to the on_connect function we made easier. Next, we need to link functions to subscribed topics as callbacks:

client.message_callback_add("motors/#", all_messages)
client.message_callback_add("motors/stop", stop_motors)
client.message_callback_add("motors/wheels", set_motor_wheels)
client.message_callback_add("all/stop", stop_motors)
client.message_callback_add("all/#", all_messages)

The function client.message_callback_add connects a function to the client, so for each of the topic matches, the correct function is called. The function all_messages is connected to all the topics. We finally need to connect to MQTT and enter a loop to wait for messages:

client.connect("localhost", 1883)
client.loop_start()
while True:
if time.time() - last_message > 1:
stop_motors()
time.sleep(0.1)

This code completes the system. It connects the client to the MQTT broker, using localhost to connect with a broker on the same Raspberry Pi with the default port of 1883. The code starts the message handler with client.loop_start, and then monitors to ensure things stop if there has been no message for 1 second.

We can send this using pyinfra inventory.py deploy/update_code.py. We can use two SSH sessions like we did before. In the first Raspberry Pi SSH session, start our service:

sudo robotpython robot/inventor_hat_service.py

This must run with sudo because of how the Inventor HAT Mini board works. The service will start and, as we saw before, is now waiting for messages.

Connected with result code 0

If you see result codes other than 0, please check the username and password and verify that you have deployed Mosquitto.

The tools MQTT UI (https://github.com/EdJoPaTo/mqttui) and MQTT Explorer (https://mqtt-explorer.com/) are good desktop tools for monitoring and interacting with MQTT on your robot.

We’ll test initially by publishing a stop message from another Raspberry Pi SSH session:

mosquitto_pub -t motors/stop -m "" -u robot -P robot

We should see this arrive on our Inventor HAT service:

motors/stop b''

We can get a little more ambitious and make the robot move (with it propped up):

mosquitto_pub -t motors/wheels -m "[0.8,0.8]" -u robot -P robot

The motors should start moving and stop after 1 second.

You may run into a few problems here.

  • If the robot doesn’t move, first check that you’ve run the simple motor test and the troubleshooting steps in the section Test – demonstrating that the motors move.
  • If it still doesn’t work, look at the log of the motors service. If you see json.decoder.JSONDecodeError, check that you have sent the correct message with mosquitto pub.

The deployment and Inventor HAT service code should look similar to the version in the repository. In the repository, go to main/chapter‑6/2‑making‑an‑mqtt‑service. To access the repository link, follow the steps in the Download the example code files section in the Preface.

We’ve built and troubleshooted a motor-handling service, which we can start to connect to. Let’s make a simple line behavior with it.

Our behaviors will all need to connect to MQTT and start a message loop. We can capture that in some common code in robot/common/mqtt_behavior.py:

import paho.mqtt.client as mqtt
import time
import json
def default_on_connect(client, userdata, flags, rc):
print(f"Connected with result code {rc}")
def connect(on_connect=default_on_connect, start_loop=True):
mqtt_username = "robot"
mqtt_password = "robot"
client = mqtt.Client()
client.on_connect = on_connect
client.username_pw_set(mqtt_username, mqtt_password)
client.will_set("all/stop", "")
client.connect("localhost", 1883)
if start_loop:
client.loop_start()
while not client.is_connected():
time.sleep(0.01)
return client
def publish_json(client, topic, data):
client.publish(topic, json.dumps(data))

The code here imports Paho to interact with MQTT and time. The default_on_connect function provides a placeholder to print debug information; it’s designed to be overridden.

The connect function has familiar connection code; however, we add client.will_set. This creates an MQTT last will, a last message that the broker will send on behalf of this code if it disconnects unexpectedly. This is similar to atexit and will ensure the motors stop if something goes wrong.

Unless start_loop is set to false, this connect function will automatically start client loop independently of our code. The client loop is used to send and receive messages from MQTT.

The while loop waits for the client to be connected with calls to client.is_connected(). Finally, there’s a helper to send a message with a JSON payload, automatically encoding it on the way.

We can use this to write a robot/behavior_line.py that will drive forward and stop:

from time import sleep
from common.mqtt_behavior import connect, publish_json
client = connect()
publish_json(client, "motors/wheels", [0.8, 0.8])
sleep(1)
publish_json(client, "motors/wheels", [0.8, 0.8])
sleep(1)

This code imports our mqtt_behavior and uses it to connect. Then we send wheels messages to move the motors, 1 second apart. It must send two, as with a 2-second wait the motor service would time out. It doesn’t need a stop message, as the MQTT will handle that.

Use the update_code deployment, then run this in an SSH session with robotpython robot/behavior_line.py, and the robot should drive both motors. Note that this behavior does not need sudo, because the other service is handling the hardware that needed it.

You should power off the robot, put it on the floor, and try it again there. You will need two SSH sessions – one to start the motor’s service and one to run the behavior.

We can now build other behaviors using the same service. This is a common interface, and I have built versions for other robot controllers that I use in my other robots. An exciting outcome is I can run this behavior_line.py code on ArmBot (the robot seen in *Chapter 1,*Introduction to Robotics) or my other Raspberry Pi robots. They all move forward for 2 seconds at 80% of their motor speed.

Let’s build more behaviors!

Now for the first behavior that will make our robot seem like one. Let’s make a quick sketch of a path for our robot to follow. For example, see Figure 6*.*7:

Figure 6.7 – A path for our robot to drive

Figure 6.7 – A path for our robot to drive

Figure 6.7 – A path for our robot to drive

In Figure 6*.*7, I’ve drawn a path. The straight lines are for driving forward for 1 second. We don’t yet have a way to consider distance traveled, only time. We can guess at times relative to distances, but this isn’t precise or repeatable. We will see later how to improve that repeatability. The curves are a turn where we slow one motor down more than the other.

The final spiral means a victory spin on the spot when the path is complete—we can do this by putting one motor in reverse while the other drives forward.

Let’s write this code. First, we want the imports: sleep and robot. But before we do anything, let’s make some helper functions for this behavior. I called my file behavior_path.py, and the code is shown in the following snippet:

from time import sleep
from common.mqtt_behavior import connect, publish_json
def forward(client, seconds):
publish_json(client, "motors/wheels", [0.8, 0.8])
sleep(seconds)
def drive_left(client, seconds):
publish_json(client, "motors/wheels", [0.2, 0.8])
sleep(seconds)
def drive_right(client, seconds):
publish_json(client, "motors/wheels", [0.8, 0.2])
sleep(seconds)
def spin_left(client, seconds):
publish_json(client, "motors/wheels", [-0.8, 0.8])
sleep(seconds)

The helpers use the same language we used to describe the behavior. We have forward, drive_left, drive_right, and spin_left. These are not in the service because other behaviors may use more continuous behavior than this.

These helpers each set the motor speeds, and then sleep for a determined number of seconds. We can then create the client and sequence them by adding the following code to behavior_path.py:

client = connect()
forward(client, 1)
drive_right(client, 1)
forward(client, 1)
drive_left(client, 1)
forward(client, 1)
drive_left(client, 1)
forward(client, 1)
spin_left(client, 1)

Now, we can upload this to the Raspberry Pi and run it via SSH with the following:

$ robotpython robot/behavior_path.py

Your code should look like the version in the repository. In the repository, go to main/chapter‑6/3‑following‑a‑path‑with‑mqtt. To access the repository link, follow the steps in the Download the example code files section in the Preface.

Now, if your robot is anything like mine, you saw it drive and make turns, but the turns have overshot/undershot in some way, and the robot may be veering to one side. Commit this code, then we can tune the turns here by changing the amount of time in the turn steps, like this:

forward(client, 1)
drive_right(client, 0.6)
forward(client, 1)
drive_left(client, 0.6)
forward(client, 1)
drive_left(client, 0.6)
forward(client, 1)
spin_left(client, 1)

Try to tweak these values to get close to 90-degree turns. This tweaking takes patience: change them and upload them. Tweaking values in code is a crude form of calibration, tuning code to match the quirks of our robot. Your robot’s calibration is likely to be a little different from mine. If you move between surfaces (for example, from a wooden floor to a carpet) or run this on a robot with different characteristics, then the timings will change. Battery freshness can also affect these times.

You may be able to account for some of the veering by tuning one motor to be slower in the straight function, like this (adjust for your own robot’s veer):

def forward(client, seconds):
publish_json(client, "motors/wheels", [0.8, 0.7])
sleep(seconds)

If you are lucky, the motors will be quite close. This code holds up for a while, but may be hard to fine-tune. Why do we get this veer?

Motor speeds can vary, even those from the same manufacturer. Other causes of minor variations are wheel diameters, axle positioning, weight distribution, slippery or uneven surfaces, wiring resistance, and motor controller variations. This variation makes it unlikely that you’d get a perfectly straight line from a robot this way. Later in the book, we will make use of the encoders/speed sensors to drive more accurately.

Without sensors, a robot isn’t able to determine where it is or if it has bumped into anything. If the robot runs into a wall, you’d probably have to go and move it to somewhere it has room to move.

Housekeeping: Now is a good time to commit your code, power off your robot, and put it on charge.

In this chapter, we’ve learned how to install the code for the Inventor HAT Mini and demonstrate that our motors work. We then started building an MQTT service for our behaviors to use, while noting how we could make a layer like that for other robots. We saw our robot move on a path and tuned it, while finding out some of the shortcomings of using motors without any sensors.

You can now use this when starting any hardware project: test the motors/output devices first, then create a layer for a behavior to use them, such that if their hardware later changes, you only need to change the motor code.

In the following chapters, we will start adding sensors and building behaviors with them. But first, we’ll see how to drive our robot remotely, using a phone to talk to MQTT!

Try these ideas to enhance your learning from this chapter:

  • Sketch out another simple path and write code for the robot to follow it. For example, try to get it to follow a figure-of-eight shape.
  • What topics would you subscribe to if you had an additional output to control – perhaps some LED (light-emitting diode) lights?
  • Consider how you would lay out a service for a robot with kart-style steering. What topics would it use? You don’t need to write the code yet, but having an interface in mind is a good start. Hint: It would probably have one motor speed for the drive and a motor position for the steering.

Please refer to the following for more information: