Skip to content
ImagineWorld

IMU-Based Robot Navigation with Python

node_idnode-book_learn-robotics-programming_chapter-13-imu-based-robot-navigation-with-python
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num13
chapter_titleIMU-Based Robot Navigation with Python
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 13 — IMU-Based Robot Navigation with Python

Section titled “Chapter 13 — IMU-Based Robot Navigation with Python”

In Chapter 12*,* Encoder-Based Localisation with Python, we saw how the encoder can provide information about how the robot has moved. However, as you also saw with pose movement, encoders can be fooled by wheels slipping and provide only relative movement information. Encoders can quickly grow asymmetric errors and produce curved paths that the robot did not really take. If we want to know the absolute orientation or provide another way to improve our orientation information, we need a compass. Like a compass, magnetic interference can affect heading accuracy, especially indoors.

An i nertial m easurement u nit (IMU) provides a group of sensors we can use to estimate the robot’s absolute orientation, or orientation relative to a starting point. The IMU can also be used to determine the orientation’s rate of change.

This chapter introduces the IMU, shows you how to add it to your robot, make the data available and use it in behaviors.

By the end of the chapter, you’ll see how a robot can estimate its orientation with respect to an absolute direction such as cardinal North.

We’ll also see how to visualize the information from this sensor in our dashboards.

In this chapter, you will learn about the following topics:

  • Learning about the inertial measurement unit
  • Connecting an IMU to a Raspberry Pi robot
  • Reading the Euler vector with MQTT
  • Driving a robot from IMU data and PID

Let’s get started!

Before we get started, make sure you have the following parts:

  • The robot and code from Chapter 12*,* Encoder-Based Localisation with Python
  • Your test area, preferably far from very strong magnets
  • A computer with a recent browser (Chrome, Firefox, Safari, Edge)
  • Any compass (your phone may have a compass app)

The following items should come from the parts list in Appendix A*:* Shopping for Robot Parts:

  • A BNO055 unit, preferably the Adafruit ADA4646 (see Appendix A*: Shopping for* Robot Parts)
  • JST PH 4-pin to male header cable – I2C STEMMA Cable – 200 mm – Pi Hut 104250
  • 6 x 20 mm M2.5 nylon standoffs
  • 2 x M2.5 nylon screws
  • 2 x M2.5 nylon nuts

You will require the following tools from the shopping list:

  • Screwdriver set
  • Long, flat needle-nose pliers

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.

Learning about the inertial measurement unit

Section titled “Learning about the inertial measurement unit”

IMUs are found in drones and rover floor robots, and are critical for self-balancing robots. An IMU combines sensors to get a reading on a robot’s absolute orientation in 3D space. The sensor data is either combined in software on the robot or by a processor onboard the IMU module.

IMU modules are tiny but have their roots in flight hardware that uses large spinning gyroscopes. IMUs use micro-electro-mechanical systems, commonly known as MEMS technology. MEMS put mechanical devices on micro-scale chips with moving parts. Inertial measurement units detect the relative motion of tiny parts inside them.

The direct measurements may be analog (see Chapter 2, Exploring Robot Building Blocks – Code a nd Electronics). IMU modules often include an analog-to-digital converter and communicate over a bus such as I2C or SPI.

The different sensor combinations on an IMU often include the following:

  • A temperature sensor, to account for temperature effects on other sensors
  • A gyroscope, which measures rates of rotation, but cannot measure absolute rotation and will drift over time if used alone
  • An accelerometer, which measures acceleration (including gravity) and indicates which way is up, but cannot detect yaw
  • A magnetometer, which measures magnetic fields and can act as a compass, but can generate a lot of noise and is sensitive to tilting

Each sensor can contribute to a full heading, with the gyroscope detecting quick turns, the accelerometer detecting the up/down axis, and the magnetometer detecting absolute rotation, subject to magnetic interference. As we work with each of these sensor types, we will learn more about them.

Now that we know a little about IMUs, let’s learn about why we’ve chosen the BNO055.

You can construct an IMU from a separate accelerometer, gyroscope, and magnetometer, along with devices to convert the output of the sensor. However, to reduce the wiring and complexity of this, a single module combining them is helpful. On some modules, there are three or four separate chips; however, they also come as a single chip. The BNO055 module we’ve suggested is a single chip, with some support devices on a small module.

IMU systems use degrees-of-freedom (DOF) to denote how many sensor axes are present. A 9-DOF system has 3 rotation axes (X, Y, and Z) multiplied by three sensors. Sometimes, you will see 10-DOF due to the addition of a temperature sensor.

The BNO055 is easier to code for than the ICM or MPU sensors, because the BNO055 performs complex calculations on board. The ICM/MPU sensors can do this, but software supporting this is not available for the Raspberry Pi from Python at the time of writing. The BNO055 sensors have historically had problems sharing an I2C bus, and all IMUs can produce a lot of data. We will put the IMU on a different I2C bus to mitigate both these issues.

The support in terms of documentation and libraries for controlling the device from Python is also an important factor. The MPU/ICM sensors have some deficits in this area, which leads to choosing the BNO055. The BNO055 is arguably more prone to small precision issues; however, their impact on our design is negligible.

Let’s take a closer look at this BNO055 device.

A closer look is shown in the following diagram:

Figure 13.1 – Close-up of the BNO055 module

Figure 13.1 – Close-up of the BNO055 module

Figure 13.1 – Close-up of the BNO055 module

The preceding diagram shows the recommended IMU module from Adafruit. Notable features are annotated:

  • Mounting holes: The board has convenient mounting holes. We will use two of these to attach it firmly to our robot.
  • Pose axis indicator: This shows the X, Y, and Z axes of this IMU. We can align the X axis with the front of the robot, with the Y axis pointing left, and the Z axis pointing up. This aligns with the poses we used in the previous chapter.
  • Power indicator: When debugging, it is good to know the sensors are receiving power.
  • Solderable connectors: We aren’t using them in the current robot, but they make this BNO055 breakout usable in other projects.
  • QW/ST I2C c onnectors: Between a number of vendors, the QWIIC and STEMMA series have standardized the layout and connector size for I2C connectors, with commonly available cables. This means we don’t need to solder this device.

