Skip to content
ImagineWorld

Programming Distance Sensors with Python

node_idnode-book_learn-robotics-programming_chapter-08-programming-distance-sensors-with-python
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num8
chapter_titleProgramming Distance Sensors with Python
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 8 — Programming Distance Sensors with Python

Section titled “Chapter 8 — Programming Distance Sensors with Python”

We’ve built a robot that we can drive, but until it uses some sensors, it isn’t showing much automatic behavior. In this chapter, we’ll find out about the different types of range-finding distance sensors and choose a suitable type. We will see how to mount the chosen distance sensor arrangement to the robot, connect it electronically, and then write code for it.

We will look at how to get data from the distance sensor. We will then see how to serve that data via MQTT and transform the data to visualize it on our phone app.

You will learn about the following topics in this chapter:

  • Choosing between optical and ultrasonic sensors
  • Attaching and reading a distance sensor
  • Making sensor data available in MQTT
  • Viewing sensor data in a smartphone app

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

  • The Raspberry Pi robot and the code from the previous chapters
  • A smartphone or PC with Wi-Fi
  • A VL53L5CX Time of Flight array sensor breakout, preferably the Pimoroni PIM622
  • A Stemma QT/Qwiic 4-pin JST-SH cable 300 mm long
  • A sensor mounting bracket – Pimoroni COM3600
  • The M2.5 Nylon Standoff kit
  • A pin vise with M2.5 and smaller bits
  • A clamp or vise
  • Long-nosed flat pliers
  • A screwdriver suitable for the nylon bolts

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.

Choosing between optical and ultrasonic sensors

Section titled “Choosing between optical and ultrasonic sensors”

Before we use distance sensors, let’s find out what these sensors are, how they work, and some of the different types of distance sensors that are available.

The most common ways to sense distance use ultrasound or light. The principle of both of these mechanisms is to fire off a pulse and then sense its reflected return, using its timing to measure a distance, as can be seen in the following diagram:

Figure 8.1 – Using pulse timing in a distance sensor

Figure 8.1 – Using pulse timing in a distance sensor

Figure 8.1 – Using pulse timing in a distance sensor

We focus on the sensors that measure the response time, T, otherwise known as the time of flight. Figure 8.1 shows how these sensors use reflection time.

Let’s use this understanding of how sensors work to take a closer look at optical sensors and ultrasonic sensors.

Light-based sensors can use visible light, but more often use infrared laser light that we cannot see.

Optical distance sensors are small and can take a precise and fast series of measurements. However, they can be saturated by bright lights, such as facing direct sunlight or halogen lamps, which means they aren’t suited to every task. Most sunlight indoors is indirect (at an angle) so, for indoor robotics, they are great. Some sensors can report on the quality of their measurement data, so poor data can be excluded.

The following figure shows an example of an optical distance sensor:

Figure 8.2 – A VL53L5CX on a carrier board

Figure 8.2 – A VL53L5CX on a carrier board

Figure 8.2 – A VL53L5CX on a carrier board

The figure shows a VL53L5CX optical distance sensor and 8x8 array on a breakout carrier board from Pimoroni. The small rectangular device with two squares above the white writing in the left image is the sensor. The rest of the board is to carry the supporting electronics and has convenient mount points and connections to break it out for use with other electronics. The device pictured, the VL53L5CX, can detect an array of distances, which means that it can be used in place of 64 simpler sensors.

Breakouts like this also have useful information printed on them, beyond the device name, it has pins labeled, along with the default I2C address for this sensor and its voltage range. We’ll discuss voltage ranges below.

There are other optical sensors available; however, few have this 8x8 array ability. The product page from Pimoroni at https://shop.pimoroni.com/products/vl53l5cx-time-of-flight-tof-sensor-breakout has a lot of useful information about this board. Alongside the features and specifications, there are links here to a datasheet with details of the sensor chip, a schematic showing all the support components and the wiring of this breakout, and library code, which we will make use of.

The pictured sensor includes data quality measurement and reflectance/light measurement, as well as the expected distance sensing. We will see how to use data quality status further down in this chapter.

Optical sensors can be more expensive than ultrasonic sensors but often use I2C, making it easier to share pins with other connected devices. Using multiple I2C sensors, however, does come with the added complication of changing their I2C addresses. We are only using one of these sensors in the book so this is not required.

Now we’ve looked at the optical sensors, what about the sound-based sensors?

Most sound-based distance sensors use ultrasonic sound with frequencies beyond human hearing limits, although they can annoy some animals, including dogs. Mobile phone microphones and some cameras pick up their pulses as clicks. Ultrasonic devices tend to be larger than optical ones, but they are cheaper since sound travels slower than light and is easier to measure. Soft objects that do not reflect sound, such as fabrics, can be harder for these to detect.

Figure 8.3 shows the HC-SR04, a common and inexpensive ultrasonic distance sensor:

Figure 8.3 – The HC-SR04 ultrasonic distance sensor

Figure 8.3 – The HC-SR04 ultrasonic distance sensor

Figure 8.3 – The HC-SR04 ultrasonic distance sensor

The pictured HC-SR04 has two large cans, one for sending and the other for detecting ultrasonic sound bursts. The response from them needs to be precisely timed by code to make a distance measurement. They have a range of up to 4 meters from a minimum of about 2 cm.

These sensors can be confused by rattling keys, squeaky wheels, and chassis vibrations.

There are a number of ultrasonic-based devices, including the common HC-SR04, but not all of them are suitable.

Another aspect of comparing these sensor modules is their electrical compatibility with the Raspberry Pi and whether they need further electronics to connect them.

The I/O pins on Raspberry Pi are only suitable for inputs of 3.3 V. Many devices use 5 V logic for their inputs and outputs. Let’s see what logic levels and voltage are, and why you should try to use the native voltage level when possible.

