Programming Encoders with Python
local graph
Chapter 11 — Programming Encoders with Python
Section titled “Chapter 11 — Programming Encoders with Python”Programming Encoders with Python
Section titled “Programming Encoders with Python”Sensing how the robot has moved is key to building autonomy in a robot; a starting point here is to detect how its own wheels have turned. Encoders are a key tool for doing this. We drove a robot along a path back in Chapter 6, Drive and Turn – Moving Motors with MQTT and Python, but it’s unlikely that it has stayed on course. Using encoders can allow us to correct that. If you tried in that chapter to drive a specific distance, it’s likely the robot overshot or undershot, also a problem that encoders can help with. This chapter investigates types of encoders, how to use those present on your robot, and then how to build behaviors to correct moving in a straight line and for a particular distance. We will then look at how to make a specific turn. Please note that this chapter does contain math. But don’t worry, we’ll break it down step by step.
In this chapter, you will learn about the following topics:
- Measuring the distance traveled with encoders
- Detecting the distance traveled in Python and MQTT
- Driving a specific distance
- Driving in a straight line
- Making a specific turn
Technical requirements
Section titled “Technical requirements”Before we get started, make sure you have the following parts:
- The robot with the Raspberry Pi built in the previous chapters
- Digital caliper
- Tape measure or ruler
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.
Measuring the distance traveled with encoders
Section titled “Measuring the distance traveled with encoders”Encoders are sensors that detect movement, encoding motion into electrical signals. They may measure axle rotation or movement along a straight track. Tachometers (tachos) measure shaft rotational speed, whereas encoders measure position or incremental change in position, from which speed can be calculated.
Estimating how far a robot has traveled is also known as odometry, and encoders will be an important source of data for this.
With this understanding of what encoders are, let’s look at the encoder on your robot.
The encoder on your robot
Section titled “The encoder on your robot”Your robot is already equipped with a set of magnetic encoders and sensors. Look at the following diagram to see what you have got:

Figure 11.1 – Your robot’s magnetic encoder
Figure 11.1 – Your robot’s magnetic encoder
The preceding diagram shows both a photographic and diagrammatic representation of the encoders present on each FIT0450 motor in your robot. The left image shows the rear of a robot motor. Around the rear of the motor shaft is a M agnetic e ncoder disk. This rotates past a pair of Magnetic sensors.
The diagram on the right shows a diagram of the arrangement, with the N (N orth) and S (S outh) poles alternating on the magnetic encoder disk. This pattern passes the sensors, known as H all effect sensors, which detect the changing magnetic fields.
In the FIT0450 type we are using, the encoder disk is on the motor shaft, which is geared down for wheel rotations. This means that the sensor may rotate many times for a single wheel rotation, so we can get precise information about wheel movements.
With the robot powered off, try rotating a wheel slowly, and see how the encoder disk rotates more quickly than the wheel.
Using encoder sensor devices requires pulse counting. The Inventor HAT Mini board library has tools to fetch the counts. Let’s test this out.
Simple sensor counting with the Inventor HAT Mini
Section titled “Simple sensor counting with the Inventor HAT Mini”We’ll make an initial test by importing the Inventor HAT Mini encoders and printing the count on each side as the motors move. This example is derived from the robot/tests/test_motors.py example from the Test – demonstrating that the motors move section in Chapter 6, Drive and Turn – Moving Motors with MQTT and Python. Copy it into robot/tests/test_encoders.py and make the highlighted changes:
from time import sleepimport atexitimport inventorhatmini
board = inventorhatmini.InventorHATMini()left_motor = board.motors[1]right_motor = board.motors[0]left_encoder = board.encoders[1]right_encoder = board.encoders[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)
while True: print("Left encoder: ", left_encoder.count()) print("Right encoder: ", right_encoder.count()) sleep(0.1)This test code is mostly familiar. However, we add a left and right variable to reference the encoders, and a while loop to output the encoder counts until we stop the program.
Power up the robot, then use pyinfra inventory.py deploy/update_code.py on your computer to send the code. Running this requires us to stop the Inventor HAT service. Prop your robot wheels off the desk, then use this sequence (via SSH) to run the test (and see the output):
$ sudo systemctl stop inventor_hat_service$ sudo robotpython robot/tests/test_encoders.pyYou should see it counting forward:
Left encoder: 0Right encoder: 0Left encoder: 79Right encoder: 60Left encoder: 286Right encoder: 223Notice here that the counts change as you rotate the wheels, confirming that there’s working encoder feedback. Rotate the wheel both ways to see the count decrease, too. When you are done, press Ctrl + C to stop it. We should check that this works before continuing.
Troubleshooting
Section titled “Troubleshooting”If you have run into any trouble here, check the following:
- This code requires exclusive I2C bus access to the Inventor HAT Mini. That means if the Inventor HAT service is running, this won’t be allowed to.
- Permission-denied errors usually mean you need
sudoon a command. - If you see tracebacks or other Python errors, double-check the preceding code.
- If you see no counting, or a wheel is counting backward, carefully check the encoder wiring with the diagrams in Figure 5.12 in Chapter 5, Building Robot Basics – Wheels, Power, and Wiring – you need to check the wiring. You may need to swap the encoder signal wires, so forward is a positive result on both sides.
This should have fixed common errors. You could try changing the direction of the motors and see whether the wheels go the other way.
We had to stop a service to be able to access the same I2C device. Our MQTT bus usually means multiple behaviors can interact with subsystems. Don’t worry, we’ll put it back on the MQTT bus so things can run together again.
We’ve tested the encoders on the robot, seeing feedback on your screen as they moved. What kind of information are we collecting here?
Encoding absolute or relative position
Section titled “Encoding absolute or relative position”The following diagram shows these types of sensors in comparison:

Figure 11.2 – Comparing absolute and relative sensing
The diagrams in Figure 11.2 illustrate these types of positioning.
The left circle shows an Absolute position ing at 60 degrees to a given 0 point. Absolute position encoders can encode the exact position and do not need information about the previous position, but may need to be calibrated to determine how an encoding matches a real-world location. In a crude form, a variable resistor in a servo motor is an absolute encoder. Absolute position encoding can be done through more complicated optical or magnetic markers on a wheel or strip. Absolute sensors can be more bulky, expensive, or require many inputs. An absolute encoder strip or wheel is also known as a scale.
The circle on the right shows R elative p ositioning. An encoder reads a movement of 60 degrees. However, this is relative, as we don’t know where we started from, only that we’ve moved by 60 degrees. Relative encoders encode a relative change in position – that we have taken a certain number of steps clockwise or counterclockwise, for example. They can measure a position relative to the last time we measured by counting the number of slots that have passed. These are also called incremental encoders. This hardware is cheap and straightforward. A drawback is that adding relative movements can accumulate errors, and your code needs to remember where it was last. Mistakes in these errors will cause sensors to drift over long distances.
If a sensor can tell you where something is at, then it is absolute. If it can tell you how much it has moved by, it is relative.
The Inventor HAT Mini is storing counts in its controller memory. We can prove this with an experiment:
- Start the preceding test code again and note the encoder counts.
- Stop the test code, then start it again, noting the new encoder counts.
- Power down the robot completely, disconnecting the power.
- Power the robot up, stop MQTT, and start the test again.
- Check the new encoder counts.
You should now see how the encoder counts are relative to some arbitrary starting point in memory, and not an absolute wheel position.
We are using relative encoders. We’ve talked about counting, but how is it counting in both directions?
Encoding direction and speed
Section titled “Encoding direction and speed”Basic relative encoding measures how many transitions pass the sensor. We can use that to derive the speed and distance. By using two sensors slightly apart, we can also derive the direction. Figure 11.3 shows how this works:

Figure 11.3 – Encoding speed and direction with multiple sensors
Figure 11.3 – Encoding speed and direction with multiple sensors
The top shows E ncoding s peed only. On the left, the magnetic encoder disk has alternating north and south poles. As they pass the sensor element, they generate electronic pulses. Each pulse has a rising edge, where it goes up, and a falling edge, where it goes down. You can count these edges to detect movement. If you drive a motor with a direction, you can use a system with a single sensor like this, as we will do in our robot. This state wheel shows how it transitions only between 1 and 0.
A system using two sensor elements can encode speed with direction (as shown in the Encoding speed with direction image), producing twice as many edges for more resolution. By placing the second sensor so that its edges are out of phase with the first, it can generate an edge halfway between the edges of the first sensor.
We can then combine the pairs to get a sequence: 10, 11, 01, 00. Because it has four phases, it is known as quadrature encoding. By seeing in which direction the sequence occurs, we can also detect which direction a motor is turning.
You can use direction encoding to build record and replay robots. You can also find this in a mouse, where the direction is essential information, so the additional complexity needed to encode the directions is required.
The FIT0450 motors we have used on our robot include quadrature encoders. These magnetic encoders account for four of the six pins we used to connect our motors to the Inventor HAT Mini.
Let’s see what other types of encoders there are.
Other types of encoders
Section titled “Other types of encoders”You’ve seen how the encoders on our robot work using magnetism; the other common engineering approach is to use light. We can look at the other types and examples of encoders, along with their parts, to better understand them. See the following diagram:

Figure 11.4 – Encoder sensors
Figure 11.4 – Encoder sensors
The top left of the preceding figure shows an O ptical encoder sensor. These shine a L ight source through a slot and detect the beam with a L ight sensor on the other side. This way, as the opaque sections move through it, they break the beam and produce an electrical signal. The top right shows a photo of a real device. Due to the beam being interrupted, we call them photo interrupters, optical encoders, or opto-interrupters.
The middle left shows an optical E ncoder strip with transparent and opaque bars. When it moves, the passage of the bars lets us measure how much it moved.
In the middle right is an E ncoder disk. This wraps the bars around a disk, so we can measure rotation – perfect for wheels. Multiple optical encoders can be used in a quadrature encoding arrangement to detect direction and increase resolution.
The bottom row shows modules combining a gear motor with magnetic encoders, an N20 motor combination, and a larger 12 V motor.
We tested our encoders and performed some small experiments with them. It’s now time to integrate them with MQTT for further experiments.
Detecting the distance traveled in Python and MQTT
Section titled “Detecting the distance traveled in Python and MQTT”Our goal is to make encoder data available in real time for other robot behaviors to use it. In this section, we will make the encoder data available over MQTT, initially as counts, but then see how to convert counts to distances as a more useful measurement.
We will then test them in a simple behavior to demonstrate that they are ready to be used in other robot behaviors. Let’s add them to our MQTT bus.
Adding encoders to the Inventor HAT service
Section titled “Adding encoders to the Inventor HAT service”The Inventor HAT service needs exclusive access to the board’s services, but reflecting functions on the MQTT bus makes them available to other behaviors. The architecture here keeps a direct sensor interface in one module and distributes the data from it over MQTT, so behaviors on the robot can consume it.
We’ll represent them with the sensors/encoders/data MQTT topic with a payload of left_count and right_count.
We’ll also subscribe to the sensors/encoders/control/reset topic to reset the counts to 0 between behaviors.
We are going to change our Inventor HAT service in a few places. Let’s start with the imports in robot/inventor_hat_service.py:
import atexitimport jsonimport timefrom functools import partial
import inventorhatminiimport paho.mqtt.client as mqttfrom common.mqtt_behavior import publish_json
last_message = 0board = inventorhatmini.InventorHATMini()left_motor = board.motors[1]right_motor = board.motors[0]left_encoder = board.encoders[1]right_encoder = board.encoders[0]pan = board.servos[0]tilt = board.servos[1]In this code, we’ve imported publish_json to help us publish the sensor data. We’ve then added variables to track each of the encoders.
We then need a function to get the encoder data and publish it via the MQTT client. Add these functions between on_connect and exit_handler:
def update_encoders(client): publish_json(client, "sensors/encoders/data", { "left_count": left_encoder.count(), "right_count": right_encoder.count() } )
def reset_encoders(*_): left_encoder.zero() right_encoder.zero()The update_encoders function publishes the count for each encoder on the sensors/encoders/data topic. This creates a continuous live stream of sensor data that any behavior can subscribe to. The reset_encoders function is an MQTT handler. It ignores any parameters and resets the count on both encoders.
We need to subscribe to the encoder control topic in the on_connect function:
def on_connect(client, userdata, flags, rc): print(f"Connected with result code {rc}") client.subscribe("motors/#") client.subscribe("leds/#") client.subscribe("all/#") client.subscribe("sensors/encoders/control/#")Let’s add reset_encoders as an MQTT message callback handler; find this code and add the highlighted line:
client.message_callback_add("all/stop", stop_motors)client.message_callback_add("all/#", all_messages)client.message_callback_add("sensors/encoders/control/reset", reset_encoders)We are now going to change the end of robot/inventor_hat_service.py to regularly call update_encoders:
while True: update_encoders(client) if board.switch_pressed(): client.publish("launcher/poweroff", "") if time.time() - last_message > 1: stop_motors() time.sleep(0.05)We’ve also added some convenience code to power off the robot when the USER button on the Inventor HAT Mini is pressed.
Send this updated Inventor HAT service with pyinfra. We can now monitor our encoders with MQTT. SSH to the Pi, and run mosquitto_sub ‑u robot ‑P robot ‑t sensors/encoders/data to see the output.
If you move the wheels, you will see the encoder values change:
sensors/encoders/data {"left_count":587,"right_count":34}sensors/encoders/data {"left_count":667,"right_count":-13}sensors/encoders/data {"left_count":755,"right_count":-64}For a more interesting display, try installing m qtt u i (https://github.com/EdJoPaTo/mqttui). This lets you explore messages on the robot and will make simple graphs. See the mqttui project for documentation.
You can also reset these to zero:
$ mosquitto_pub -u robot -P robot -t sensors/encoders/control/reset -nThe ‑n flag here means there’s no payload. Not all messages need a payload.
High-frequency messages with large payloads can start to saturate the bus and possibly slow down the Raspberry Pi. Be mindful of message sizes or frequencies.
Let’s troubleshoot any issues.
Troubleshooting encoders on MQTT
Section titled “Troubleshooting encoders on MQTT”If you have run into any problems here, check the following:
- Please ensure you have had the original encoder test working first, and followed the troubleshooting steps there.
- If you see tracebacks or other Python errors, double-check the preceding code.
- Use
journalctl ‑u inventor_hat_serviceand jump to the end with Shift + G to check for errors or tracebacks if you see nothing on the topic.
We now have encoder data on the MQTT bus! However, encoder counts are arbitrary, so it’s more useful to turn the counts into a distance in millimeters. Let’s look at the relationship between encoder ticks and the distance moved in millimeters.
Turning ticks into wheel revolutions
Section titled “Turning ticks into wheel revolutions”Before we can get millimeters, we need to convert from encoder counts to wheel turns or revolutions. We need to know how many slots there are on the encoder and the motor gear ratio. The FIT0450 motor has a gear ratio of 120:1, and our quadrature encoders will read 32 pulses per encoder disk revolution. We’ll let our code multiply those to get the number of counts per revolution in robot/inventor_hat_service.py:
left_encoder = board.encoders[1]left_encoder.counts_per_rev(32 * 120)right_encoder = board.encoders[0]right_encoder.counts_per_rev(32 * 120)When we set counts_per_rev, the Inventor HAT library can divide the encoder count by this value and determine how many times the wheel has turned, or the fraction of a full turn the wheel has made. counts_per_rev sets the precision of our encoders, such that a high gear ratio or an encoder disk with more regions could increase that precision.
As a general rule, we let the computer do calculations. Not only is that easier for us than calculating it, but logically laying out the variables (gear ratio and encoder disk count) and their relationship (multiplying them) makes it easier to update when things change than pasting the result of doing your own arithmetic (3,840), which may look arbitrary later.
We can then have this output in the update_encoders function:
def update_encoders(client): publish_json( client, "sensors/encoders/data", { "left_count": left_encoder.count(), "left_revolutions": left_encoder.revolutions(), "right_count": right_encoder.count(), "right_revolutions": right_encoder.revolutions(), } )If you deploy services, and then subscribe to the encoders data topic, you will see the following:
sensors/encoders/data {"left_count":-1920,"left_revolutions":-0.5,"right_count":-339,"right_revolutions":-0.08828125}sensors/encoders/data {"left_count":-1920,"left_revolutions":-0.5,"right_count":-339,"right_revolutions":-0.08828125}sensors/encoders/data {"left_count":-1919,"left_revolutions":-0.49973958333333335,"right_count":-343,"right_revolutions":-0.08932291666666667}We can now see how much the wheel has turned. We are closer to calculating distances. One way to think about distances is how much wheel tread must have moved on the ground to make a distance. This has a relationship to the diameter of the wheels.
Where other machines use encoders
Section titled “Where other machines use encoders”An encoder is used where the rotation of an axle needs to be controlled or measured precisely. These may be electronic or mechanical sensors.
Computer printers, scanners, and robot vacuum cleaners combine encoders with DC motors. Sensing what angle a motor has turned through is an essential component of servo motors, which we saw in Chapter 10, Using Python to Control Servo Motors. High-end audio or electrical test/measurement systems use encoders in control dials. These are self-contained modules that have knobs, but users can turn them indefinitely.
Industrial robots use encoders for record-and-replay interfaces. Users press a Record button and move a robot, such as an arm, through a set of movements, then press a S top button. After the user has recorded this sequence, the robot can replay it.
Now we have measured our movement in terms of wheel revolutions, how can we get that into millimeters?
Driving a specific distance
Section titled “Driving a specific distance”We can use our sensors to drive a specific distance, putting the robot as close as possible to the target. We will need the geometry of the robot to do so, though.
Accounting for the wheel diameter
Section titled “Accounting for the wheel diameter”A robot with wider wheels will move further forward per revolution than a robot with smaller wheels; clearly, these have a relationship. The following diagram shows how:

Figure 11.5 – Relating encoders to distance moved
Figure 11.5 – Relating encoders to distance moved
The Revolutions to radians diagram panel shows how the number named Pi, written π, relates revolutions to radians. This is useful because multiplying the wheel radius by radians (as we do in the Radians to distance moved panel) tells us how far it has rolled. For any circle, we can get radians by multiplying by 2 times π. Pi is the ratio of a circle’s diameter to its circumference (the distance around it). The measure of the angle, or how much we’ve gone around a circle, is known as an arc length, and its unit is radians.
The Finding the diameter panel shows measuring the diameter of our robot’s wheel with digital calipers. Fit the calipers around the widest part of the wheel. Mine, rounded to the nearest mm, are 67 mm. We halve the diameter to find the radius.
The Converting from encoder counts to distance moved panel puts this all together. The Inventor HAT library uses the E ncoder count and Counts per rev (how many ticks per revolution) input to get R evolutions. Multiplying revolutions by 2 π gets us the A ngle turned in radians. We combine the A ngle turned with the W heel radius to get the D istance moved in mm. We assume the left and right wheels have the same diameter.
Let’s build this! At the top of robot/inventor_hat_service.py, add wheel_radius:
left_encoder = board.encoders[1]left_encoder.counts_per_rev(32 * 120)right_encoder = board.encoders[0]right_encoder.counts_per_rev(32 * 120)wheel_radius = 67 / 2Because the encoder is on the motor shaft, each wheel revolution includes 120 motor revolutions, so we multiply the encoder pulses by the gear ratio.
We can then start getting more information about our encoder in the update_encoders function:
def update_encoders(client): left_data = left_encoder.capture() right_data = right_encoder.capture() publish_json( client, "sensors/encoders/data", { "left_distance": left_data.radians * wheel_radius, "right_distance": right_data.radians * wheel_radius, } )We now use the encoder.capture method to snapshot all the encoders information from the Inventor HAT at the same time, as reading them at different times could introduce inconsistencies. The Inventor HAT library already converts encoder counts to radians for us; so we just need to multiply it by the wheel radius to get the distance.
Our encoder data now returns the more useful distances in mm. Deploy this with pyinfra. Try it out by subscribing to the sensors/encoders/data topic and then gently turning the wheels, or pushing it along the floor:
sensors/encoders/data {"left_distance":25.7078817587896,"right_distance":67.36670934232926}This is a great time to make a git commit. What about speeds?
Measuring speeds
Section titled “Measuring speeds”We are currently returning the position of our encoders, but not their speed. However, the encoder library for the Inventor HAT board also returns the radians per second.
Add the highlighted code to the update_encoders function in robot/inventor_hat_service.py:
def update_encoders(client): left_data = left_encoder.capture() right_data = right_encoder.capture() publish_json( client, "sensors/encoders/data", { "left_distance": left_data.radians * wheel_radius, "right_distance": right_data.radians * wheel_radius, "left_mm_per_sec": left_data.radians_per_second * wheel_radius, "right_mm_per_sec": right_data.radians_per_second * wheel_radius, } )Here, we’ve converted radians per second into mm per second using the wheel radius. Use pyinfra to send this again, and try rotating the wheels. You should see that while the distances have changed, the speeds only register momentarily while you are moving the wheels.
Let’s try using the distance in a behavior.
Driving a known distance
Section titled “Driving a known distance”We’ll make a behavior to drive until the distance has passed a certain limit, and then stop. Create the robot/drive_known_distance.py file, with familiar imports:
import ujson as jsonimport timefrom common.mqtt_behavior import connect, publish_jsonWe start by having a place to store the current sensor state:
class DriveKnownDistanceBehavior: def __init__(self): self.left_distance = 0 self.right_distance = 0The next part of the code handles our sensor data:
def on_encoders_data(self, client, userdata, msg): distance_data = json.loads(msg.payload) self.left_distance = distance_data['left_distance'] self.right_distance = distance_data['right_distance']We’ll connect on_encoders_data to MQTT, so it’s called every time there’s new encoder sensor data. We then have a function to drive a line with an expected distance:
def drive_line(self, client, expected_distance=1000, speed=0.8): distance_reached = False while not distance_reached: # Sense left_error = expected_distance - self.left_distance right_error = expected_distance - self.right_distance
# Think distance_error = max(left_error, right_error) if distance_error < 1: distance_reached = True current_speed = 0 else: current_speed = speed # Act publish_json(client, "drive_known_distance/plot", { "left_error": left_error, "right_error": right_error, "time": time.time() }) publish_json(client, "motors/wheels", [current_speed, current_speed]) time.sleep(0.1)The drive_line method is called with an mqtt client and, optionally, a distance and speed. There are settings as defaults here.
The distance_reached variable tracks whether we’ve reached the expected distance or not. The while loop after will run until we’ve reached the expected distance.
The Sense section finds the error for each encoder, where the error is how far we are from the target. We publish this information for a plot. The left_distance and right_distance members are updated asynchronously by the MQTT callbacks, so this loop always uses the latest received values.
The Think section finds the largest error. If it is below 1, we have arrived, so we set the speed to 0 and set the distance reached flag to true. Otherwise, we use the default speed.
The Act section publishes this calculated speed to the wheels.
We then finish off the behavior with a start method, which sets up our MQTT client, then resets the encoders. It then runs our drive_line method:
def start(self): client = connect() client.subscribe("sensors/encoders/data") client.publish("sensors/encoders/control/reset") client.message_callback_add("sensors/encoders/data", self.on_encoders_data) self.drive_line(client)
behavior = DriveKnownDistanceBehavior()behavior.start()The bottom of the program creates the behavior and starts it.
Let’s wire it into our services and phone app with familiar code. We will need a corresponding section in deploy/deploy_services.py:
code = files.put( name="Update drive_known_distance code", src="robot/drive_known_distance.py", dest="robot/drive_known_distance.py")deploy_service("drive_known_distance", "robot/drive_known_distance.py", False, common.changed or code.changed)We have data plotted here, so let’s add a page to control the behavior and see its plot.
Making the drive known distance page
Section titled “Making the drive known distance page”We are going to be able to use the tools we’ve been building for graphing and page creation. The page here is again constructed from familiar components.
Create the robot_control/drive_known_distance.html file:
{% extends "robot_control/page.html.j2" %}{% block title %}Drive known distance{% endblock %}{% block content %} <button id="start">Start</button> <button id="stop">Stop</button> <div class="line_chart"> <canvas id="plot"></canvas> </div>
<script type="module"> import 'https://cdn.jsdelivr.net/npm/chart.js'; import { connect, publish_when_clicked } from './mqtt_client.js'; import { create_timeseries_chart } from './chart_helper.js'; let mqttClient = connect();
publish_when_clicked(mqttClient, "start", "launcher/start", "drive_known_distance"); publish_when_clicked(mqttClient, "stop", "launcher/stop", "drive_known_distance");
const behavior_chart = create_timeseries_chart('plot', ['left_error', 'right_error']);
mqttClient.subscribe('drive_known_distance/plot'); mqttClient.on('message', (topic, message) => { switch (topic) { case 'drive_known_distance/plot': behavior_chart.update_data(JSON.parse(message)); break; } }); </script>{% endblock %}This code extends the now familiar page template, with title, control buttons, and a chart.
In the JS, we connect the launcher buttons and make a time-series line chart with the left and right error values. We then have an MQTT topic handler for the behavior plot data.
We also need to add a menu option in robot_control/index.html:
<li><a href="drive_known_distance.html">Drive a known distance</a></li>Send it over using the Pyinfra deploy_services script. Power down, go to battery power, and put the robot on a clear floor, then use your phone to start this.
The robot should drive roughly a meter. Let’s troubleshoot to ensure that things are working.
Troubleshooting
Section titled “Troubleshooting”You may see some problems, but we can diagnose them:
- If you see no movement, try (via SSH) using
journalctl ‑u drive_known_distanceto see its logs. - Ensure that previous examples for getting encoder data have worked.
- You may also need to use
journalctlto check theinventor_hat_servicetoo. - If it’s bending off to the left or right, we actually expect that at this point. You would be lucky if it drove in a perfect straight line yet.
We now have the robot trying to drive a distance, but the motors aren’t matched. The chart shows it clearly:

Figure 11.6 – Drive known distance screen
Figure 11.6 – Drive known distance screen
When the page loads, there’s an initial 0 value. When the user clicks the S tart button, the graph jumps up to 1,000, the distance from the target. However, it’s then clear that the left graph reaches the end before the right, and overshoots by 200 mm (20 cm). In an ideal scenario, those left and right errors should move together, without a gap.
Let’s fix the graph starting before we pressed S tart.
Chart helper fix
Section titled “Chart helper fix”The chart time starts from the page load, instead of from when you press the button. In robot_control/chart_helper.js, find create_timeseries_chart and change it to this:
export function create_timeseries_chart(element_name, columns) { const chart_data = prepare_datasets(columns); const ctx = document.getElementById(element_name); const chart=new Chart(ctx, { type: 'line', data: chart_data, options: options_for_timeseries });
let first_item = true;
return { update_data: (data_item) => { data_item.time = data_item.time * 1000; if (first_item) { chart_data.datasets[0].data[0] = data_item; first_item = false; } else { chart_data.datasets[0].data.push(data_item); } chart.update(); } }}In the highlighted code, a first_item variable has been added, so the chart tracks whether the first item was sent, and replaces the placeholder data as soon as that happens.
Send this with pyinfra, and the graph should look better. However, the right motor is moving slower than the left, making the robot turn. So, in the next section, let’s use this information to straighten things up.
Driving in a straight line
Section titled “Driving in a straight line”By now, you have seen differences in the outputs. In only 1 meter, my left side is 20 cm ahead of the right, an error that is increasing. It’s rare for two motors to be the same. This section will use the real-time encoder data and verify motor synchronization.
How can we use encoders to correct our course and drive in a straight line?
There are two methods: either closed-loop control of the motors to ensure that they are at the expected speed, or balancing the speed between motors. Some systems combine both approaches. We are going to implement closed-loop motor control, because it’s useful for many behaviors.
Tracking over time
Section titled “Tracking over time”We will be tracking time differences a lot, and for our motor control, knowing how much time has elapsed since the last update will be essential for determining speed. So let’s make a quick helper for this in robot/common/time_stepper.py:
import time
class TimeStepper: def __init__(self): self.last_update = time.time()
def step(self): new_time = time.time() time_difference = new_time - self.last_update self.last_update = new_time return time_differenceThis stores a last_update time, and has a step method that calculates a time difference (also known as a time delta) each time it is called.
This component is ready to use, but we also need another component, the Proportional - Integral - Differential (PID) controller, which we’ll investigate and build in the next section.
Closed-loop motor control with a PID
Section titled “Closed-loop motor control with a PID”Any system using a feedback loop for control is closed-loop, but when we say closed-loop motor control, we specifically mean taking the output speed of a motor shaft and using that to control the input power to the motor. The following figure shows how this loop works:

Figure 11.7 – Closed-loop speed control
Figure 11.7 – Closed-loop speed control
For each motor, we have an I ntended speed – the set point for this system in mm/s. This is compared with the M easured speed (also in mm/s) from the encoder to generate an error. Note the units on these boxes. The error is fed to the PID c ontroller, which generates an output in terms of motor control effort. If the motor speed is too low, it should result in more motor effort to speed it up, and if it’s too high, then motor effort should be lower. The output is used to control the power to the motor. This system can result in smooth motor movement.
In Chapter 9*,* Avoiding Obstacles with Distance Sensors, we saw how proportional control could lead to smooth distance sensing. We will build on that into a PID controller. This has three components:
- Proportional (P): The error value multiplied by a gain, or a proportional constant. This corrects for immediate errors in a way we’ve seen before.
- Integral (I): Corrects for continuing errors, for example, we are close but not quite on track for a long time. A motor can be consistently slower than the set point. This is multiplied by an integral constant.
- Derivative (D): Damps the response of the system to reduce the chance of it overshooting. Note that our system is also damped by the physics of motors and encoders. This would also be multiplied by a derivative constant.
By manipulating the gain settings, we tune how much each component influences the outcome of the controller. We won’t be using the d erivative component at this stage.
We need an unused motor speed capacity to be able to speed up a bit. If the speed is too close to 100%, we get clipping. An integral behavior with clipping can make the robot behave strangely, so watch out for clipping at 100%!
Leave headroom for PID adjustments – use no more than 80% of motor speed.
Now that we have some idea of how a PID controller works, let’s build one in code.
Creating a Python PID controller object
Section titled “Creating a Python PID controller object”The PID controller code is a fundamental robotics building block, and we’ll use it to control wheel speed automatically based on encoder feedback. We will start with just proportional control, and add in the other terms as we need them. You will use the basic concepts here in many robotic systems. Add the robot/common/pid_controller.py file:
class PIDController: def __init__(self, proportional_constant, integral_constant=0): self.proportional_constant = proportional_constant self.integral_constant = integral_constant self.integral = 0
def control(self, error, time_difference=1): self.integral += error * time_difference return self.proportional_constant * error \ + self.integral_constant * self.integral
def reset(self): self.integral = 0This file does not have any imports. The PIDController class represents our controller.
The constructor (__init__) takes a proportional_constant and integral_constant. These are adjustments that let us control how much the error influences the output. We start the integral at 0.
The control method is called when we have a new error value and want to generate a new control signal. Its parameters are the current error value and time_difference.
Since we can’t always predict how often the control method will be called, the time_difference parameter allows us to capture how long has passed (in seconds) since the last call. We’ll send our time stepper data with this parameter.
The integral accumulates errors over time, so that the longer there is a steady state error, the more it will influence the output. At each step, we multiply the error by the time_difference to account for how long it was in that state. An error for 0.2 seconds will have more influence than the same error for 0.1 seconds.
The last line of the control method calculates the output. Each component, proportional and integral, is multiplied by a constant, controlling their influence on the output, then added together.
Finally, we have a reset method, so that the accumulated value of integral can be reset when we stop a robot or change direction. Otherwise, it can build up and cause problems.
With our PID controller, we can use it to adjust motor speeds in the next section.
Writing the wheel control service
Section titled “Writing the wheel control service”We can build ourselves a service to control each wheel in a closed loop. It will sit above our Inventor HAT service. This service would always be listening, but not always active.
It will publish motors/wheels messages with power levels for the motor board.
It will listen to a number of topics:
sensors/encoders/data: The encoder messages with speed information.wheel_control/enabled: Whether this service is currently controlling the motors or not. The payload for this would betrue/false.wheel_control/wheel_speed_mm: The expected speed for each wheel. The payload is a JSON list of left speed and right speed.all/stop: Service will disable itself when this message is received.
Let’s build it. Start robot/wheel_control_service.py with imports:
import ujson as jsonimport timeimport numpy as np
from common.mqtt_behavior import connect, publish_jsonfrom common.pid_controller import PIDControllerfrom common.time_stepper import TimeStepperWe are importing a number of familiar items, but we’ve now added PIDController and TimeStepper to them. We can then start the service class:
class WheelControlService: def __init__(self): self.left_speed = 0 self.right_speed = 0 self.left_pid = PIDController(0.001, 0.001) self.right_pid = PIDController(0.001, 0.001) self.time_stepper = TimeStepper() self.enabled = FalseThe left_speed and right_speed members store the intended speeds. We expect those to change over time. We also have left and right instances of the PID controller.These PID controller constants are scaled for motor driving output (between -1 and 1), so need to be kept small. We are accounting for differences in the motors, and one will have an integral correction greater than the other. There are default values here, which we’ll tune later.
The next part of the code will be message handlers. We’ll start with those managing the state of the service:
def on_enabled(self, client, userdata, message): self.enabled = json.loads(message.payload) self.left_pid.reset() self.right_pid.reset()
def all_stop(self, client, userdata, message): self.enabled = False publish_json(client, "motors/wheels", [0, 0])
def on_wheel_speed_mm(self, client, userdata, message): self.left_speed, self.right_speed = json.loads(message.payload)These methods will handle enabling, disabling, and stopping the service. The on_wheel_speed_mm method sets the expected speed for each side.
Note that when we enable the service, the PIDs are reset. This is to ensure that the integral wouldn’t build up a large error while the system was turned off.
We now need to handle the encoders:
def on_encoders_data(self, client, userdata, message): encoder_data = json.loads(message.payload) left_encoder = encoder_data['left_mm_per_sec'] right_encoder = encoder_data['right_mm_per_sec'] time_difference = self.time_stepper.step() if not self.enabled: return # Get the error left_error = self.left_speed - left_encoder right_error = self.right_speed - right_encoder left_control = np.clip(self.left_pid.control(left_error, time_difference), -1, 1) right_control = np.clip(self.right_pid.control(right_error, time_difference), -1, 1) publish_json(client, "wheel_control/plot", { "left_error": left_error, "left_control": left_control, "right_error": right_error, "right_control": right_control, "time": time.time()})
publish_json(client, "motors/wheels", [left_control, right_control])The on_encoders_data method uses the mm_per_sec measurements from the encoders. It also gets a time difference and keeps the time stepper updated each time we get encoder data.
If the service is not enabled, we stop before making further calculations. Otherwise, we compare the encoder speed with the expected speed for each side. A subtraction is used to compare and get the error value.
We use the time_stepper to ensure that updates to the integral are scaled by the time, otherwise the integral term would depend on how fast the loop runs.
We then send each error value to each PID, which returns a control value as its output. This control value is clipped with np.clip to ensure that it stays within the safe bounds of +1 and - 1 for motor power settings.
We publish the state of this as a plot, for debugging, and send the control signal to the motors/wheels topic.
The start method for this class needs to connect all these topics:
def start(self): client = connect(start_loop=False) client.subscribe("sensors/encoders/data") client.message_callback_add("sensors/encoders/data", self.on_encoders_data) client.subscribe("wheel_control/#") client.message_callback_add("wheel_control/enabled", self.on_enabled) client.message_callback_add("wheel_control/wheel_speed_mm", self.on_wheel_speed_mm) client.subscribe("all/stop") client.message_callback_add("all/stop", self.all_stop)
client.loop_forever()
service = WheelControlService()service.start()This service also needs to be added to deploy/deploy_services.py:
code = files.put( name="Update wheel control code", src="robot/wheel_control_service.py", dest="robot/wheel_control_service.py")deploy_service("wheel_control_service", "robot/wheel_control_service.py", True, common.changed or code.changed)You could deploy this now, and use mosquitto pub to interact with it, but we can easily reroute our robot/drive_known_distance.py behavior to publish messages to the wheel_control topics instead of motors/wheels. First, update the drive_line method definition to a speed in mm_per_sec:
def drive_line(self, client, expected_distance=1000, speed=100):Now, we can change the topic we publish our speed to:
publish_json(client, "wheel_control/wheel_speed_mm", [current_speed, current_speed])The last thing we need is to enable wheel_control when this starts:
def start(self): client = connect() client.subscribe("sensors/encoders/data") client.publish("sensors/encoders/control/reset") publish_json(client, "wheel_control/enabled", True) client.message_callback_add("sensors/encoders/data", self.on_encoders_data) self.drive_line(client)We can now rerun deploy_service and try the drive_known distance again. I suggest reloading the web page before pressing S tart.
Troubleshooting
Section titled “Troubleshooting”If nothing is moving, try the following:
- Increase the proportional constant (
P) to0.1; this should make something happen. - If S tart doesn’t even produce a graph when the button is pressed, load the web inspector and see whether there are any console errors.
- Via SSH, run
journalctl ‑u wheel_control_service. Press S hift + G to see the last messages, which will show you if it broke somewhere. - If you see
OSError: [Errno 5] Input/output error, this can indicate that your battery needs charging, or is not able to output 3 A at 5 V. - Violent wobbling is expected at this point.
These PID values are likely to be wrong, though. The robot may be wobbling or moving too slowly. Let’s start tuning it.
PID tuning first attempt
Section titled “PID tuning first attempt”When you run this with P: 0.001 and I: 0.001, the result will be a gradual take-off. The wheels probably won’t be moving at the same rate at the same time. I recommend starting with low P and I constant values to prevent unexpected movement.
Let’s try to increase the P constant to 0.01 on both wheels and see what happens. You’ll need to make the highlighted update in robot/wheel_control_service.py:
self.left_pid = PIDController(0.010, 0.001)self.right_pid = PIDController(0.010, 0.001)Send this again with pyinfra. Then, you can press S tart again to see the result:

Figure 11.8 – Proportional motor control on distance vs. time
Figure 11.8 – Proportional motor control on distance vs. time
The preceding graph shows distance versus time for each wheel. It is clear that this is wobbling, and you probably heard that in the motors. While this graph helps with the distance, it doesn’t entirely help with visualizing the wheel motions. We’re already supplying plot data from wheel_control_service, so let’s add a chart for it.
Open robot_control/drive_known_distance.html, and under the plot, we can add another chart. Make the highlighted change in the line_chart div:
<div class="line_chart"> <canvas id="plot"></canvas> <canvas id="wheel_control"></canvas></div>We then also need to add it to the script section below:
const behavior_chart = create_timeseries_chart('plot', ['left_error', 'right_error']);const wheel_chart = create_timeseries_chart('wheel_control', ['left_error', 'right_error']);
mqttClient.subscribe('drive_known_distance/plot');mqttClient.subscribe('wheel_control/plot');mqttClient.on('message', (topic, message) => { switch (topic) { case 'drive_known_distance/plot': behavior_chart.update_data(JSON.parse(message)); break; case 'wheel_control/plot': wheel_chart.update_data(JSON.parse(message)); break; }});We’ve now added a second chart, showing the wheel control errors and behavior below the first chart. Let’s see a screenshot of the new chart after a deploy and rerun:

Figure 11.9 – Proportional closed control graph
Figure 11.9 – Proportional closed control graph
The preceding graph shows the left and right error values for our closed motor control, with a high proportional constant. Its oscillation is now painfully clear. It’s increasing each wheel to meet an expected speed, so the error hits or goes below zero, so it proportionally provides much less power, causing the motor to slow down too much again. Proportional operation alone won’t work here.
Let’s try seeing how this goes if we drop the proportional constant back down to 0.001, and increase the integral constant only to 0.010 in robot_wheel_service.py:
self.left_pid = PIDController(0.001, 0.010)self.right_pid = PIDController(0.001, 0.010)The graph here shows after that change and a rerun:

Figure 11.10 – Integral response
Figure 11.10 – Integral response
The preceding graph shows what we get with a higher integral constant. There’s a slower start for the motors, but the result is smooth, until the end, where it overshoots by a way before stopping. Sometimes, the combination of P and I constant tuning is needed so they can counteract each other. Let’s try putting both at 0.005 as a reasonable balance for both:

Figure 11.11 – Proportional and integral
Figure 11.11 – Proportional and integral
This graph shows that both are moving a bit faster than a high integral constant alone, but it’s still wobbling and still overshooting. Clearly, they are still too high, and more tuning will be needed. You may be finding the round trip of updating the values in the code, running pyinfra, reloading, and restarting tedious. Let’s make that faster so we can tune this better. We’re going to need somewhere to store constant settings.
Adding a configuration store
Section titled “Adding a configuration store”Adjusting the PID, or speed, and then redeploying the code is long-winded. Many behaviors have tunable parameters. Storing them as variables in the behaviors would mean the tuning is lost when the behaviors are stopped. We need somewhere to store parameters and a way to edit them in control pages.
Let’s build a configuration store. Python has a built-in tool, dbm, for storing persistent configuration, even keeping it when the robot is turned off. We can then make this data available over MQTT where it’s needed.
The store is a key/value store, where the key is the unique name of an item, which stores a value, the data.
The MQTT topics for this will be the following:
config/setwith a JSON payload of[key, value]will store or update the named key with the new value.config/getwill cause the store to publish all the values named by a JSON list payload,[key_1, key_n].config/updatemeans the store will publish the requested values on this topic. The payload is{key_1: value_1, key_n: value_n}.
Create the robot/config_store.py file and start with these imports:
import ujson as jsonimport dbm.dumbfrom common.mqtt_behavior import connect, publish_jsonThe dbm.dumb import lets us make the simplest store. Let’s build a class to drive this:
class RobotConfigStore: def __init__(self): self.db = dbm.dumb.open("robot_config.db", 'c')This code also opens or creates a data store file if one doesn’t exist already. The resulting data store is put into self.db. We now need a handler that lets us set variables:
def on_set(self, client, userdata, message): key, value = json.loads(message.payload) print(f"Setting {key} to {value}") self.db[key] = json.dumps(value) self.db.sync() publish_json(client, "config/updated", {key: value})This handles the config/set topic. It loads the JSON payload and sets the value in the database for each key. The dbm database behaves like a Python dictionary here. We call self.db.sync() to ensure that the data is written to the SD card as well.
The on_set function then publishes an update message with the new values. However, since the behavior may start later, we also need to handle the config/get topic:
def on_get(self, client, userdata, message): data = json.loads(message.payload) response = {key: json.loads(self.db[key]) for key in data if key in self.db} publish_json(client, "config/updated", response)The on_get handler processes the payload through a loop to fetch each item from the database and store it in a dictionary. This is then published as JSON to config/update.
Now, we need to connect this up to MQTT and start it:
def start(self): client = connect(start_loop=False) client.subscribe("config/set") client.message_callback_add("config/set", self.on_set) client.subscribe("config/get") client.message_callback_add("config/get", self.on_get) client.loop_forever()
config_store = RobotConfigStore()config_store.start()We’ll need this to run when the robot starts, so it needs an entry in deploy/deploy_services.py with auto start set to true in the following:
code = files.put( name="Update config store code", src="robot/config_store.py", dest="robot/config_store.py")deploy_service("config_store", "robot/config_store.py", True, common.changed or code.changed)Use pyinfra to deploy services. We have a data storage service. Let’s test this before we continue. Let’s set a preliminary P value with the following command via SSH:
mosquitto_pub -u robot -P robot -t config/set -m '["wheel_control/proportional", 0.001]'We can now fetch the value with the highlighted command line:
mosquitto_sub -u robot -P robot -t config/updated -C 1 & mosquitto_pub -u robot -P robot -t config/get -m '["wheel_control/proportional"]'; fgYou should see output similar to the following:
[1] 13828mosquitto_sub -u robot -P robot -t config/updated -C 1{"wheel_control\/proportional":0.001}What we’ve done here is subscribed to the config/updated topic, accepting at least one message. The ‑C 1 flag (uppercase) tells it to stop after one message. We then use & to put that command in the background, and publish config/get, telling the config service to send an update for the named field.
We then use a semicolon (;) character to chain the command, fg, which makes the last background task a foreground task again. The result is that it waits for a message, asks for the update, then prints the message and quits.
This config store is persistent; you should be able to switch the robot off, then try fetching the data again and get the last value you updated it with.
Let’s make sure it works.
Troubleshooting the MQTT config store
Section titled “Troubleshooting the MQTT config store”If you have trouble with this, try these tools to debug it:
- If you see errors with the command, double-check the SSH command and try again. All options are case-sensitive.
- Use
journalctl ‑u config_storeto see any Python problems. - Adding
printstatements to theconfig_store.pycode can help see what it is storing or publishing.
Using the config store in a behavior
Section titled “Using the config store in a behavior”Now that we have built a place to store config, we’ll extend behaviors to use this. Start by adding this to robot/common/pid_controller.py:
def handle_config_messages(self, data, prefix): if prefix + '/proportional' in data: self.proportional_constant = data[prefix + '/proportional'] if prefix + '/integral' in data: self.integral_constant = data[prefix + '/integral'] self.integral = 0Our data store will store keys in a prefix/item form – for example, wheel_control/proportional. Since the PID controller may be used in a few contexts, it can extract data using a different prefix for each usage.
Let’s put that into robot/wheel_control_service.py:
def on_config_updated(self, client, userdata, message): data = json.loads(message.payload) self.left_pid.handle_config_messages(data, 'wheel_control') self.right_pid.handle_config_messages(data, 'wheel_control')This decodes a JSON payload for the config/updated topic and sends the loaded config to each PID with a wheel_control prefix. It doesn’t make sense to configure them individually for left and right, as the same parameters should work for both.
Now, in the robot/wheel_control_service.py start method, add the following:
client.subscribe("config/updated")client.message_callback_add("config/updated", self.on_config_updated)publish_json(client, "config/get", [ "wheel_control/proportional", "wheel_control/integral"])This connects the on_config_update handler to MQTT and then publishes a config/get message, so the config store can send any configuration as soon as possible.
You can now deploy this with pyinfra. Now, you can try changing the proportional and restarting without a code deploy. Try the following command via SSH:
$ mosquitto_pub -u robot -P robot -t config/set -m '["wheel_control/proportional", 0.010]'This message will update the proportional constant to a relatively high value. If you press S tart on the line following, you should see the wobbly graph again. You can try a few values here. Let’s make sure this works so far.
Troubleshooting wheel control with the config store
Section titled “Troubleshooting wheel control with the config store”This system is complex, but there are tools to debug it:
- Use
journalctl ‑u wheel_controlto see any Python problems. - Remember, this is communicating on MQTT topics. You can subscribe to them with
mosquitto_sub ‑u robot ‑P robot ‑t 'config/#' ‑v. You can see whether messages are being sent both to set the configuration and update it. - Adding
printstatements to theconfig_store.pycode can help see what it is storing or publishing.
You should be able to use Mosquitto to send messages, but we can do even better and put them right on the web page.
Putting config controls on the web pages
Section titled “Putting config controls on the web pages”With a config store system, our web pages can use MQTT to set things in them. We’ll make ourselves a JavaScript library to talk to our store, and then add the controls to the drive_known_distance example. Create the robot_control/config_store.js file and start it with the following:
export function config_store_client(mqtt_client) { const keys = {}; mqtt_client.subscribe('config/updated'); mqtt_client.on('message', (topic, message) => { if (topic === 'config/updated') { const data = JSON.parse(message.toString()); for (const key in data) { if (keys[key] !== undefined) { keys[key].value = data[key].toString(); } } } });This code exports a JS function that creates a client interface to the config store. The variable keys associate controls with config keys.
The code then subscribes and handles config/updated messages. We decode the message, and for each key in it, update a value item if it exists in our key list. Web input controls usually have a value member for their data, so we can assume that here. Note that we can have multiple on-message events attached to the MQTT client.
We will be returning a structure with functions to control this client:
return { add_input: (key, label, container_id, starting_value) => { const container = document.getElementById(container_id); const label_element = document.createElement('label'); label_element.textContent = label; container.appendChild(label_element); const input = document.createElement('input'); input.type = 'text'; input.value = starting_value.toString(); input.onblur = () => { const value = parseFloat(input.value); mqtt_client.publish('config/set', JSON.stringify([key, value])); }; container.appendChild(input); keys[key] = input; },We start the return here, with an add_input function, which adds input controls. It has three parameters:
key: The name of the config key this input will updatelabel: A text label for the controlContainer_id: An identifier for the HTML element to build this control instarting_value: An initial number to use before it has a config
The code for add_input starts by finding the container element. It adds a label, with the expected text in it, then creates the input control element. The appendChild function lets our code add HTML elements to the page.
The next part builds an HTML input, a text box, with our starting value in it. For the input element, there is an onblur event handler, which is called when focus leaves an input control (you click somewhere else). This means it will only send whole values, not at every character you type.
The code will then convert the input value into a floating point number, then publish a config/set message with the new value. After adding the control into the container, we add the control to the store of keys in config_store_client.
When we load a page, there may already have been config settings, so we need to prompt an update:
start: () => { mqtt_client.publish('config/get', JSON.stringify(Object.keys(keys))); } }}This start method will publish config/get with all the configured keys. So, to use this, you’d add all the inputs, then call start. This code finishes the config_store_client function and robot_control/config_store.js file.
We can now make use of this in robot_control/drive_known_distance.html. In the HTML section, add the highlighted line:
<button id="start">Start</button><button id="stop">Stop</button><div id="config"></div><div class="line_chart">This creates the container. We then need to add the JS import for it:
import 'https://cdn.jsdelivr.net/npm/chart.js';import { connect, publish_when_clicked } from './mqtt_client.js';import { create_timeseries_chart } from './chart_helper.js';import { config_store_client } from './config_store.js';let mqttClient = connect();We can now create an instance of our client and populate it with controls. Add this code anywhere after the mqttClient connect:
const config_store = config_store_client(mqttClient);config_store.add_input('wheel_control/proportional', 'wheel proportional', 'config', 0.004);config_store.add_input('wheel_control/integral', 'wheel integral', 'config', 0.008);config_store.start()The first line creates a config store client, linked to the MQTT client. We then link each control to a config store parameter with a starting value. Although it took some preparation code, using this in HTML pages will now be fairly easy.
The web page for our config is ready to use. Let’s try it. Run the Pyinfra deploy_service tool to put it on the robot and fully refresh (Ctrl/ Cmd + Shift + R) the page. It should look like the following screenshot:

Figure 11.12 – Distance drive page
The page now has a title, S tart and S top buttons, inputs for the PID constants, and graphs for both the distance and the wheel speed error. Changes to the page should affect the PID parameters of the behavior. Also, when going to the menu and back to this page, these parameters should be preserved. Note that you’ll see initial values until the update.
You now have tools to really tune the PID parameters.
Troubleshooting the config system
Section titled “Troubleshooting the config system”If you run into trouble with this web interface, try these tools to debug it:
- In the browser, use the Right Click -> Inspect tool to bring up the developer tools, and use the console to see any errors in the JavaScript.
- As in the previous example, you can use
journalctlandmosquitto_subto look at the config service and MQTT messages.
You now have a convenient way to tune behavior parameters. When you load this page again, even after powering off the robot, these values are preserved.
PID tuning take 2
Section titled “PID tuning take 2”We can now try different PID values by updating them and pressing P lay. Our current system is primarily integral-driven.
The lower wheel speed error graph will settle with higher integral constant values. I recommend increasing by about 10% and stopping if the system becomes unstable with overshoots. High integral constant values can make the system keep over-reacting to errors that are no longer present and overshoot.
Increasing proportional constant values here can help for a quicker take off, but add a lot of instability, as it takes a continuous control signal to the motors for them to drive smoothly. However, without the proportional, the integral will definitely overshoot. Therefore, start with a value at about 0.001, and see whether that makes for a smooth, quick takeoff. High proportional makes the system more susceptible to noise – overreacting to small sensor variances with big wobbles.
Remember how different PID responses are between the floor and on the desk. The rolling resistance of pulling the robot on the floor introduces a damping effect in the system. Therefore, while some tuning can be done on the desk, you may need more fine-tuning on the floor.
I found on my floor, settings of P: 0.001 and I: 0.01 worked. You will need to play with these values until you get a balance you are happy with.
We can further use PID control to improve our distance behavior. Currently, it can overshoot the distance a little, in my case, about 3 to 5 cm. We can make this far tighter.
Using PID control to stop closer
Section titled “Using PID control to stop closer”We are going to improve our known distance driving behavior in two ways now. We can closed-loop control the motors to keep the robot straight, but we can also make it stop far closer to the intended distance. Let’s use the PID again.
We will make our drive_known_distance function drive until it is within some threshold of the endpoint, then switch to PID to hit the end position. This modified behavior will then have a few configuration keys:
- PID control values for
drive_known_distance drive_known_distance/speedto control how fast it tries to drivedrive_known_distance/stopping_distancewhen it switches to PID braking
We need to start with importing the PID controller tools into robot/drive_known_distance.py:
from common.pid_controller import PIDControllerfrom common.time_stepper import TimeStepperIn the __init__ behavior, we need to set up the PID and the configurable parameters:
def __init__(self): self.left_distance = 0 self.right_distance = 0 self.distance_pid = PIDController(0.2, 0.01) self.speed = 180 self.stop_distance = 100The PID is used when braking, to slow the motors down and stop right on the set point.
We then need to overhaul the drive_line method. The start of the loop looks the same, apart from the fact that we now keep the time stepper moving:
def drive_line(self, client, expected_distance=1000): distance_reached = False time_stepper = TimeStepper() while not distance_reached: # Sense left_error = expected_distance - self.left_distance right_error = expected_distance - self.right_distance time_difference = time_stepper.step()The Think section looks a bit different. We still find the furthest distance:
# Thinkif abs(left_error) > abs(right_error): distance_error = left_errorelse: distance_error = right_errorif distance_error > self.stopping_distance: current_speed = self.speedAfter finding the greatest distance error, we check to see whether we are within the stopping distance; if not, we go at the speed configuration:
elif abs(distance_error) < 1: distance_reached = True current_speed = 0However, if we are within 1 mm of the target, we will stop completely. But what about the gap between the stopping distance and the target?
else: current_speed = self.distance_pid.control(distance_error, time_difference)For this stopping region, we feed the distance error to distance_pid, along with the time difference. The output of this PID is the motor speed in mm per second.
The Act section looks the same:
# Actpublish_json(client, "drive_known_distance/plot", { "left_error": left_error, "right_error": right_error, "time": time.time()})publish_json(client, "wheel_control/wheel_speed_mm", [current_speed, current_speed])time.sleep(0.1)With the drive_line method now updated, we also need to add an MQTT handler for configuration updates:
def on_config_updated(self, client, userdata, message): data = json.loads(message.payload) self.distance_pid.handle_config_messages(data, 'drive_known_distance') if 'drive_known_distance/speed' in data: self.speed = data['drive_known_distance/speed'] if 'drive_known_distance/stopping_distance' in data: self.stopping_distance = data['drive_known_distance/stopping_distance']This loads the payload. It delegates PID settings to handle_config_messages there, and then checks to see whether speed and stopping_distance settings are in the update.
We now need to update the start method to subscribe to config updates, and cause one for all of this class’s configuration:
def start(self): client = connect() client.subscribe("sensors/encoders/data") client.publish("sensors/encoders/control/reset") publish_json(client, "wheel_control/enabled", True) client.message_callback_add("sensors/encoders/data", self.on_encoders_data) client.subscribe("config/updated") client.message_callback_add("config/updated", self.on_config_updated) publish_json(client, "config/get", [ "drive_known_distance/proportional", "drive_known_distance/integral", "drive_known_distance/speed", "drive_known_distance/stopping_distance"]) self.drive_line(client)This is now going to run and end. The final change is to robot_control/drive_known_distance.html, where we must add inputs for these. Make the highlighted change to the corresponding code section:
const config_store = config_store_client(mqttClient);config_store.add_input('drive_known_distance/proportional', 'distance proportional', 'config', 0.2);config_store.add_input('drive_known_distance/integral', 'distance integral', 'config', 0.01);config_store.add_input('drive_known_distance/speed', 'speed', 'config', 180);config_store.add_input('drive_known_distance/stopping_distance', 'stopping distance', 'config', 100);config_store.add_input('wheel_control/proportional', 'wheel proportional', 'config', 0.004);config_store.add_input('wheel_control/integral', 'wheel integral', 'config', 0.008);config_store.start()For any configurable parameter, you need the following:
- A member variable to store state in the behavior (or a common subsystem like the PID controller)
- An MQTT handler to update that state on the update messages, subscribed to
config/updated - A
config/getmessage to fetch the current state - An input control on the web page to configure it from
Let’s send this to the robot and test it. You can tune the motor closed loop, along with the distance PID parameters, here. The current default PID values are ones that worked for me, but again, you may need to tune this. In this system, proportional is much higher as there’s no constant offset.
If the robot is creeping to a stop after the stopping distance, try a higher proportional first, and set the integral to around one-tenth of that proportional. I got stable results with settings as high as P:1.0 and I:0.1 for the stopping PID. You are aiming for a balance where the robot stops pretty quickly on target, but doesn’t overshoot or undershoot.
Increasing the speed will mean tuning that stopping PID, and you may find a speed where the motor control becomes unstable, potentially because you are hitting the upper limit on one of the motors.
The robot can now drive a specific distance while in a straight line. You’ve combined the measuring and PID adjustment tools that you’ve built throughout this chapter. But what if we want to make turns and measure those? We’ll cover this in the next section.
Making a specific turn
Section titled “Making a specific turn”The next task we can use our encoders for is to make a specific turn. When turning a robot, each wheel is going through an arc:

Figure 11.13 – Illustrating wheel movement when turning through an arc
The inner wheel drives a shorter distance than the outer wheel, causing the robot to turn. We must control these distances and the ratio between them to make an exact turn. The next figure shows how the wheels and the turn relate to each other:

Figure 11.14 – Relating wheels to a turn radius
Figure 11.14 – Relating wheels to a turn radius
The figure on the left shows how we’ll use robot measurements to calculate a turn. Modeling robotics motions like this is known as kinematics. The R obot origin represents the middle point between the driving wheels.
The robot wheels will make contact with the floor at the W heel middle. Our calculations are based on these three points. We can measure the wheel distance by adding the thickness of a wheel to the distance between the wheel inners. In my case, I get 26 + 133 mm – approximately 159 mm. You should measure your robot.
Let’s store this in the config store for later reference, using SSH on the robot:
mosquitto_pub -u robot -P robot -t config/set -m '["robot/wheel_distance", 159]'This value is now usable in the calculations in the figure. The turn radius is relative to the robot origin. We are calculating arcs for the wheels to turn from. We are going to say that a negative radius is left of the origin, and a positive radius is to the right, and that a positive angle curves to the right of the robot, clockwise.
Therefore, the left wheel’s turn radius is the difference between the turn radius and half the distance between the wheels:
left_turn_radius = turn_radius - (wheel_distance / 2)The right radius is the turn radius plus half the distance:
right_turn_radius = turn_radius + (wheel_distance / 2)We express the angle in radians. We multiply this angle by each radius to get the distances that each wheel needs to move through:
left_turn_distance = angle * left_turn_radiusright_turn_distance = angle * right_turn_radiusWe’re going to break this down into a function that calculates this and a function that ensures each wheel has driven to that distance.
Let’s turn these calculations into code, demonstrating it by attempting to drive in a square, making measured 90-degree turns:
- We will rebuild our path driving behavior. Copy the code from
robot/drive_known_distance.pyand replace the code inrobot/behavior_path.pywith it. - In
robot/behavior_path.py, rename theDriveKnownDistanceBehaviorclass toBehaviorPath. Don’t forget to do this at the end, too. - In the
initfunction, add these further members:The wheel distance will come from the config store for our calculations, and we’ll now wait for the configuration to be ready when the behavior starts.self.wheel_distance = 0self.config_ready = False - We will add a method to calculate the
curveparameters calleddrive_curve:This converts an angle to radians. We then calculate the turn radius for each wheel based on the wheel distance. The wheel turn radius is multiplied by the angle to determine the distance each wheel must drive. Let’s add a bit of debug:def drive_curve(self, client, angle_in_degrees, turn_radius):angle_in_radians = math.radians(angle_in_degrees)# Calculate the radius for each wheelleft_turn_radius = turn_radius - (self.wheel_distance / 2)right_turn_radius = turn_radius + (self.wheel_distance / 2)# Calculate the distance for each wheelleft_turn_distance = angle_in_radians * left_turn_radiusright_turn_distance = angle_in_radians * right_turn_radiusWe can see that with an MQTT sub. However, we now want to take these calculations per curve and feed them to a method to drive each wheel by the intended distance:publish_json(client, "path/curve", {"angle_in_radians": angle_in_radians,"left_turn_radius": left_turn_radius, "right_turn_radius": right_turn_radius,"left_turn_distance": left_turn_distance, "right_turn_distance": right_turn_distance,})self.drive_wheels_to_distance(client, left_turn_distance, right_turn_distance) - We now need to build this
drive_wheels_to_distancemethod. Each wheel will need to turn at a different speed, relative to their target distance. One wheel will always need to turn further, so we’ll call that the primary:Thedef drive_wheels_to_distance(self, client, left_target, right_target):left_is_primary = abs(left_target) > abs(right_target)speed_factor = 1 / max(abs(left_target), abs(right_target))left_factor = left_target * speed_factorright_factor = right_target * speed_factorspeed_factorrepresents how much to scale the wheel speeds, based on the maximum target distance. A bit of debug here will help:publish_json(client, "path/speed_factors", {"left_factor": left_factor, "right_factor": right_factor ,"left_is_primary": left_is_primary}) - We then prepare the PID, time stepper, and encoders, then start the wheels:
There’s aclient.publish("sensors/encoders/control/reset")while self.left_distance !=0 or self.right_distance != 0:time.sleep(0.01)time_stepper = TimeStepper()self.distance_pid.reset()publish_json(client, "wheel_control/enabled", True)
while/sleepafter resetting the encoders; this is to allow the reset to happen and the asynchronous distance updates to report 0 for each side. Old encoder data can cause this to skip driving. - We start a loop with a
Sensesection:The primary side is used to calculate an error, to measure how much more driving is needed to finish the movement. We also update the time difference.distance_reached = Falsewhile not distance_reached:# Senseif left_is_primary:error = left_target - self.left_distanceelse:error = right_target - self.right_distancetime_difference = time_stepper.step() - In the
Thinksection, we use the error to find a speed. This has similar stopping distance logic to the straight line:Note that this is giving a single current speed, though. Part of the thinking is to apply this to each side with the correct factor:# Thinkif error > self.stopping_distance:current_speed = self.speedelif abs(error) < 1:distance_reached = Truecurrent_speed = 0else:current_speed = self.distance_pid.control(error, time_difference)left_speed = current_speed * left_factorright_speed = current_speed * right_factor - We can now publish a plot and drive the motors in the
Actsection:# Actpublish_json(client, "path/plot", {"error": error, "time": time.time()})publish_json(client, "wheel_control/wheel_speed_mm", [left_speed, right_speed])time.sleep(0.1) - Driving a straight line is a special case of this
drive_wheels_to_distancemethod, so we can now simplify thedrive_linemethod:This case just uses the expected distance for both sides.def drive_line(self, client, expected_distance=1000):self.drive_wheels_to_distance(client, expected_distance, expected_distance) - We need to set up the configuration method for our additional configuration settings. These are just mapping configs to members of our class:
Note there’s also adef on_config_updated(self, client, userdata, message):self.config_ready = Truedata = json.loads(message.payload)self.distance_pid.handle_config_messages(data, 'path')if 'path/speed' in data:self.speed = data['path/speed']if 'path/stopping_distance' in data:self.stopping_distance = data['path/stopping_distance']if 'robot/wheel_distance' in data:self.wheel_distance = data['robot/wheel_distance']
config_readyflag we set totruehere. This allows the behavior to wait until it’s fetched the config. - In the
startmethod, we need to update theconfig/getline to account for all of those config settings:publish_json(client, "config/get", ["path/proportional","path/integral","path/speed","path/stopping_distance","robot/wheel_distance",]) - We are also now going to wait for the configuration to be ready:
while not self.config_ready:time.sleep(0.1)
- Let’s initially drive a single curve for the first test:
self.drive_curve(client, 90, 30)
We need to modify the behavior_path.html page to interact with this:
- Copy the
robot_control/drive_known_distance.htmlcontent over therobot/behavior_path.htmlweb page. - Modify the title to
Drive square path. - Find
launcher start/stopand modify them to launchbehavior_path:publish_when_clicked(mqttClient, "start", "launcher/start", "behavior_path");publish_when_clicked(mqttClient, "stop", "launcher/stop", "behavior_path"); - We also want to have the full set of configuration inputs. Replace the existing ones with the following:
const config_store = config_store_client(mqttClient);config_store.add_input('path/proportional', 'distance proportional', 'config', 1);config_store.add_input('path/integral', 'distance integral', 'config', 0.1);config_store.add_input('path/speed', 'speed', 'config', 180);config_store.add_input('path/stopping_distance', 'stopping distance', 'config', 100);config_store.add_input('wheel_control/proportional', 'wheel proportional', 'config', 0.004);config_store.add_input('wheel_control/integral', 'wheel integral', 'config', 0.008);config_store.start()
- The plot sources will change:
mqttClient.subscribe('path/plot');mqttClient.subscribe('wheel_control/plot');mqttClient.on('message', (topic, message) => {switch (topic) {case 'path/plot':behavior_chart.update_data(JSON.parse(message));break;case 'wheel_control/plot':wheel_chart.update_data(JSON.parse(message));break;}});
The HTML and code are now ready for an initial test. Because we’ve replaced the old behavior_path, it’s already set up in the deploy_service and menu system, so you can now deploy it with pyinfra.
Load the menu, and with the robot on the floor, press S tart. This uses the same distance PID as before, and the same wheel control PID as before, so see the previous Adjusting the PID take 2 section for notes on adjusting this.
The robot should now turn pretty close to 90 degrees; it may overshoot and then pull back a little. Let’s ensure that this works.
Troubleshooting driving a curve
Section titled “Troubleshooting driving a curve”You can simplify to calling drive_line only first, and ensure that it still works before debugging the driving curve. However, if you run into trouble, try these:
- Ensure that all previous examples have worked.
- If there is wobbling or it slows down and creeps to the target, you may need to tune the PID.
- If it fails to do anything, use
journalctlandmosquitto_subto inspect the services and MQTT messages to pinpoint any code issues. - If it stops short without slowing, it may have crashed before going into the PID. Verify this with
journalctl. - If your measurement of the size of the width between the wheels is too small, it will turn too far; if it’s too large, it will not turn far enough. A more accurate measurement will lead to more accurate curves.
- If config key names don’t match in the
get,update, andsetareas, they will have defaults. For example,robot/wheel_distancehas a default of0, so you will get a small movement. - If the robot is slipping or the floor is uneven, it may also have trouble making the right turn. Encoders account for how much the wheel has turned, not how much ground the wheel covered doing so.
You can now try different curve radius settings and see how the robot moves.
When you have a feel for this and have debugged it, you can turn it into a path, like a square. Open robot/behavior_path.py, and alter the end of the start method:
while not self.config_ready: time.sleep(0.1)
for n in range(4): self.drive_line(client, 300) self.drive_curve(client, 90, 30)This will loop over driving forward and making a 90-degree turn.
Your robot can now drive in straight lines and make precise turns. It accounts for motor speeds, wheel sizes, and the geometry of the robot. Let’s see what we’ve learned.
Summary
Section titled “Summary”In this chapter, we used encoder sensors on our robot to determine how far each wheel has turned. We programmed the robot to stop at target distances, then combined encoders with a PID controller to correct the robot’s path. We then took the calculations further to calculate driving through a curve in terms of wheel movements.
You’ve seen PID controllers react to a difference between a sensor measurement and expectation by generating a control signal.
We also explored storing configuration so robot settings can be adjusted from our browser or phone.
In the next chapter, we are going to do even more with our encoders. We are going to see how a robot can guess its position in a space from these encoders!
Exercises
Section titled “Exercises”- The curved behavior can use many different radius values. Try different curves, and see how the robot moves.
- Try chaining curves other than 90 degrees together with straight lines, to make shapes other than squares. Triangles, pentagons, circles, and S shapes are possible. A figure of 8 is too if you are really ambitious.
- Try the robot on a different surface, and see how the PID tuning will need to change for either the wheel control or driving.
- For the PID behaviors, tune the PIDs, try high values for the proportional or the integral, and observe how this makes the robot behave.
- The wheel controller could do with a timeout like the one used in the Inventor HAT service. Could you adapt that code so it won’t drive off?
Further reading
Section titled “Further reading”Please refer to the following for more information:
- You can see more information about the encoder library at https://github.com/pimoroni/ioe-python/blob/main/docs/encoder.md. This shows what further functions are available.
- PID control is a deep subject. It is a key area in self-balancing robots, drones, and other autonomous control systems. Here is a great video series so that you can explore these further on YouTube: Brian Douglas – PID Control – A brief introduction: https://www.youtube.com/watch?v=UR0hOmjaHp0.
- An in-depth article on turning precise corners with PID control shows how this was used for a competition-winning LEGO ® Mindstorms robot: GW Lucas – Using a PID-based Technique For Competitive Odometry and Dead-Reckoning: http://www.seattlerobotics.org/encoder/200108/using_a_pid.html.