The large chip in the middle is the BNO055 chip, but it has a lot of supporting circuits.

The right view shows a detailed view of the chip with its orientation, and a 3D view below. The white dot can be used to orient the chip if your board is different. The long edge to the right of the white dot is the Y axis pointing up, with the short edge above the dot being the X axis. Looking at the 3D view, the Z axis points up from the surface with the white dot.

Let’s see how we connect this multiple sensor module to our Raspberry Pi robot!

We’ll explore how to attach this IMU module to our robot, first physically and electrically. We will then get the software set up enough so that we have connected Python to the temperature sensor.

We need to securely mount the device on the robot. We must ensure it is facing the correct orientation. The IMU has a magnetometer module, which is sensitive to magnetic fields. The motors and encoders on our robot have magnetic fields that we’ll want to keep the device away from. Ensure the robot is powered off before starting this section.

The orientation of the IMU is essential for the experiments with it to make sense, and it should align with the poses seen in Chapter 12, Encoder- B ased Localisation with Python. Let’s see this in a diagram:

Figure 13.2 – Robot orientation

Figure 13.2 – Robot orientation

Figure 13.2 – Robot orientation

The preceding diagram shows the orientation of the X, Y, and Z axes on the robot, following the ENU convention mentioned in Chapter 12, Encoder- B ased Localisation with Python.

In ENU, 0 radians corresponds to East, increasing counterclockwise toward North.

The X axis should face forward, while the Z axis should face up. Finally, the Y axis should point left. Aligning the axes ensures that our IMU will give usable, consistent readings.

The following figure shows how we will mount the part on the robot:

Figure 13.3 – Attaching the IMU

Figure 13.3 – Attaching the IMU

Figure 13.3 – Attaching the IMU

The preceding diagram has numbered panels showing how we will physically attach this to the robot. Follow these numbered steps:

  1. Check the parts. Ensure you have 6 x 20 mm M2.5 standoffs, 2 M2.5 screws, 2 M2.5 nuts, and the IMU module.
  2. Identify the two holes you will use – the arrows show the two holes. There’s an axes indicator in this panel to show that X will face the front of the robot.
  3. Bolt a standoff into each hole using a nut underneath – you’ll need the long flat pliers to hold the nut in place under the holes.
  4. Extend the standoffs so there are 3 sets of 20 mm standoffs on each column. This is to give sufficient space between the IMU and the magnetic interference from motors and encoders.
  5. Use the nylon screws to bolt the IMU on top, ensuring that the X axis faces the front of the robot.
  6. Your attached IMU should look like the example shown.

We’ve now attached the IMU to the robot. You’ve lined up its axes so you know what to expect from our sensors. The module is now ready for wiring.

Although there are many addresses left on bus 1, the BNO and VL53L5CX tend to compete for bus bandwidth and should be kept apart. The BNO055 also does some interesting I2C clock stretching tricks that interfere with other sensors and need the Pi’s software i2c support. For this reason, we are isolating this sensor on a custom I2C bus numbered 2.

Because this module needs to be wired into a different I2C bus, we will be wiring into the top of the Inventor HAT Mini to reach the pins for that. We will be using the holes above to plug wire connectors into.

The following diagram shows how:

Figure 13.4 – Wiring the IMU to the Raspberry Pi

Figure 13.4 – Wiring the IMU to the Raspberry Pi

Figure 13.4 – Wiring the IMU to the Raspberry Pi

The preceding diagram shows how we wire the IMU to the custom software I2C bus 2 (I2C2) connectors on the Raspberry Pi. Use the following numbered steps:

  1. Parts: You’ll need the JST PH 4-pin to male header cable.
  2. Pin out: Match the wire colors and positions to this pin map. Ensure to count 7 pins in from the left for this group of pins.
  3. Making the connection: Insert each wire pin into the header holes on top of the Inventor HAT Mini. They will feel tight; push firmly. Plug the other end into the IMU.

Double-check the connections and their positions. With this wired up, you are ready to test it.

Power on the robot. The first indicator that things are right should be a power light on the IMU board; if not, power off and check the power and ground wires.

We need to reconfigure our Raspberry Pi config to add a further software I2C bus (which can deal with clock stretching) on the GPIO pins 23 and 24, as shown in the wiring diagram. Open the deploy/configure_pi.py file and add the following:

files.line(
name="Enable software i2c-gpio controller for BNO055",
line="^dtoverlay=i2c-gpio.*",
path="/boot/firmware/config.txt",
present=True,
replace="dtoverlay=i2c-gpio,bus=2,i2c_gpio_sda=23,i2c_gpio_scl=24,i2c_gpio_delay_us=2",
_sudo=True,
)

This adds an overlay during boot time on the Raspberry Pi, setting up the pins as I2C bus 2. We can then send it with pyinfra inventory.py deploy/configure_pi.py ‑y.

You will then need to reboot the Raspberry Pi (SSH, and type sudo reboot) for this to take effect.

Next, log in via SSH. Then use the sudo i2cdetect ‑y 2 command to look for devices on I2C bus 2:

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

You should see a single device at address 28. If you do see multiple devices, ensure you have checked I2C bus 2 and not I2C bus 1. If you see no devices on I2C bus 2, you will need to power off and check the SDA and SCL wiring.

Having now verified the device is connected, let’s write some code to talk to the BNO055 module.

We will need to install some libraries to make our connection. Open the deploy/virtual_env.py file and find the pip.packages section. Make the highlighted additions:

pip.packages(
name="Install pip dependencies for services",
packages=["vl53l5cx-ctypes", "Adafruit-Blinka", "adafruit-extended-bus", "adafruit-circuitpython-bno055"],
virtualenv=robot_venv,
)