Voltage describes how much pressure there is on an electrical flow. Different electronics are built to tolerate or respond to different voltage levels. High voltages through a device can damage it. Lower voltages won’t be detected or make unclear readings. Logic devices output a high (1) or low (0) voltage to represent true/false values. These voltages must be above a threshold to be true and below it to be false. We must be aware of these electrical properties or we will destroy things and fail to get them to communicate.

The graph in Figure 8.4 shows the effects that different levels have:

Figure 8.4 – Voltages and logic levels

Figure 8.4 – Voltages and logic levels

Figure 8.4 – Voltages and logic levels

The graph in *Figure 8.*4 has voltage on the Y-axis (left) from 0 to 5 V. The four dashed lines running through the graph are different voltage levels. Below the lowest dashed line at 0.8 V, an input is considered a logic 0. Above the next line, at 2.3 V, is where many 3.3 V devices consider things at logic 1. Above the 3.3 V line, damage may occur to a Raspberry Pi. Above 4.2 V would be considered a logic 1 for 5 V devices, although some will allow as low as 2 V. The Raspberry Pi needs help to talk to those.

Along the graph are five bars. The first bar is at 0 V and is a clear logic 0 to all devices. The next bar is a clear logic 1 for the Raspberry Pi at 3.3 V, but being below 4.2 V, may not be seen as logic 1 by some 5 V devices. The bar labeled U nclear is at 1.8 V – in this region between the low and the high thresholds, the logic is not clear for a 3.3 V device, and this should be avoided. The bar labeled Vague logic 1 is a little below the threshold and could be misinterpreted by 3.3 V devices. The last bar is at 5 V, which is the output of 5 V devices. This would damage Raspberry Pi inputs.

Warning: Proper connection between sensors and controllers needs to match voltage levels to avoid random data, no data, or damage to either device.

Level shifters can be used where they don’t match.

When buying electronics for a robot, consider carefully what voltage the robot’s main controller uses (the Raspberry Pi), and check that the electronics work with the controller’s voltages. The VL53L5CX module works well here, being a 3.3 V device.

We should consider how the two sensors we’ve illustrated here compare in terms of information about the world and where we would place them.

Having multiple sensors allows a behavior to detect which side is closer to an obstacle, or infer more information about the obstacle it is facing. With this, the robot can detect where open spaces are and move toward them. *Figure 8.*5 shows how this works:

Figure 8.5 – Using two sensors

Figure 8.5 – Using two sensors

Figure 8.5 – Using two sensors

In Figure 8*.*5, the second robot can make more interesting decisions because it has more data from the world with which to make those decisions.

However, some sensors produce more than one reading, as if they were multiple sensors. We can compare the HC-SR04 with the VL53L5CX. It’s important to note that there are cheaper and less capable optical sensors than the VL53L5CX. The next diagram shows what distances are sensed:

Figure 8.6 – Comparing distance sensor modules

The preceding diagram shows the HC-SR04 and the VL53L5CX, and for each, how they are sensing the environment in front of them. These diagrams are not to scale but they illustrate how each sensor views the world.

The HC-SR04 measures in a cone with roughly a 15-degree field of view (FoV) across the middle. It will detect a reading for the nearest object in front of the sensor.

The VL53L5CX measures 64 regions, forming a cone with a 63-degree FoV, much wider than the HC-SR04. The illustration shows that each region in this can have an independent measurement value. The HC-SR04 misses completely that there’s a stepped feature in front of the wall, reporting only the closest 75 cm measurement. Multiple HC-SR04 sensors would be needed for more resolution. The VL53L5CX has measured 90 cm at the wall, 80 cm for the regions hitting the first step, and 75 cm for the regions hitting the next step. This resolution means we can use one sensor in the place of many. This also can feed more interesting robot algorithms.

We’ve seen some distance sensor types and discussed the trade-offs and choices for this robot. You’ve learned about voltage levels, and why this is a crucial consideration for robot electronics. We’ve also looked at how many sensors we could use and where we could put them. Now let’s look at how we’ll put this distance sensor on the robot.

First, we will wire in and secure this sensor to the robot. We will then write some simple test code that we can use to base our behavior code on in the next section. After completing this section, the robot block diagram should look like *Figure 8.*7:

Figure 8.7 – Robot block diagram after adding the sensor

Figure 8.7 – Robot block diagram after adding the sensor

Figure 8.7 – Robot block diagram after adding the sensor

This diagram builds on the block diagram in Figure 5*.1 9 from Chapter 5, Building Robot Basics – Wheels, Power, and Wiring*, by adding the sensor. It has an arrow to the Raspberry Pi, since although it is an active sensor, the information from it is logically flowing from the sensor to the Raspberry Pi. In the next section, let’s attach the sensor to the robot chassis.

Our sensor needs to be pointed to the front of our robot; it needs to not fall off and move rigidly with the chassis. The chassis doesn’t have front-facing bolt holes; however, in the suggested purchase list, we have the COM3600 bracket, and the top of our chassis has holes. Unfortunately, the bracket holes don’t align with our needs, so we are going to need to drill some additional holes, and then assemble the sensor onto the robot. The following diagram shows the additional holes:

Figure 8.8 – Additional holes

Figure 8.8 – Additional holes

Figure 8.8 – Additional holes

The preceding drawing shows the additional holes. The holes are made on the bracket. First, find the front and base on the bracket – these are the smooth outside surfaces. The front should have two slots and a hole – and we will be adding further holes here to mount the sensor. The drawing shows dimensions with arrows 18 mm in from the outside, 14 mm between the holes, and 3 mm from the rear edge (away from the corner). The holes are 2.5 mm in diameter, for M2.5 screws.

Let’s mark out the holes on the bracket using a clamp/desk vise, pencil, and calipers:

Figure 8.9 – Marking out the bracket holes

Figure 8.9 – Marking out the bracket holes

Figure 8.9 – Marking out the bracket holes