Adafruit makes a number of Python-compatible libraries available, and it makes them available for CircuitPython, MicroPython, and CPython targets. The Adafruit Blinka layer is a compatibility layer for these libraries on our Python (CPython), along with the extended bus, so it can use our extra I2C bus. We can then use the CircuitPython bno055 library. You’ll need to run deploy/virtual_env.py in pyinfra to install it.

We can fetch its temperature. This is a simple way to demonstrate that we are communicating with the chip. Try this in robot/tests/test_bno055.py:

from adafruit_extended_bus import ExtendedI2C as I2C
import adafruit_bno055
import time
i2c = I2C(2)
bno055 = adafruit_bno055.BNO055_I2C(i2c)
while True:
print(bno055.temperature)
time.sleep(0.1)

In this code, we import the extended I2C bus library and set up I2C bus 2. We then pass that to the BNO055 to set that up.

Send this with pyinfra inventory.py deploy/update_code.py ‑y and run it via SSH with robotpython robot/tests/test_bno055.py. You should see the temperature:

$ robotpython robot/tests/test_bno055.py
/home/danny/robotvenv/lib/python3.11/site-packages/adafruit_blinka/microcontroller/generic_linux/i2c.py:30: RuntimeWarning: I2C frequency is not settable in python, ignoring!
warnings.warn(
23
23
23
23
23
23
23
23

The warning at the start can be ignored; however, you should start seeing the temperature. If you gently rest your finger on the sensor, you’ll see this rise.

Note that if you use the hardware Pi I2C buses 0 or 1 for this, you are likely to see strange negative numbers when the BNO performs clock stretching. See https://learn.adafruit.com/raspberry-pi-i2c-clock-stretching-fixes/software-i2c for a more detailed explanation.

You now have the IMU connected and producing data. Let’s make use of it for more.

The gyroscope in the IMU can measure relative rotation around each axis. In a MEMS gyroscope, a tiny mass vibrates back and forth very quickly. When the orientation of the gyroscope is changed, the mass will still be moving in the original direction. This movement at a different angle from the rest of the assembly will change electrical fields that the sensor detects.

We are going to be talking about orientation using a rotation system derived from the pose coordinate system we already have. See the following diagram:

Figure 13.5 – Rotation systems

Figure 13.5 – Rotation systems

Figure 13.5 – Rotation systems

The preceding diagram shows our robot’s b ody c oordinate s ystem for reference, with the X, Y, and Z axes the same as those used in our poses.

Marked on the diagram are the naming conventions for rotations around each axis. Movement around the X axis is known as roll. Rotating around the Y axis is known as pitch. Rotation around the Z axis is known as heading or yaw.

The direction of the rotation is important. You can use a right-hand rule for this. Take your right hand and hold your thumb up. If your thumb is pointing along the axis, then the fingers on your fist will wrap in the direction of the rotation. This rotation will also be consistent with the rotation used in our localisation system.

We can modify robot/test_bno055.py to print the output of the gyroscope, along with its status:

while True:
print("Gyro Calibration:", bno055.calibration_status[1], "Gyro:", bno055.gyro)
time.sleep(0.1)
When you update this, and rerun it, you should see something like this:
$ robotpython robot/tests/test_bno055.py
Gyro Calibration: 3 Gyro: (0.001090830782496456, 0.002181661564992912, 0.002181661564992912)
Gyro Calibration: 3 Gyro: (0.0, 0.0, 0.001090830782496456)
Gyro Calibration: 3 Gyro: (0.0, 0.002181661564992912, 0.003272492347489368)

We are printing the calibration status, which is the chip’s measure of how ready the gyro is for use. A status of 3 indicates it’s fully calibrated – the gyroscope calibrates as soon as it’s turned on.

The other thing being printed is the gyroscope orientation data in radians per second per axis. It’s pretty noisy, but quite close to zero unless you rotate the robot around. When you stop moving the robot, it goes back to the noisy zeros. Try rotating it in each axis.

The gyroscope is a relative sensor; it measures motion around the axes, but does not maintain the position.

We could smooth this and add the relative numbers (integrate) in our software; however, the gyroscope alone will have similar cumulative errors to encoder-based orientation. So, we will fuse this data with other sensors on the chip. Let’s see the other data the chip produces.

The accelerometer measures acceleration forces acting on a mass in the IMU, which will pull the mass in a direction opposite to the force. Let’s see a conceptual diagram of this:

Figure 13.6 – How an accelerometer works

Figure 13.6 – How an accelerometer works

Figure 13.6 – How an accelerometer works

The preceding diagram shows a conceptual view of an accelerometer. Let’s take a look at it in more detail:

  1. Panel 1: This panel shows a mass suspended by springs in a box. At rest, the ball would tend to the middle of the chamber. Each pair of springs represents one of the X, Y, or Z axes.
  2. Panel 2: When a force is exerted on the chamber, the inertia of the suspended mass will make it push on the opposing spring. Measuring the movement of the ball will tell us the direction and strength of forces.

A MEMS accelerometer is the same mass on springs in a tiny on-chip form, using a silicon mass and tiny silicon springs. The system measures changes in an electrical field to determine where the mass is.

While on Earth, the mass is pulled downward by gravity, which shows up as an upward (opposite movement) on the Z axis – the system is being pushed up by the desk it is resting on, with a force opposite to gravity. We can use the fact that it always points away from gravity to measure which way is up, relative to the robot, giving the tilt of the robot as an absolute measurement.

We can see this with a small change to the test code. Make the highlighted changes to robot/test_bno055.py:

while True:
print("Acc Calibration:", bno055.calibration_status[2], "Acc:", bno055.acceleration)
time.sleep(0.1)

This time, we are looking at the third element of the calibration status, the accelerometer, as well as printing all the data from the accelerometer sensor. If you update the code and rerun the test, you will see the following:

Acc Calibration: 0 Acc: (-0.07, -0.19, 9.35)
Acc Calibration: 0 Acc: (-0.1, -0.19, 9.3)

The calibration status is staying at 0, which means you will need to calibrate the accelerometer. To do this, you will need to perform some movements with the robot:

Figure 13.7 – Calibration movements

Figure 13.7 – Calibration movements

Figure 13.7 – Calibration movements

The preceding diagram shows how we can calibrate the accelerometer and other IMU components on this robot. Leaving the test running, move the robot smoothly and slowly through the following sequence of motions:

  1. Begin with the robot sitting flat and upright on a level surface for a few seconds.
  2. Lift the robot and sweep it through a slow figure-of-eight motion.
  3. Tilt the robot so the front faces up, hold for a few seconds, then hold it so the back faces up.
  4. Now lift the robot so the right side is facing up for a few seconds, then the left side.
  5. Turn the robot fully upside down and hold for a few seconds.
  6. Finally, return the robot upright on a flat surface.

This sequence is to expose the sensors on the BNO055 to a full range of orientations so it can determine offset and scale values. Ensure that you align the robot with up as accurately as possible. You should see the calibration go from 0 to 1 and then to 3. The output should look like this:

Acc Calibration: 3 Acc: (0.21, -0.21, 9.69)
Acc Calibration: 3 Acc: (0.22, -0.25, 9.71)
Acc Calibration: 3 Acc: (0.08, -0.22, 9.72)
Acc Calibration: 3 Acc: (0.11, -0.12, 9.64)
Acc Calibration: 3 Acc: (0.28, -0.31, 9.73)

This output shows an X, Y, and Z value for the forces on the robot in meters per second squared. These three values make up a vector, a mathematical object with an orientation and size. You can see this vector as an arrow representing the direction and size of a force.

The vector scale will be quite close to 9.8 m/s 2, as it’s being affected by gravity. If you lift and turn the robot, you’ll see that move.

However, to get a real feel for the accelerometer vector, we’ll need to visualize it. Let’s get our IMU connected to MQTT before we add more.

We will start by surfacing the items we already have from the IMU in MQTT and building a visualization around the accelerometer. We can then look at the magnetometer, another sensor, and visualize the combination of all three sensor components.

We’ve demonstrated getting IMU data. The next stage to making it useful is publishing the data. Let’s combine the MQTT code with the IMU code we’ve seen to make an MQTT IMU interface.

We’ll publish on two topics:

  • sensors/imu/status – publish the status of each IMU component
  • sensors/imu/accelerometer – publish the accelerometer vector

Add the robot/imu_service.py file with the following content:

import time
from adafruit_extended_bus import ExtendedI2C as I2C
import adafruit_bno055
from common.mqtt_behavior import connect, publish_json
client = connect(start_loop=False)
i2c = I2C(2)
bno055 = adafruit_bno055.BNO055_I2C(i2c)
while True:
status = bno055.calibration_status
publish_json(client, "sensors/imu/status", {
"sys": status[0],
"gyro": status[1],
"acc": status[2],
"mag": status[3],
})
acc = bno055.acceleration
publish_json(client, "sensors/imu/accelerometer", {
"x": acc[0],
"y": acc[1],
"z": acc[2],
})
time.sleep(0.05)
client.loop(0.05)

This combines code you’ve seen in the tests and previous MQTT clients. You could also add the gyro and temperature data in the same way if you wanted to show them in the visualization layer. We also need to add an entry in deploy/deploy_services.py for this:

code = files.put(
name="Update IMU service",
src="robot/imu_service.py",
dest="robot/imu_service.py")
deploy_service("imu_service", "robot/imu_service.py",
False, common.changed or code.changed)

For the sake of not flooding the bus, we’ve left the auto-start at False, so we will start and stop this service on demand.

You can run deploy_services.py using pyinfra and use Mosquitto to launch this. You’ll be able to subscribe to status and accelerometer updates with a Mosquitto sub. However, let’s build a visualization for this in our browser.

While graphing the numbers or showing the values on a screen would work, a 3D rendering would be more helpful. We are going to make use of the JavaScript babylon.js library. Let’s see how. Create the robot_control/accelerometer.html file.

{% extends "robot_control/page.html.j2" %}
{% block title %}Accelerometer visualization{% endblock %}
{% block content %}
<script src="https://cdn.babylonjs.com/babylon.js"></script>
<button id="start">Start</button>
<button id="stop">Stop</button>
<div>
<canvas id="plot" style="width: 80%; height: 80%;"></canvas>
</div>
Status: <samp id="status"></samp>
<script type="module">
import { connect, publish_when_clicked } from './mqtt_client.js';
let mqttClient = connect();
publish_when_clicked(mqttClient, "start", "launcher/start", "imu_service");
publish_when_clicked(mqttClient, "stop", "launcher/stop", "imu_service");
const canvas = document.getElementById("plot");

So far, this is similar to the code we’ve written for the charts, other than a new script src tag for babylon.js. We have styled the size of the canvas, and we’ve added a new element type, samp, for the status. samp just shows the status as a small code section.

Now we get 3D. Babylon works with a 3D scene, with cameras and lighting:

const engine = new BABYLON.Engine(canvas, true);
const scene = new BABYLON.Scene(engine);
const camera = new BABYLON.FreeCamera("camera", new BABYLON.Vector3(0, 20, 30));
camera.setTarget(BABYLON.Vector3.Zero());
const light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0, 1, 0));
light.intensity = 0.7;

This sets up a simple scene. However, we are placing the camera so it’s looking back at zero from a positive Z. Let’s create an arrow as a drawing:

const arrow = BABYLON.MeshBuilder.CreateLathe(
"arrow",
{
shape: [
new BABYLON.Vector3(0, 0, 0),
new BABYLON.Vector3(0, 10, 0),
new BABYLON.Vector3(5, 5, 0),
new BABYLON.Vector3(2.5, 5, 0),
new BABYLON.Vector3(2.5, 0, 0),
new BABYLON.Vector3(0, 0, 0),
]
}
);

This creates a mesh, a 3D object to draw. You can try the coordinates here on some graph paper; it’s half an arrow, but the Lathe mesh means this shape is revolved into a solid, making a round arrow, starting at 0. We can now add MQTT handlers:

mqttClient.subscribe('sensors/imu/#');
mqttClient.on('message', (topic, message) => {
switch (topic) {
case 'sensors/imu/accelerometer':
const { x, y, z } = JSON.parse(message);
arrow.alignWithNormal(new BABYLON.Vector3(x, z, y));
break;
case 'sensors/imu/status':
document.getElementById('status').innerText = message;
break;
}
});

We have two handlers here. The accelerometer handler sets the normal of the arrow. In this case, the arrow will point along this normal. babylon.js uses Y as the vertical axis, whereas our robot uses Z as up, so we swap the Y and Z elements here.