The photos above show three stages to marking out the holes in the bracket:

  1. Use a clamp to position the bracket so you can mark holes and later protect your fingers when cutting them. Use the top straight edge of the calipers to find 3 mm, then mark a small pencil line. Pencil lines are faint but clear enough to drill from. Mark the 3 mm line along the outside edge of the front, to the left and right.
  2. Then, mark the 18 mm line in from the left edge, and the same in from the right edge.
  3. You should end up with two crosses ready to drill.

We can drill these using the pin vise:

Figure 8.10 – Drilling with the pin vise

Figure 8.10 – Drilling with the pin vise

Figure 8.10 – Drilling with the pin vise

The photo shows me using the pin vise, which is a small hand drill for tiny bits and is used to make accurate holes in small parts like these. Continue with these steps:

  1. In Panel 4, I start by making a 0.5 mm hole, a pilot hole, where the lines cross, as it’s easier to guide a smaller drill bit. Aim for accuracy, not speed, here.
  2. Once you’ve drilled carefully through, as shown in Panel 5, use the 2.5 mm bit to bore it out to fit the bolts.
  3. You should have two additional holes, as shown in Panel 6.

There are holes in the chassis that line up with the slots, so we can make use of these to mount the bracket. You will now be able to assemble the sensor onto the robot, as shown in the following pictures:

Figure 8.11 – Assembling the sensor onto the chassis

Figure 8.11 – Assembling the sensor onto the chassis

Figure 8.11 – Assembling the sensor onto the chassis

The prior diagrams show how to bolt these parts together. Start by pushing the standoff threads through the bracket and tightening the nuts behind them with the long-nosed flat pliers.

Next, bolt the sensor onto these standoffs. Then, bolt the bracket into the chassis using the two holes near the front. Try to ensure the bracket is aligned in the middle when tightening the nuts.

With the sensor rigidly attached to the robot, it is ready for wiring.

We can wire this sensor with the long QW/ST cable (four-pin JST-SH 300 mm). The wiring should look like this:

Figure 8.12 – Sensor wiring

Figure 8.12 – Sensor wiring

Figure 8.12 – Sensor wiring

The sensor has a connector socket on its back, shown on the left of the preceding picture sequence. The plug on the cable will only go into the sockets one way.

Warning: Don’t force these as the sockets can break!

There’s a socket for the other end on the Inventor HAT Mini, shown at the top left. I then tucked the cable out of the way of the robot wheels, as shown in the zoomed-out robot view at the bottom. You can route the wire through the middle to make it tidier.

The sensor usually comes packaged with a protective orange cover slip over the sensor element. Be sure to gently remove this using the tiny tab before use.

This sensor is wired into the Raspberry Pi, but now it needs some code to get its data!

Installing Python libraries to communicate with the sensor

Section titled “Installing Python libraries to communicate with the sensor”

To work with this sensor, we need to add some libraries. The sensor data consists of 64 data elements per message, so we will use the Python ujson library to create JSON data more efficiently. We’ll also prepare numpy for more efficient number manipulation. The NumPy (pronounced numb – pie) library has many ways to manipulate numeric arrays, reshaping them and transforming them rapidly. NumPy is an essential library for more interesting Python robotics.

Let’s use PyInfra to install it on the Raspberry Pi. Open deploy/base_packages.py and add the highlighted code:

base_packages = apt.packages(
name="Install python and i2c tools",
packages=["python3-pip", "python3-smbus", "i2c-tools",
"python3-ujson", "python3-numpy"],
_sudo=True,
)

We then need a pip package too. Open the file deploy/virtual_env.py and add the following to the end:

pip.packages(
name="Install pip dependencies for services",
packages=["vl53l5cx-ctypes"],
virtualenv=robot_venv,
)

We are installing vl53l5cx‑ctypes, a Pimoroni library created to interact with the device from Python. Run pyinfra inventory.py deploy/virtual_env.py to prepare this. Because virtual_env.py imports base_packages.py, it will ensure the NumPy installation runs first.

Ensure you have made the base_packages changes first!

With the library now installed, we can write test code to read the sensor.

This sensor array means that we will get multiple data elements for each reading. We’ll start with a simple test script to get some data from the sensor and print it on the screen.

Create the file robot/tests/test_distance_sensor.py:

import atexit
import time
import vl53l5cx_ctypes
print("Initializing distance sensor...")
sensor = vl53l5cx_ctypes.VL53L5CX()
print("Setting distance sensor resolution and frequency")
sensor.set_resolution(8 * 8)
sensor.set_ranging_frequency_hz(10)
print("Starting distance sensor ranging")
sensor.start_ranging()
atexit.register(sensor.stop_ranging)
while True:
if sensor.data_ready():
data = sensor.get_data()
print(data.distance_mm[0][0], data.distance_mm[0][7])
time.sleep(0.01)

This imports vl53l5cx_ctypes along with time. We create an instance of the VL53L5CX sensor and then configure the 8x8 resolution – equivalent to 64 sensors! We configure how often the sensor sends data with set_ranging_frequency_hz. A setting of 10 configures it to send 10 times per second. Hz, short for Hertz, is a measurement of how many cycles there are per second.

We then tell the sensor to start_ranging, starting the data output. This sensor should be left in a good state when we are done, so atexit ensures we call stop_ranging too. The main loop waits for sensor data and reads it.

The variable data.distance_mm is a two-dimensional array, with a list of a single item, containing a list of 64 entries. See the following diagram for the configuration:

Figure 8.13 – Sensor data arrangement

Figure 8.13 – Sensor data arrangement

Figure 8.13 – Sensor data arrangement

As the diagram shows, item 0 is the bottom-right cell of the sensor data. Our code above prints from 0, and then item 7 for the bottom left of the robot.

Run pyinfra inventory.py deploy/update_code.py to make this available on the Raspberry Pi, then, in SSH, run robotpython robot/tests/test_distance_sensor.py to start it. It will take about 20 seconds to initialize the sensor, and then you should start seeing distance data in millimeters:

307 277
306 284

Each line shows the bottom-right and then the bottom-left measurement. You can test the values by taking a flat, opaque object above 5 cm squared and waving it in front of the sensor. You can angle the item to the left or right and see the numbers updating.

You’ve configured the sensor and demonstrated that the distance sensor is working. To make sure you’re on track, let’s troubleshoot anything that has gone wrong.

If this sensor isn’t working as expected, try the following troubleshooting steps:

  • If there are syntax errors, please check the code against the examples; be aware of indentation, colons, and types of brackets.
  • Ensure you have run the PyInfra scripts for deploying the sensor library and deploying the new code.
  • Ensure that the cable is plugged into both the sensor and the Raspberry Pi. The error RuntimeError: VL53L5CX not detected on 0x29 shows a connection problem. You can verify it is present with the command i2cdetect ‑y 1 over SSH. You should see the following:
    0 1 2 3 4 5 6 7 8 9 a b c d e f
    00: -- -- -- -- -- -- -- --
    10: -- -- -- -- -- -- -- 17 -- -- -- -- -- -- -- --
    20: -- -- -- -- -- -- -- -- -- 29 -- -- -- -- -- --
    30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
    40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
    50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
    60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
    70: -- -- -- -- -- -- -- --
    The entry at 29 is the distance sensor. If you don’t see this, ensure it is plugged in.
  • If you see no output, note that this sensor can take up to a minute to initialize when you start the Python program. This is because a large chunk of code needs to be sent to the sensor. You could put prints before/after the line with vl53l5cx_ctypes.VL53L5CX() to see this time.
  • If values are way out or drifting, then ensure that the surface you are testing on is opaque. Transparent surfaces such as glass will not work so well, and highly reflective surfaces such as a phone screen can confuse the sensor.
  • Ensure you’ve removed the protective tape.

When you are done, press Ctrl + C to stop this. You may observe it needs a few times and doesn’t exit so cleanly, as it’s waiting for the underlying I2C library to do things. We’ll need to work around that later.

Now that we’ve seen the sensor working, we will make it available to MQTT so we can start using it!

Like our other robot functions, we will make this available via MQTT. MQTT will be used to control this sensor and to start broadcasting its data.

Before we build more, let’s check on the system design. Look at the following figure:

Figure 8.14 – Distance sensor system

Figure 8.14 – Distance sensor system

Figure 8.14 – Distance sensor system

The preceding figure shows our system design. It has elements from our driving system; however, some items are left out as we aren’t changing them or directly making use of them here. The Distance sensor service is designed to send its sensor data over MQTT while receiving sensor control instructions over MQTT. The Web server serves web pages. In the browser, the Distance plotting library uses JS components (such as Chart.js) to display our distance sensor data, received via MQTT, and it’s made use of in a Distance plotter page, and a Manual drive with distance page too.

The code running in the browser may still send Motor topic instructions to control the motors, so we can add a fun behavior to drive the robot while viewing from this sensor.

The service systemctl is still the underlying control for starting/stopping all services. There are also hypothetical o ther behaviors services, which could consume sensor data and control the sensor and the motors while offering up another browser view of its data. An example might be a wall-avoiding behavior, which we will build in later chapters.

Let’s start building this system!

We’ve installed a package, ujson, but are not yet using it. This can give our MQTT sensor handling code an upgrade in speed. We’ll make this upgrade in robot/common/mqtt_behaviour.py. Update the imports in this file to look like this:

import paho.mqtt.client as mqtt
import time
import ujson as json

The ujson package has the same functions as the built-in json library, so we get the speed boost without needing a new way to dump/load JSON data.

Now we are ready to get the sensor connected to MQTT.

We’ll build an MQTT service around this sensor, using the patterns we’ve seen before. The service will subscribe to a sensors/distance/control topic for messages to start and stop ranging. The service will publish sensor data on a topic, sensors/distance_mm, as a 2D array of JSON data matching the sensor geometry.

Let’s build the service in a new file, robot/distance_sensor_service.py:

import atexit
import time
import vl53l5cx_ctypes
from common.mqtt_behavior import connect, publish_json
VALID_STATUSES = (vl53l5cx_ctypes.STATUS_RANGE_VALID, vl53l5cx_ctypes.STATUS_RANGE_VALID_LARGE_PULSE)

The imports start with the familiar atexit, then time, so we can sleep where needed. We import the sensor library and then our mqtt_behavior wrapper library.

We add the constant VALID_STATUSES with a list of valid statuses so we can filter invalid sensor data out.

Let’s put our sensor service into a class. Add this into the same file:

class DistanceSensorService:
def __init__(self):
self.sensor = vl53l5cx_ctypes.VL53L5CX()
self.sensor.set_resolution(8 * 8)
self.sensor.set_ranging_frequency_hz(10)
self.is_ranging = False

The __init__ function here sets up the sensor. The resolution is the full 8 by 8, and a frequency of 10 Hz means we want data 10 times per second. We store a handle for the sensor in self.sensor. We also track whether we are ranging. Let’s add an MQTT handler for starting/stopping the sensor:

def start_ranging(self, *args):
self.sensor.start_ranging()
self.is_ranging = True
def stop_ranging(self, *args):
self.sensor.stop_ranging()
self.is_ranging = False

These handlers are simple and need no parameters, so we ignore them with *args, which consumes all parameters, making them optional. It then makes the call to the sensor start/stop ranging methods. Stopping ranging is a function we can use to stop the data ranging at any time. When we have data, our code needs to consume it and publish that over MQTT:

def update_data(self):
data = self.sensor.get_data()
as_list = list(data.distance_mm[0])
# Skip low confidence data
for n, data in enumerate(list(data.target_status[0])):
if data not in VALID_STATUSES:
as_list[n] = 3000 # max 3m.
publish_json(self.client, "sensors/distance_mm", as_list)