The status handler sets the innerText property of the status element to the raw message, so we’ll just see the raw JSON on the page. We need to start the 3D renderer loop and close the page:

engine.runRenderLoop(() => {
scene.render();
});
</script>
{% endblock %}

The loop will call the scene render on a regular basis, which means the arrow onscreen will display the changes our MQTT handler made to its normal.

We can add this to the menu in robot_control/index.html:

<li><a href="accelerometer.html">Accelerometer</a></li>

Run the PyInfra deploy services script and load the menu. When you click this page, you’ll need to wait a short time to see the arrow. Click the S tart button, and the arrow should start to follow the robot. You should see something similar to the following screenshot:

Figure 13.8 – Screenshot of accelerometer arrow

Figure 13.8 – Screenshot of accelerometer arrow

Figure 13.8 – Screenshot of accelerometer arrow

The preceding screenshot shows the arrow in a 3D view on the screen. The robot’s front should be facing the right of the screen, and the arrow should match the upside of the robot.

You may run into trouble here. If you don’t see things, try the following:

  • When running PyInfra, you may see Error in template. This usually means you’ve missed one of the template symbols.
  • Ensure all previous examples are functioning.
  • Check the JavaScript console and journalctl logs for error messages.
  • Verify the MQTT messages.
  • Check for any typos.

You should now be able to see your accelerometer vector. However, we still have a further, more complicated sensor, the magnetometer.

A magnetometer reads magnetic field strengths in 3D to produce a vector. Code you write can use this to determine the magnetic North in the same way as a compass.

A compass measures a heading from the Earth’s magnetic field by using a magnetized needle or disk pointing to North. If you have one, now would be a good time to determine where North is in the room you test the robot in.

The magnetometer passes electricity through material that creates a current when exposed to a magnetic field, as shown in the following diagram:

Figure 13.9 – Hall effect sensors in the magnetometer

Figure 13.9 – Hall effect sensors in the magnetometer

Figure 13.9 – Hall effect sensors in the magnetometer

The preceding diagram shows schematic illustrations of the Hall effect sensors used in the magnetometer. Here’s how these work:

  1. A power source (left) provides power, causing a constant current to flow through the sensor material. A second circuit uses a volt detector to measure the voltage deflected in the material. If there’s no magnetic field, the current will pass straight through, so no deflection, and no voltage is measured.
  2. A magnet is above the plate, deflecting the electrons flowing to one side. This will cause a negative charge on the right plate, and a positive charge on the left plate, causing a voltage to flow through the measuring circuit, and a greater-than-0 measurement on the voltage detector.
  3. Putting the magnet on the other side of the sensor changes the magnetic field, reversing which plate is charged, and causing a reverse voltage to flow. The voltage will now measure below 0.

This is known as the Hall effect, and the amount measured represents the strength of the magnetic fields. Using three such plates, you can measure the field in three axes. Tiny silicon versions of this are present in our IMU.

We can extend our system to send magnetometer data over MQTT. Open robot/imu_service.py, and locate the while loop. Under the code that sends the accelerometer data, add the code for the magnetometer data:

magnetometer = bno055.magnetic
publish_json(client, "sensors/imu/magnetometer", {
"x": magnetometer[0],
"y": magnetometer[1],
"z": magnetometer[2],
})

You can then copy robot_control/accelerometer.html to robot_control/magnetometer.html. Edit the page to display magnetometer data from the IMU topic, along with updating the page title and index link.

When you send this, load the page and be sure to click the S top button, then the S tart button, to ensure you are running the current IMU service. You will be able to see a different vector from the accelerometer vector. This is pointing to the strongest magnet source – which is hopefully North. If it’s pointing at other equipment in your house, you need to move away from that.

Pin headers and other robot components are often made from magnetic metal. You can also carefully bring a metal object, such as a screwdriver, close to the IMU (don’t touch the electronics with it), and you should be able to see the arrow move. One reason for the figure of 8 movement in the preceding calibration is so that the magnetometer is taken through many different positions.

Now we’ve seen each of the sensors, let’s see how to get the chip to combine them.

This BNO055 is capable of fusing all the sensors and giving a full orientation as 3D Euler angles. This has the roll, pitch, and yaw values we saw earlier in the chapter. The sensor needs all the status values to be at 3. We will make a status and visualization page to calibrate the robot with the motions until everything reads 3.

Why fuse these? Each sensor provides a different value and with different limitations:

  • The gyroscope provides short-term rotation, subject to drift
  • The accelerometer provides a tilt reference, but no yaw information
  • The magnetometer provides magnetic fields, a long-term yaw reference, but is subject to magnetic interference and is slow to respond

It will then perform a number of operations:

  • Smooth the noisiness of the accelerometer so it is less jittery
  • Allow the gyroscope readings to affect the rotation, both smoothing and integrating (adding) its measurement of change
  • Combine the magnetometer readings with detections of its changes and non-changes at different angles so that magnetic objects attached to the robot don’t bias the use of this so much

Combining them allows the IMU to estimate an absolute orientation of the robot.

We can conveniently extend our system to make this Euler vector available. Note that this is no longer an X, Y, and Z position like the previous vectors, but all rotation values.

Open robot/imu_service.py. The bno055 library returns the Euler rotations in degrees; however, we are working in radians throughout the book, so we will be converting this value. At the top, add the following imports:

import numpy as np
import ujson as json

Then add the following code in the loop:

euler = np.radians(bno055.euler)
publish_json(client, "sensors/imu/euler", {
"yaw": euler[0],
"roll": euler[1],
"pitch": euler[2],
})

The BNO055 returns Euler angles in the order (yaw, roll, pitch). We can then create a visualization. We’ll use some simple boxes and cylinders to make something shaped a little like our robot onscreen.

Most of the page is identical to the robot_control/accelerometer.html page. Make a copy of that and call it robot_control/imu.html. We are going to focus on the JavaScript module. We start with imports and create a slightly different camera position:

import { connect, publish_when_clicked } from './mqtt_client.js';
let mqttClient = connect();
publish_when_clicked(mqttClient, "start", "launcher/start", "imu_service");
publish_when_clicked(mqttClient, "stop", "launcher/stop", "imu_service");
const canvas = document.getElementById('plot');
const engine = new BABYLON.Engine(canvas, true);
const scene = new BABYLON.Scene(engine);
const camera = new BABYLON.FreeCamera("camera", new BABYLON.Vector3(0, 10, -15));
camera.setTarget(BABYLON.Vector3.Zero());
const light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0, 1, 0));
light.intensity = 0.7;

We are going to make a robot representation, so the mesh will be a bit more complicated:

function makeRobot() {
// Orient so X is forward, Y is up, Z is right
const chassis = new BABYLON.MeshBuilder.CreateBox("robot", { height: 1, width: 5, depth : 3 });
chassis.position.y = 0.5;
const wheelL = new BABYLON.MeshBuilder.CreateCylinder("wheelL", { diameter: 1, height: 0.5 });
wheelL.position.z = 1.5;
wheelL.position.y = 0.5;
wheelL.rotation.x = Math.PI / 2;
const wheelR = wheelL.clone("wheelR");
wheelR.position.z = -1.5;
const electronics = new BABYLON.MeshBuilder.CreateBox("electronics", { height: 0.5, width: 1, depth : 1.5 });
electronics.position.y = 1.25;
electronics.position.x = -1;

This code creates a box for the chassis, and a box for the electronics above it. However, we need to combine these meshes into a single merged object, so it can be rotated as a single thing:

return new BABYLON.Mesh.MergeMeshes(
[
chassis,
wheelL,
wheelR,
electronics
],
true
);
}
const robot = makeRobot();

This MergeMeshes method turns the multiple parts into a single mesh, and the lone true parameter ensures that the other meshes are consumed, so they don’t remain on the page as unrotated duplicates. Creating the robot 3D model is in a function that returns the mesh, so the next line calls it and stores the result.

We finish the JavaScript section with a slight change in the MQTT handlers:

mqttClient.subscribe('sensors/imu/#');
mqttClient.on('message', (topic, message) => {
switch (topic) {
case 'sensors/imu/euler':
const { roll, pitch, yaw } = JSON.parse(message);
robot.setDirection(new BABYLON.Vector3(0, 0, 1),
yaw, pitch, roll);
break;
case 'sensors/imu/status':
document.getElementById('status').innerText = message;
break;
}
});
engine.runRenderLoop(() => {
scene.render();
});

In the highlighted change, we are setting the direction of the robot mesh. There’s a vector to specify what up is, the Z axis, and then the yaw, pitch, and roll parameters are passed in a fixed order.

Add a link for this to the menu, and then run the deploy services script.

When you load it in the browser, you should see a screen like the following:

Figure 13.10 – IMU Visualization page

Figure 13.10 – IMU Visualization page

Figure 13.10 – IMU Visualization page

The preceding screenshot shows the visualization with a simplified graphic of your robot. You will need to click the Stop and Start buttons for it to receive new IMU data. When it does so, you should ensure you are fully calibrated, and you should see the robot move relative to your motions. The exact alignment of yaw will depend on where North is relative to your screen.

Remember that you will be able to see the angles as an MQTT message by spying on the MQTT bus (mqttui or MQTTX). Remember that these will be in radians.

If you don’t see what you expect, try the following:

  • Remember that 0 is East and not North
  • Ensure you are fully calibrated
  • Verify journalctl and MQTT to see the Euler values or errors with the IMU service
  • Verify the browser JavaScript console to check for JavaScript errors

We now have Euler data from our IMU sensor, and a nice way to visualize it. However, what if we want to make use of it in a robot’s behavior?

Our IMU yaw data can be consumed by a robot’s behavior by connecting it to a PID controller. We can build on concepts seen before to make this work. In this section, we’ll design and build an IMU-based robot behavior, with some supporting code to make it work.

Let’s make a design for this behavior.

We can use our calibrated sensors’ yaw to create a behavior that will steer the robot to always face a particular direction. We can then create a simple page to start, stop, and set the intended direction for it.

Let’s see this behavior idea as an information flow diagram:

Figure 13.11 – Always face direction behavior

Figure 13.11 – Always face direction behavior

Figure 13.11 – Always face direction behavior

The preceding diagram shows how we start with an expected yaw, somewhere we want the front of the robot to face. Although note we will need to account for the front X axis being aligned with East here. The IMU will have provided an actual yaw, so subtracting this from the expected yaw will produce an error value.

Like our other PID behaviors from Chapter 11, Programming Encoders with Python, we will be using a dt (delta time) from a time stepper here.

We will feed dt and the error to the PID to generate a control signal. We will apply it by setting one motor speed to its output, and the other to its output negated, so the robot will turn. As the robot turns, the movement will mean there’s a new actual yaw from the IMU. With the right PID tuning, it will turn until the error is close to zero.

When we build this, we will be dependent on calibrated sensors, so we’ll start building this by improving the IMU service to store the calibration data.

If you’ve turned the robot off and started again, you will have to go through the calibration routine again. This takes time and can frustratingly take a few attempts to get to full status 3 every time. Thankfully, the BNO055 allows us to read or set calibration values. It will forget them when it is reset, but we have a config store on the robot where we can keep information like this for later.