In this update_data method, we fetch the sensor data, specifically the distance_mm arrays. Before we can use this data, we need to convert the ctype data into list, making it easier to manipulate.

Some elements of the sensor can produce bad data if there’s too much light on them. Luckily, the sensor has a target_status array, which tells us what state each element is in. We can check each element in this list. If they are in our VALID_STATUSES list, they are good data. For anything else, we’ll substitute the long range of 3000 for 3 meters. We then publish this list as JSON to the sensors/distance_mm topic.

The next part the service needs is a main loop:

def loop_forever(self):
print("Making connection")
self.client = connect()
self.client.subscribe("sensors/distance/control/#")
self.client.subscribe("all/stop")
self.client.message_callback_add("sensors/distance/control/start_ranging", self.start_ranging)
self.client.message_callback_add("sensors/distance/control/stop_ranging", self.stop_ranging)
self.client.publish("sensors/distance/status", "ready")
self.client.message_callback_add("all/stop", self.stop_ranging)
print("Starting loop")
while True:
if self.is_ranging and self.sensor.data_ready():
self.update_data()
time.sleep(0.01)

This method creates and connects an MQTT client, stored as a self.client member to use later. Once it is connected, it subscribes to the sensor/distance/control topics, adding callbacks to the handlers above. It also connects the all/stop topic to stop the sensor ranging. It then sends a ready message, so we can see when it is running. There are some print statements to show what is going on.

The main loop checks whether there is sensor data ready, and if so, it will call the update_data method above to publish that data. There’s a tiny sleep so this loop doesn’t block. We need to finish the file by creating an instance of our class and starting its loop:

print("Initialising sensor")
service = DistanceSensorService()
atexit.register(service.stop_ranging)
service.loop_forever()

Once the distance sensor service is created, we register the stop ranging method to ensure it’s stopped when this service stops for any reason.

We need to deploy and start this sensor service. This service depends on files in robot/common, and we need to start it up. Let’s add this to deploy/deploy_services.py:

code = files.put(
name="Update distance sensor service",
src="robot/distance_sensor_service.py",
dest="robot/distance_sensor_service.py")
deploy_service("distance_sensor_service",
"robot/distance_sensor_service.py",
True, common.changed or code.changed)

I mentioned in the sensor test that the sensor library does not stop very well, which, in the systemd context, could cause problems restarting or stopping services. We can account for this in deploy/service_template.j2 with the following change:

WorkingDirectory=/home/{{ pi_user }}/
ExecStart=/home/{{ pi_user }}/robotvenv/bin/python -u {{ service_file }}
KillSignal=SIGINT
TimeoutStopSec=2

The SIGINT kill signal sends a Ctrl + C, but TimeoutStopSec means that after 2 seconds, a less graceful termination signal will be used to kill the process.

Now run pyinfra against deploy/deploy_services.py. You can SSH into the Raspberry Pi and see whether our service is running:

$ systemctl status distance_sensor_service.service
:
Active: active (running)

You can also (in the first minute or so) subscribe to see that initial ready message:

$ mosquitto_sub -u robot -P robot -t 'sensors/#' -v

You should eventually see the ready message:

sensors/distance/status ready

Leave this window open to see the data we get from the sensor. Make another SSH session to the Raspberry Pi and send the following:

$ mosquitto_pub -u robot -P robot -t sensors/distance/control/start_ranging -m ""

In the subscribed session, it should start showing sensor data:

sensors/distance_mm [172,184,201,193,3000,134,3000,3000,419,342,283,356,425,3000,3000,3000,455,494,317,475,421,282,290,281,517,541,503,536,418,322,340,317,562,556,545,539,434,375,397,334,556,539,536,534,491,494,504,411,567,534,540,529,521,519,519,426,572,553,562,544,534,543,537,494]

Alternatives for MQTT interactions are to install mqttui or mqtt-explorer on your computer and connect them to your robot. They are super useful for debugging MQTT! There’s also a curl shorthand to publish messages: curl mqtt://robot:[email protected]/ sensors/distance/control/start_ranging ‑d ""

You can stop it with this command:

$ mosquitto_pub -u robot -P robot -t sensors/distance/control/stop_ranging -m ""

You can use C trl + C to stop the mosquitto_sub process.

If you do not see any sensor data, try these steps to fix things:

  • You cannot leave robot/tests/test_distance_sensor.py running as only one program can directly control the sensor.
  • Check that your mosquitto_sub command is correct and that you’ve sent the pub message.
  • If there’s no data, you can check the service with systemctl status distance_sensor_service. This should show active (running).
  • If this is showing a failure, you can view its logs with journalctl ‑u distance_sensor_service, then press S hift + G to go to the end. This should show you why it’s not happy.
  • Verify all the code for the distance sensor service.
  • Use the previous troubleshooting steps to ensure you can detect the I2C device.

We have data, but viewing it this way isn’t very nice. Let’s make it visual.

Our phones and computers have been sending data to the robot; however, they are also quite capable of receiving data, such as sensor data, back from the robot and displaying it for the user. We’ll need a few parts to make this happen, making a visualization component, and modifying the web app to display from it.

Please note that anywhere you see learnrob3.local, you should substitute this for the hostname or IP address of your robot. Android users will need to use the IP address. See Finding your Raspberry Pi on the network section in Chapter 3*,* Preparing a Headless Raspberry Pi for a Robot.

It’s a small thing, but web servers traditionally serve HTTP on port 80. It makes our system a little more friendly to do so.

This requires a small change in deploy/deploy_services.py. Find the line that sets up the server and make the highlighted change:

deploy_service("web_server", "-m http.server --directory robot_control 80",
True, pages_changed)

Simply adding that space and port 80 will make it operate there instead of needing an extra port number every time.

Before we can see the data on the phone, we must convert this stream of numbers into something more visual. We will use Chart**.js** – a library for making charts in the JavaScript (JS) layer. We will need to subscribe and receive data, transform it, and then display it.

Raw sensor data is not great for us to visualize, so we’ll need a small pipeline of transformations to make it digestible. See the following image:

Figure 8.15 – Transforming the data for display

Figure 8.15 – Transforming the data for display

Figure 8.15 – Transforming the data for display

The top picture shows how different transformations affect the data, and how the transformations form a pipeline is shown below.

In the top-left plot, labeled Raw data, the smaller distance measurements are drowned out by the measurements in the 3000 range.

Because our sensor can produce measurements with a wide range, we will clip this to readings under 1000. This transformation makes details closer to the sensor more distinct on the display compared to those further away. We will be displaying the distances as a grayscale image on a grid, so we need to normalize it so all values are between 0 and 1. Finally, we need to orient the values into this grid.

We will animate our data as a series of image frames. MQTT isn’t suitable for streaming image frames; however, Chart.js can take the MQTT data and transform it into good visuals. We can make a library prepare our plot, and then receive data, transforming it into a form the plot can use.

Let’s build the Chart.js interface in the file robot_control/distance_chart.js. We’ll start with a convert data function, which implements the pipeline above:

function convert_data(raw_data) {
const clipped_data = raw_data.map(d => Math.min(d, 1000));
const normalised_data = clipped_data.map(d => d / 1000);
return normalised_data.map(
(data, index) => (
{
x: 8 - (index % 8 + 0.5),
y: Math.floor(index / 8) + 0.5,
distance: data
}
)
);
}

In this function, our data arrives as a JS array. Arrays in JS have a handy method, map, which, when given a transformation to apply on each item, returns a new list from all the transformations.

So, we use this to map the raw data to clipped_data, finding the smaller of each element or 1000 using the min function. Then, we normalize by dividing each item by 1000.

The next step is to map the flat list into items with an x and y coordinate and the distance value, so we can put them in a grid. The x/y coordinates are shifted by 0.5 so items will be in the middle of each grid section. We subtract x from 8 to flip it.

Chart.js works on datasets, which represent all the data you’d intend to display on a chart or plot, along with its options. Add this code:

function prepare_dataset() {
const empty = Array(64);
empty.fill(0, 0, 64);
return {
datasets: [
{
label: 'Distance',
data: convert_data(empty),
backgroundColor: function(context) {
const value = context.dataset.data[context.dataIndex].distance;
const intensity = value * 255;
return \`rgba(${intensity}, ${intensity}, ${intensity}, 100)\`;
},
}
]
};
}

This function prepares an empty dataset, ready to accept data, with a set of values at 0, and labels it Distance, which will show up in the chart. There’s then a setting for a background color for each point in our dataset.

For us to show each point as a grayscale item, we multiply the normalized distance by 255, where 255 is the brightest element. In JS, the backtick, `, symbol is used to write variables in a string.

Let’s start building the chart:

export function make_distance_chart() {
const element = document.getElementById('distance_chart');
const data = prepare_dataset();
const options = {
pointStyle: 'rect',
radius: 25,
};
const chart = new Chart(element, {
type: 'scatter',
data: data,
options: options
});
return {
update_data: function(raw_data) {
data.datasets[0].data = convert_data(raw_data);
chart.update();
}
}
}

The chart will need to be rendered somewhere on an HTML page, and like the Stop/Start buttons, it needs to find a context element to work in. We use the same getElementById for this. However, we’ve decided that where we use this chart, it will be in an element named distance_chart.

We then use our functions above to prepare an empty dataset. In the options, we will make each point a small rectangle with rect. The radius here is used for that rectangle’s size.

With the options and data, we have enough to create a chart. Since we aren’t making lines, the scatter type makes sense; however, we are overriding the color of each point and making them 25-unit rectangles.

Our distance chart then returns a data structure for controlling it. Currently, the only thing needed is an update_data function. This function is intended to be called from an MQTT handler and will result in the data being converted and the chart refreshed. We can now make use of this chart on a page.

We’ll also make buttons easier to connect as we want to start/stop our sensor. We’ve added Start buttons to the behavior path. Since we’ll frequently need a button that sends an MQTT message, let’s make a shortcut JS function for this. Open robot_control/mqtt_client.js and add the following:

export function publish_when_clicked(client, element_id, topic, data) {
document.getElementById(element_id).addEventListener("click", () => {
client.publish(topic, data);
});
}

This starts with export, making the function available for other JS code to use. It has the following parameters:

  • Client: For the MQTT client
  • element_id: Has the button ID
  • topic: The MQTT topic to publish a message on
  • data: The data to publish on that topic

The publish_when_clicked function gets the button element by its ID and sets up a click handle, which publishes the data payload to the topic.

We’ll use this in our new page.

Add the page robot_control/distance_plotter.html and start with the common HTML stuff:

<!DOCTYPE html>
<html>
<head>
<title>Robot control - Distance plotter</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Robot control - Distance plotter</h1>
<a href="index.html">Back to menu</a><br>
<button id="start">Start distance data</button>
<button id="stop">Stop distance data</button>
<div style="width: 400px; height: 400px;">
<canvas id="distance_chart" width="400" height="400"></canvas>
</div>

After the familiar buttons, we have a div containing a canvas. The div provides the space for the chart canvas, and the canvas element is where the chart will be drawn. We provide a width and height at both levels to make the output roughly square. The canvas has the id distance_chart, used to find the canvas in the make_distance_chart function.

We then need JS code to drive this. The JS code starts by importing components and connecting buttons:

<script type="module">
import 'https://cdn.jsdelivr.net/npm/chart.js';
import { connect, publish_when_clicked } from './mqtt_client.js';
import { make_distance_chart } from './distance_chart.js';
let mqttClient = connect();
publish_when_clicked(mqttClient, "start", "sensors/distance/control/start_ranging", "");
publish_when_clicked(mqttClient, "stop", "sensors/distance/control/stop_ranging", "");

The imports now start with loading the Chart.js library from the internet. You can also opt to download and place the chart in the robot libs folder (as we did for MQTT) if you prefer. Having it come from a CDN (Content Delivery Network) means it will be quick on devices that have seen this before, whereas having it come from the libs folder means it will work without you needing full internet access when running things – you still need that to deploy.

We also import the new make_distance_chart function. Let’s make our chart:

const chart = make_distance_chart(mqttClient);
mqttClient.subscribe('sensors/distance_mm');
mqttClient.on('message', (topic, message) => {
if (topic == 'sensors/distance_mm') {
const distance_data = JSON.parse(message);
chart.update_data(distance_data);
}
});

We can now store a reference to our chart in the variable chart. We then subscribe to the MQTT sensor data, and every time we get a matching message, we will decode the JSON and use the update_data function to refresh the chart with new data.

We now need to close up this HTML file:

</script>
</body>
</html>

We just need to add a link to our menu in robot_control/index.html:

<li><a href="distance_plotter.html">Distance plotter</a></li>

And we are ready to test this.

Use pyinfra with deploy_services to start this running.

We can test this by pointing a web browser to http://learnrob3.local/ with our robot’s hostname and clicking on Distance plotter and the Start button.

You should see something like the following screenshot:

Figure 8.16 – The distance sensor web display

Figure 8.16 – The distance sensor web display

Figure 8.16 – The distance sensor web display

The preceding screenshot shows a page with the data as a grayscale grid, with the image showing nearby objects as darker. It’s viewing a wall at an angle. Your display will be updating, so you can slowly wave your hand in front.

Beware of the mirror effect! Test by waving objects in front of a robot facing away. If it’s facing you, left and right will work the wrong way!

It’s probably a good idea to press the S top button when you are done.

If you aren’t seeing this update, there are a few good things to check. Remember you can use the journalctl command to see their logs. Here are more tips and refreshers for using it:

  • Ensure that with the distance sensor service running, you are able to subscribe and see a stream of sensor data.
  • Verify all code.
  • Use journalctl ‑u <servicename> to see the logs for a single service.
  • Press S hift + G to jump to the end of this log. You can also type /, then a search term, and then press E nter to search the log below your current line.
  • Use Q or C trl + C to quit.
  • You can follow a log with journalctl ‑u <servicename> ‑f.

Let’s get this into the app and on your smartphone!

You may have noticed that we are making quite a lot of HTML for each behavior. Beyond the title and a few content elements, too much of it is very similar. We have used a template for rendering the unit files for our services. We can put templates to use to reduce how much HTML is needed for each behavior. PyInfra can use a template to make this work well for us.

Create the file robot_control/page.html.j2:

<!DOCTYPE html>
<html>
<head>
<title>Robot control - {% block title %}{% endblock %}</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Robot control - {{ self.title() }}</h1>
<a href="index.html">Back to menu</a><br>
{% block content %}{% endblock %}
</body>
</html>

This is the same HTML we’ve been using but with something new. The {% block title %}{% endblock %} section will be replaced with a title from a page making use of this. There’s also {{ self.title() }}, which is needed for the second time we use the title.

Let’s update robot_control/distance plotter.html to use the template:

{% extends "robot_control/page.html.j2" %}
{% block title %}Distance plotter{% endblock %}
{% block content %}
<button id="start">Start distance data</button>
<button id="stop">Stop distance data</button>
<div style="width: 400px; height: 400px;">
<canvas id="distance_chart" width="400" height="400"></canvas>
</div>
<script type="module">
import 'https://cdn.jsdelivr.net/npm/chart.js';
import { connect, publish_when_clicked } from './mqtt_client.js';
import { make_distance_chart } from './distance_chart.js';
let mqttClient = connect();
publish_when_clicked(mqttClient, "start", "sensors/distance/control/start_ranging", "");
publish_when_clicked(mqttClient, "stop", "sensors/distance/control/stop_ranging", "");
const chart = make_distance_chart(mqttClient);
mqttClient.subscribe('sensors/distance_mm');
mqttClient.on('message', (topic, message) => {
if (topic == 'sensors/distance_mm') {
const distance_data = JSON.parse(message);
chart.update_data(distance_data);
}
});
</script>
{% endblock %}

This code starts by saying it extends the template above. Note that we must reference the template name with its full path.

The page defines a title block, with the page’s friendly name. It also defines a content block, with our start button and the JS for it.

We also need to modify our deploy/deploy_services.py to use this. At the top, in the imports, add:

import os

We will use the os library to get the contents of the robot_control folder, treating the files there as templates. In deploy_services.py, find the following lines:

code = files.sync(
name="Update web server code",
src="robot_control", dest="robot_control")
deploy_service("web_server", "-m http.server --directory robot_control 80",
True, code.changed)

And swap them all for this:

pages_folder = files.directory(
name="Create robot_control folder",
path="robot_control"
)
pages = [
files.template(
name=f"Deploy {file_name}",
src=f"robot_control/{file_name}",
dest=f"robot_control/{file_name}",
)
for file_name in os.listdir("robot_control")
]
pages_changed = pages_folder.changed or any(page.changed for page in pages)
deploy_service("web_server", "-m http.server --directory robot_control 80",
True, pages_changed)

This change will render out all files in that folder as templates. We start by ensuring we have a destination folder, as the files.template operation does not automatically create a folder.

We then loop over all the files in robot_control, using os.listdir to list its contents. For each file, we use the files.template operation.

We then check for any changes and store the result in pages_changed. Finally, we use that pages_changed result when deploying the web server service, to trigger a restart. The nice thing here is we will not need to repeat the stuff in pages.html.j2 again.

After running deploy services, test that the distance plotter still works, and then we can use these tools to build further fun pages.

Adding a distance sensor page to the driving page

Section titled “Adding a distance sensor page to the driving page”

What will be fun here is to take our manual drive page and put the chart inside it. We will need buttons to Start/Stop ranging, and in the robot_control folder, create the file drive_with_distance.html. We can use our blocks and override the headings first:

{% extends "robot_control/page.html.j2" %}
{% block title %} Manual drive with distance{% endblock %}

This page will now need elements for both the chart, buttons, and joystick in a content block:

{% block content %}
<button id="start">Start distance data</button>
<button id="stop">Stop distance data</button>
<div style="width: 400px; height: 400px;">
<canvas id="distance_chart" width="400" height="400"></canvas>
</div>
<div id="joydiv" style="width:35vh;height: 30vh;"></div>

These elements don’t yet have code, so we can add a script block combining the parts we’ve seen:

<script src="libs/joy.js"></script>
<script type="module">
import 'https://cdn.jsdelivr.net/npm/chart.js';
import { connect, publish_when_clicked } from './mqtt_client.js';
import { make_distance_chart } from './distance_chart.js';
let mqttClient = connect();
publish_when_clicked(mqttClient, "start", "sensors/distance/control/start_ranging", "");
publish_when_clicked(mqttClient, "stop", "sensors/distance/control/stop_ranging", "");
const chart = make_distance_chart(mqttClient);
mqttClient.subscribe('sensors/distance_mm');
mqttClient.on('message', (topic, message) => {
if (topic == 'sensors/distance_mm') {
const distance_data = JSON.parse(message);
chart.update_data(distance_data);
}
});
var joystick = new JoyStick(
'joydiv',
{} ,
function(stickData) {
console.log(stickData.x, stickData.y);
let speed = stickData.y / 100;
let direction = stickData.x / 100;
console.log("Speed:", speed, "Direction:", direction);
mqttClient.publish("motors/wheels", JSON.stringify(
[speed + direction, speed - direction]
));
}
);
</script>
{% endblock %}

This loads the joystick JS library, then uses a script element to load in the charts, MQTT, and button code.

It uses elements we’ve seen for the distance chart and joystick. The joystick could even be made into a component in a similar way, letting us build pages with more elements.

Finally, we need to add a link to this into robot_control/index.html:

<ul>
<li><a href="manual_drive.html">Manual drive</a></li>
<li><a href="behavior_path.html">Drive path</a></li>
<li><a href="drive_with_distance.html">Manual drive with distance</a></li>
<li><a href="power_off.html">Power off</a></li>
</ul>

We can now run pyinfra with the deploy/deploy_services.py script to deploy this and then go to the main robot site at http://learnrob3.local. Select Manual drive with distance**.** You need to press Start Ranging to see the distance sensor display:

Figure 8.17 – Screenshot of distance sensing in the phone app

Figure 8.17 – Screenshot of distance sensing in the phone app

Figure 8.17 – Screenshot of distance sensing in the phone app

The screenshot shows the distance sensor plotting page. The start and stop links will start/stop the sensor data. The grid image shows sensor data, with darker items being closer to the sensor. I am holding an object in front of the sensor.

Press the S top button before exiting the page.

You might have noticed that the updates are too slow. Even worse, motor control messages take a long time to get through.

This will cause problems later when our behaviors try to interact with the sensor and motors. The problem here is the sensor is sending a lot of data, and the I2C bus bandwidth it uses is shared with the motors. However, we can improve this a lot by increasing the I2C bus speed. Replace the file deploy/configure_pi.py with the following script:

from pyinfra.operations import files
files.line(
name="Enable I2C 1 at 400Khz",
line="[#]\?dtparam=i2c_arm=on.*",
path="/boot/firmware/config.txt",
present=True,
replace="dtparam=i2c_arm=on,i2c_arm_baudrate=400000",
_sudo=True,
)

We’re now managing the /boot/firmware/config.txt (/boot/config.txt on older Raspberry Pi OS versions) kernel parameters directly. This code will find a line dtparam=i2c_arm=on and ensure it’s not commented out while adding the high baud rate (speed) at 400 kHz. This is 4 times faster than the default 100 kHz.

Send this to the Raspberry Pi with pyinfra inventory.py deploy/configure_pi.py. Ensure you reboot when it has been completed.

You can now point your phone back at the Raspberry Pi, and the robot should now drive smoothly and have much faster sensor updates.

You’ve built a method to visualize your distance sensor data right in the phone app. This sensor combination is ready for more interesting code to control the robot autonomously.

In this chapter, we have added sensors to our robot, letting it build up a picture of the robot. We’ve seen how we can surface that sensor data over MQTT, which lets us plug in ways to consume the data.

We then built a visualization and plotting system using Chart.js to view the data, so we can see what the sensors are seeing, dealing with some of the problems with the data on the way.

In the next chapter, we will be building upon this with behaviors to consume the sensor data and avoid obstacles with it.

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

  • Try using the distance sensor to drive your robot. Can you tell where a wall is and navigate parts of your space using the sensor data only?
  • We’ve added minimal style to the pages. Could you do better? The start/stop links are small and hard to read and the graph isn’t centered.
  • Consider cable management for the sensor cable. Adhesive clips aligning the cable along the top right of the chassis will work well here.
  • Remembering to stop the sensor ranging when walking away is easy to forget. Could you add a behavior that would stop ranging on a 10-minute timer? Perhaps with “I’m still here” messages to prevent that?
  • Another idea is to use the “Last will” system in MQTT.js so that if the phone disconnects, the broker will tell the behavior to stop.
  • We’ve taken steps in this chapter to reduce repeating code. What other opportunities do you see?

Please refer to the following links for more information:

  • The Python library we are using comes from Pimoroni and has documentation at https://github.com/pimoroni/vl53l5cx-python/blob/dev/REFERENCE.md.
  • Learn more about what Chart.js can do at https://www.chartjs.org/. We will be using more chart types throughout the book.
  • You can also read a lot more about Chart.js with Learn Chart.js: Create interactive visualizations for the Web with Chart.js 2 by Helder da Rocha. This will give more insight into using HTML, CSS, and JS for visualizations.