We are going to extend the IMU service to do the following:

  • Request IMU calibration data from the config store
  • Set it if we receive it
  • If we reach status 3 on all devices, store the config in the config data store

The exact shape of the config is specific to the BNO055, so we are going to store and retrieve a further JSON payload there. We will use the config key imu/calibration.

Open the robot/imu_service.py file and find the client connection line.

Let’s start with a function to store our calibration data. Add this after the BNO055 is created, but before the while loop:

def store_calibration():
bno055.mode = adafruit_bno055.CONFIG_MODE
try:
calibration = {
'offsets_accelerometer': bno055.offsets_accelerometer,
'offsets_magnetometer': bno055.offsets_magnetometer,
'offsets_gyroscope': bno055.offsets_gyroscope,
'radius_accelerometer': bno055.radius_accelerometer,
'radius_magnetometer': bno055.radius_magnetometer,
}
finally:
bno055.mode = adafruit_bno055.NDOF_MODE
publish_json(client, "config/set",
["imu/calibration", json.dumps(calibration)]
)

The calibration is a series of offsets and radii for the different sensors. We must put the chip into config mode while reading these, so they are held for that operation. We take all of these values and store them in a single Python dictionary. We can store anything in our data store, as long as we can encode it in a value. Encoded JSON is a string, so we can store that. We must not forget to put the chip back into NDOF mode – where it fuses multiple sensors with 9 degrees of freedom, hence this being in a finally clause.

We will also need to decode that structure and set the values on the BNO055 if we receive the calibration data. Add the following function:

def calibration_received(calibration_data):
if bno055.calibration_status[0] == 3:
return
unpacked = json.loads(calibration_data)
bno055.mode = adafruit_bno055.CONFIG_MODE
try:
bno055.offsets_accelerometer = tuple(unpacked['offsets_accelerometer'])
bno055.offsets_magnetometer = tuple(unpacked['offsets_magnetometer'])
bno055.offsets_gyroscope = tuple(unpacked['offsets_gyroscope'])
bno055.radius_accelerometer = unpacked['radius_accelerometer']
bno055.radius_magnetometer = unpacked['radius_magnetometer']
finally:
bno055.mode = adafruit_bno055.NDOF_MODE

First, we check if the system is already calibrated, so we don’t override that. Our configuration system resends the config when it is set, so we don’t want to respond to our own messages. We must also only set these values while in config mode.

Next, we want to subscribe to config updates with a handler, and then ask for config if there is any already. Add the following code:

def on_config_updated(client, userdata, message):
data = json.loads(message.payload)
if 'imu/calibration' in data:
calibration_received(data['imu/calibration'])
client.subscribe("config/updated")
client.message_callback_add("config/updated", on_config_updated)
publish_json(client, "config/get", ["imu/calibration"])

We now need to consider when to update this configuration. Replace the status part of our main loop with this code:

previous_status = (0, 0, 0, 0)
while True:
status = bno055.calibration_status
publish_json(client, "sensors/imu/status", {
"sys": status[0],
"gyro": status[1],
"acc": status[2],
"mag": status[3],
})
if tuple(status) != previous_status:
previous_status = tuple(status)
if status[0] == 3: # Fully calibrated
store_calibration()

We don’t want to republish all the time our status is 3, only when it changes to being fully calibrated. So, before the main loop, we can use a variable previous_status to store the state for later comparison. Then, after the status is retrieved, we check whether it’s different. If so, we update previous_status. It’s only then that we check status 0 (system) for the full calibration (3) status, and store the calibration.

We must also change our loop to perform a synchronised MQTT client loop to ensure it’s not trying to handle received calibration data at the same time as another chip operation. Make the highlighted change near the top of the code:

client = connect(start_loop=False)

Change the end of the loop to include a client.loop instruction:

time.sleep(0.05)
client.loop(0.05)

This client.loop instruction is a manual loop to avoid concurrent access while we are interacting with the IMU.

When you send this to the robot and run the S tart button from the IMU page, you should see the config messages on the MQTT bus. Test this by powering off the robot, powering it on again, and starting the IMU behavior when the robot is ready. This time, you should not need to recalibrate, as it will receive calibration data from the config store. This way, you do not need to calibrate it every time you use it.

We can use the calibrated sensors and our behavior design to program the behavior now. Create a new file named robot/face_direction.py. We’ll start with imports and setting up a PID:

import atexit
import time
import ujson as json
import numpy as np
from common.mqtt_behavior import connect, publish_json
from common.pid_controller import PIDController
from common.time_stepper import TimeStepper
class FaceDirectionBehavior:
def __init__(self):
self.pid = PIDController(0.3, 0.2)
self.time_stepper = TimeStepper()
self.target_yaw = 0

The PID values are high because the yaw is in radians, with values between 0 and 2 * pi, about 6.28. The PID output is scaled to match the motor input range (−1 to 1). The target yaw is set to 0, but can be adjusted. This should be facing East.

Let’s add an IMU data handler that works with the PID:

def on_imu_data(self, client, userdata, message):
# Sense
imu_data = json.loads(message.payload)
current_yaw = imu_data['yaw']
time_difference = self.time_stepper.step()
# Think
yaw_error = self.target_yaw - current_yaw
if yaw_error > np.pi:
yaw_error -= 2 * np.pi
if yaw_error < -np.pi:
yaw_error += 2 * np.pi
control_signal = self.pid.control(yaw_error, time_difference)
# Act
publish_json(client, "face_direction/plot", {
"yaw_error": yaw_error,
"control_signal": control_signal,
"time": time.time()
})
publish_json(client, "motors/wheels", [control_signal, -control_signal])

The sense section extracts the yaw data and updates the time stepper. The think section determines the error value. The yaw from the IMU wraps around between 2 pi and 0, which means that the robot will start turning the wrong way if it’s close to 0. By restricting the range of the error with these if statements, we’ve kept the error closer to the zero mark around the target yaw. This value is then fed into the PID.

In the act section, we publish a plot and update the motors from the control signal.

We are going to let this behavior start our IMU service, which means it will also be responsible for stopping it. Let’s set up what this should do when it’s stopped:

def stop(self, client):
publish_json(client, "motors/wheels", [0, 0])
client.publish("launcher/stop", "imu_service")

This uses the launcher to stop the IMU service, as well as stopping the wheels.

We want the system to start moving when the IMU status is calibrated. Add the following section:

def on_status_update(self, client, userdata, message):
status = json.loads(message.payload)
if status['sys'] == 3: # Fully calibrated
client.subscribe("sensors/imu/euler")
client.message_callback_add("sensors/imu/euler", self.on_imu_data)

This message handler will unpack status messages, and when the sys status is 3, indicating the IMU is fully calibrated, it will connect the sensors/imu/euler topic to the on_imu_data handler.

We then tie this together in the start function, setting up the handlers and registering the stop function before it starts moving:

def start(self):
client = connect(start_loop=False)
client.subscribe("sensors/imu/status")
client.message_callback_add("sensors/imu/status", self.on_status_update)
client.publish("launcher/start", "imu_service")
atexit.register(self.stop, client)
client.loop_forever()

Although we’ve subscribed and sent messages, the MQTT handlers won’t start processing until the loop_forever call. By registering stop to run at exit before this point, it should stop everything even if there are problems.

We can now start this behavior in the normal way:

behavior = FaceDirectionBehavior()
behavior.start()

This should be mostly similar to the other PID-based behaviors you’ve seen before. You will need to add this in deploy/deploy_services.py.

We can also make a page to control and monitor it, based on our button page template with a time series plot. Add a new robot_control/face_direction.html file:

{% extends "robot_control/page.html.j2" %}
{% block title %}Face direction{% endblock %}
{% block content %}
<button id="start">Start</button>
<button id="stop">Stop</button>
<div class="line_chart">
<canvas id="plot"></canvas>
</div>
Status: <samp id="status"></samp>
<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", "face_direction");
publish_when_clicked(mqttClient, "stop", "launcher/stop", "face_direction");
const behavior_chart = create_timeseries_chart('plot', ['yaw_error', 'control_signal'])
mqttClient.subscribe('face_direction/plot');
mqttClient.subscribe('sensors/imu/status');
mqttClient.on('message', (topic, message) => {
switch (topic) {
case 'sensors/imu/status':
document.getElementById('status').innerText = message;
break;
case 'face_direction/plot':
behavior_chart.update_data(JSON.parse(message));
break;
}
});
</script>
{% endblock %}

This control page should be starting to look quite familiar; the names of items may be different, but you have seen their function before. You will also need to add a face direction item to the robot_control/index.html menu.

Use deploy/deploy_services.py with pyinfra to send this to the robot. When you load it, and click S tart, you should see the following happen:

  • The IMU service will pick its calibration data, and the page will show a status of 3. If not, go back to the previous example and get things calibrated so the data is stored. It will not start moving until you have calibrated the robot.
  • The motors will turn to line the robot up with the target yaw – East. It may stop short. This is the proportional response. If this doesn’t move quickly, increase the proportional gain; if it overshoots, maybe lower it.
  • The motors will, after a while, slowly move to offset any error left. This is the integral response. If this takes a very long time, increase the integral a bit.
  • The graph will show how close the error is to the target, along with the control signal.

First, try turning the robot away, and watch it return to its space. You can try a few different target yaw values in this example.

There’s a known issue with this behavior in the PID controller, which we should fix before moving on.

Note that if you hold the robot away from facing East for a while, the integral will cause the robot to massively overshoot past it when it is finally able to move. Try this – and be prepared to catch it when it tries to spin multiple turns. Let’s correct this problem with a smart reset when the error passes the zero mark.

Open robot/common/pid_controller.py. First, at the top, add a numpy import:

import numpy as np

Then we need to change our class constructor to allow a smart reset mode:

def __init__(self, proportional_constant, integral_constant=0, smart_reset=False):
self.proportional_constant = proportional_constant
self.integral_constant = integral_constant
self.integral = 0
self.smart_reset = smart_reset

We can now use this in the control mode:

def control(self, error, time_difference=1):
if self.smart_reset and np.sign(error) != np.sign(self.integral):
self.reset()
self.integral += error * time_difference
return self.proportional_constant * error \
+ self.integral_constant * self.integral

This reset will happen if the error and the integral end up with different signs, so crossing the line to a negative error will stop an existing integral from feeding it further.

We need to enable this in robot/face_direction.py:

def __init__(self):
self.pid = PIDController(0.3, 0.2, smart_reset=True)
self.time_stepper = TimeStepper()
self.target_yaw = 0

Now you can hold the robot off target for some time, and it will stop close to the zero mark. You should be able to hear the motors winding up with the integral as you hold it; it will overshoot a bit, but quickly come back.

We have now incorporated another useful sensor into our robot system. Let’s see what we’ve learned.

In this chapter, we connected an inertial measurement unit to our robot and ensured it’s correctly positioned relative to the robot. We saw how to get data from it, calibrate the sensor, and make that data available via MQTT.

We saw how it represents the yaw, pitch, and roll of the robot, and how we can visualize that, along with how to use it in a behavior to get the robot to face a direction.

In the next chapter, we are going to add a camera, so the code on the robot can see!

The following challenges will let you build a better robot and learn more from the techniques in this chapter:

  • Try adding an Euler angles display to the IMU page.
  • Could you extend the robot 3D mesh model in the Euler page?
  • The face direction service still needs tuning the old way by reloading code. Could you extend it so the target yaw and PID settings are configurable from the page?
  • Could you combine the facing direction with obstacle-avoiding code, such that the robot would drive in a specific direction until encountering an obstacle, steer away from it, then steer back in the intended direction when the obstacle is clear?

Please refer to the following for more information: