Skip to content
ImagineWorld

Avoiding Obstacles with Distance Sensors

node_idnode-book_learn-robotics-programming_chapter-09-avoiding-obstacles-with-distance-sensors
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num9
chapter_titleAvoiding Obstacles with Distance Sensors
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 9 — Avoiding Obstacles with Distance Sensors

Section titled “Chapter 9 — Avoiding Obstacles with Distance Sensors”

Avoiding obstacles is a key feature in mobile robots, as bumping into stuff is generally not good. It is also a behavior that starts to make a robot appear smart, as if it is behaving intelligently. In this chapter, you will build a safe test area for your robot and turn sensor data from the distance sensor MQTT services into robot movement. You’ll see how to use the sensors for simple obstacle avoidance and then compare it with proportional control behavior.

You’ll learn about different approaches to robotics problems and what proportional behavior looks like.

We’ll cover the following topics in this chapter:

  • Making a test area for your robot
  • Building a wall-avoiding behavior
  • Visualizing wall-avoider data
  • Using proportional control

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 computer with a browser
  • 10 x A1 foamboard sheets
  • A sharp craft knife with a fresh blade
  • A metal ruler
  • A tee square
  • Wide duct tape

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.

We are going to set up autonomous behaviors for the robot. You will only control a start and stop button, and it will move itself. However, a robot under test can behave in unexpected ways, running into hazards like stairs, people, or hard walls.

Controlling the environment makes testing robots safer and easier. We can intentionally use the test space to see how behavior runs in different scenarios.

Warning: Some light conditions and surfaces, like bright sunlight through a mirror or window, will confuse this distance sensor. Soft, fuzzy, transparent, or mirrored surfaces may cause strange behavior too.

Driving the robot on a smooth surface like wood is different from driving on carpet, so the floor is another factor worth controlling. If you do not have a smooth floor, I recommend lining the arena with foamboard.

The obstacle code will work on any area, but while getting an initial behavior to run, limiting the variables will make that easier.

The designs below are inspired by Pi Wars, which is a Raspberry Pi robotics challenge competition held in the UK. They held an at-home competition in 2022, with details for arena construction rules at: https://piwars.org/2022-competition/general-rules/.

If you have limited space, a long, narrow test area is suitable, but using the techniques to make walled-off areas may help.

We are going to do the following:

  1. Choose a test area layout
  2. Choose a building material and tools
  3. Design the parts
  4. Build the test area

Let’s start by designing the test area.

The designs of test areas are going to be based upon several factors:

  • What is the test area going to test or prove? The intended usage will influence the layout of the test area. We will provide some examples for this.
  • What is the size of the robot? This will influence the size of the arena features.
  • How fast is the robot? This will again influence the size of the arena.
  • How will parts connect to each other? The connections may be suitable for different arena parts.
  • What other test areas will you have, and can you share parts between them? Thinking about this will reduce how many parts you make and how much you need to store.

It’s a good idea to make the inner distances simple metric multiples like 1.5 meters and 0.75 meters to simplify designing and building test spaces. For some tests, we will need to provide those measurements to our robot. The outer measurements will depend on your space.

Here are some example test area layouts:

Figure 9.1 – Test area layouts

Figure 9.1 – Test area layouts

Figure 9.1 – Test area layouts

The preceding figure shows the inner dimensions of three different simple arena layouts. Let’s explore why each could be useful to us:

  • Layout A is a simple 1.5 M by 1.5 M square, useful for testing how code behaves in a large area.
  • Layout B is a narrow track with long straight walls. This would prove that our avoiding code can work in long, narrow spaces.
  • Layout C is an irregular but simple shape. This could prove that the avoiding code works in a long, narrow area, as with shape B, but also has a larger space with diagonals possible. Having no rotational symmetry means we could use it for more interesting localization software in later chapters.

For this book, we will use test area C or similar, which we can use for testing in this chapter and as a reference layout in later chapters. I used the Inkscape drawing software to sketch these shapes.

Another aspect of the design is how we’ll make the boundaries. We want there to be walls, which the sensors can register, so they should be at least 100 mm high, putting them above the height of the distance sensor.

Also relevant to the design is the color. Plain colors like white or black are easier for sensors to read, and will help with later exercises.

Let’s now see what we’ll use to build this.

The material you choose depends on what you have.

I recommend foamboard because it is lightweight and easy to cut. Foamboard comes in different sizes, thickness, and colors. I recommend buying wide (over 500 mm in the smallest dimension) foamboard sheets with 10 mm thickness.

Foamboard can be marked with a pencil. You will need a try-square to get good right angles. Foamboard can be cut using a sharp craft knife and a metal straight edge. A cutting mat is recommended to avoid damaging work surfaces.

If you already have plywood, MDF, or another light, rigid material, and are comfortable with the tools for cutting it, go ahead. I do not recommend cardboard for this, as it will be damaged easily.

Now you’ve examined the building material, let’s look at how we’ll build this.

We can use the layout and the building material to design the parts we need to make for our test area.

You’ll cut walls from the sheet material and then join them with a few kinds of corners. I found that by adjusting the wall heights I used, I could cut the foam sheets into strips, and then cut the strips to the right lengths.

We’ll use right-angled corners to keep the construction simple, as shown in the following diagram:

Figure 9.2 – Joining foamboard corners

Figure 9.2 – Joining foamboard corners

Figure 9.2 – Joining foamboard corners

The preceding figure shows three types of joints we’ll use. It shows a view for assembling the part, how it looks assembled, and a top view. Note that only the corners of wall sections are shown here.

  • You can make the joint labelled (A) by cutting slots into the upper panel and lower panel. Dimension m is for the slot width, which should be the same as the material thickness. The slot height h should be half of the panel height. The parts can then slot together as Figure 9.2 shows. As material will stick out on either side, this is suitable for outside corners, with the outside material supporting the structure.
  • The joint labelled (B) is suitable for inside corners and is made by putting duct tape across the inside of the joint. Note that this joint can flex, so this needs to be between type (A) joints.
  • The joint labelled (C) is suitable for joining two panels in a straight line with duct tape. The boards will not be long enough for whole walls, so it’s quite likely they will need to be joined end to end with duct tape on one side.

Using the arena designs above and these joint types, you can now sketch out your designs, with dimensions, and consider which joints will go into which corners.

Type (A) joints also allow the panels to be rearranged, which means that although we are building test layout C, we may be able to rearrange panels into test layouts A and B. Flat pack storage of this is possible by pulling apart the slotted corners.

Here’s an example of an arena design for layout C:

Figure 9.3 – Sample arena assembly

Figure 9.3 – Sample arena assembly

Figure 9.3 – Sample arena assembly

Figure 9.3 shows a test layout C assembly, showing how each corner is constructed and where tape strips would go. Panels with the same length and corners are labelled. There are 6 similar panels labelled A. While this 3D CAD design gives clarity, a labelled biro sketch will give a similar idea of how you would build an arena.

You will then translate these into some panel cutting dimension guides. I recommend a software drawing tool for this. See the following diagram:

Figure 9.4 – Example arena parts

Figure 9.4 has scaled drawings of each of the parts that the example arena assembly in Figure 9.3 needs. As shown, the parts should have dimensions for cutting them. We have only annotated one height and one slot, because we can assume that all the panels have the same height, and the slots have the same dimensions.

Let’s see how to cut the panel parts.

Let’s use our designs to cut all the parts. Gather your tools, and find a large cutting area.

Requirements for a cutting area:

  • It should be large enough to work comfortably.
  • It should have a cutting mat to protect the surface from being damaged.
  • It should be well-lit.
  • It should be at a comfortable height, as you will make repeated cuts.

Important: At no time should your hand, arm, or any part of your body be in the path of the blade.

We start by cutting wall height strips from the sheets. The following diagram shows how:

Figure 9.5 – Cutting walls from foamboard sheets

Figure 9.5 – Cutting walls from foamboard sheets

Figure 9.5 – Cutting walls from foamboard sheets

The preceding diagram shows how to cut the walls using a foamboard sheet, a tee square, a pencil, a metal ruler, a sharp craft knife, and a cutting mat. Use the following steps:

  1. Start by marking the wall heights on the sheet so we can follow the marks. Measure carefully by using a tee square to keep them straight. I used 210 mm for the wall height. Mark clearly with pencil – you may need to come in from each side if your tee square is smaller than the sheet, as mine was.
  2. Place the foamboard sheet on a cutting mat. Note that the cutting mat may be smaller than the sheet. Always ensure the cutting mat is under the area you are cutting. Align the metal ruler with the pencil line on the foam sheet.
  3. Use the metal edge as a guide to gently score with the sharp craft knife over the pencil mark you have drawn. Repeatedly score over the same area, allowing the knife to cut a bit deeper with each pass. The wall heights do not need to be super accurate. Move the sheet along the cutting mat if you need to.
  4. Repeat this until you are through the bottom layer of paper on the foamboard.

Do not force the blade. The more time you take on this, the cleaner the cuts will be. Be patient and let later cuts follow the earlier cuts. Any tearing suggests too much pressure or that the blade needs to be changed for a sharper, fresher one.

Now that you have cut the wall height strips, we can cut panels from them using the same techniques:

  1. Mark the length of a panel on a strip. You can probably arrange the smaller panels to get more than one out of each strip. Use the pencil and tee square for this.
  2. Mark the slots and take extra care over their precision.
  3. With the foamboard on the cutting mat, repeat the process of scoring against a metal edge.

Take care cutting the slots, as they need to be somewhat more precise than the other cuts.

When you have cut the parts, make the tape hinges on the corners, as shown in F igure 9.2. You can then assemble as shown in Figure 9.3. You will then need to partially disassemble to reinforce and fold type B and C joints as shown in Figure 9.6:

Figure 9.6 – Folding and reinforcing the joints

Figure 9.6 – Folding and reinforcing the joints

Figure 9.6 – Folding and reinforcing the joints

The preceding diagram shows joint types B and C again. The top row shows each joint as it was assembled, with the original tape highlighted. Follow these steps for each:

  1. Fold the panels as shown in the F olding stage. Note that the rule for each type is that it folds into the original tape hinge.
  2. When fully folded, they should be flat like the F olded stage. The tape will cause a small gap here. Type B joints will stick out about as far as the foam thickness.
  3. The reinforced section shows where to put some new reinforcing duct tape on the outside of the joint. This should still allow them to hinge back out to the original configuration.

You can now assemble the arena. Fold the joints out and slot the panels together to make the whole arena again.

Now that we have a test arena, we can program our robot to drive autonomously in it. Let’s build an autonomous wall-avoiding behavior.

Our robot can use the distance sensor to detect walls or obstacles. We will start by dividing the sensor array into left and right regions, then build a fixed - distance avoider using b ang - bang control, changing direction based on a threshold, and choosing between two states for each motor. The robot will turn (steer) to avoid the first sensor that is too close. It will either be turning or driving straight forward.

You will need the distance sensor examples from Chapter 8*,* Programming Distance Sensors with Python, and the robot driving examples from Chapter 7*,* Driving the Robot with a Phone and Python, to both be working before starting this code.

How can a robot drive and avoid (most) obstacles? Let’s start by drawing out what we mean in Figure *9.*7:

Figure 9.7 – Obstacle avoidance basics

Figure 9.7 – Obstacle avoidance basics

Figure 9.7 – Obstacle avoidance basics

In Figure 9*.*7, a robot drives forward (A), then detects a wall (B). The robot icons have a cone in front of them showing the sensor’s field of view, with a darker bar showing it finding close objects. The robot then turns away (C) by reducing the speed or reversing one of the motors. It then keeps driving until another wall is detected (D), turns away from that, and then drives off while it’s clear (E). We can use this to make our first attempt at wall-avoiding behavior.

The following is a flow diagram for the main loop of the fixed-distance behavior:

Figure 9.8 – Obstacle avoidance flowchart

Figure 9.8 – Obstacle avoidance flowchart

Figure 9.8 – Obstacle avoidance flowchart

The flow diagram in Figure 9*.*8 describes a loop that does the following:

  1. The diagram starts in the Sense phase when distance sensor data is received.
  2. We then prepare the sensor data to make it usable.
  3. In the Think phase, the behavior starts by expecting both motors to go forward. At this point, this is an expectation; it’s not instructed to the motor.
  4. It then checks, using a threshold, if the left side is too close, and if so, sets the right motor to go backwards.
  5. If the left side is not too close, it checks if the right side is too close, and if so, sets the left motor to backwards.
  6. At the end of the Think phase, we enter the Act phase. The first act is to send the motor speeds (via MQTT).
  7. After the Act phase, the robot will now move forward, and the sensor service will send new data, with feedback from the movement. This will mean it loops around into the Sense phase.

We should also think about how this fits into the architecture of our system:

Figure 9.9 – Fixed-distance avoider architecture

Figure 9.9 – Fixed-distance avoider architecture

Figure 9.9 – Fixed-distance avoider architecture

The architecture diagram is an altered version of one we’ve previously seen; however, this time, the changed areas of the diagram are the Fixed - distance avoider we will build and a Fixed - distance avoider page in the web app. The page will use the Launcher to start/stop this avoider via s ystemctl.

The avoider will ask the Distance sensor service to start ranging and receive readings as Sensors distance in mm via MQTT. It will use those to send motor messages to the Inventor HAT service to move the robot. The Fixed - distance avoider page will display a distance chart, as we saw in Chapter 8, Programming Distance Sensors with Python, and a plot of the behavior too.

We will need to condition the data for obstacle avoiding before we can use it. If you place the robot on the floor while running the distance plotter, you will see something like this:

Figure 9.10 – The floor pixels

This is where we’ll need to consider the sensor layout and position. The lower few pixels (rows 0, 1, and 2) are picking up the floor. We need to reject some rows of this; otherwise, the robot will always be trying to avoid the floor!

We will also be dividing this sensor data into a left field and a right field, so we can avoid the closest obstacle.

Let’s start building the fixed-distance avoider. We’ll make it work and then add the visualization afterward:

  1. Create the file robot/fixed_distance_avoider.py, starting with familiar imports:
    import time
    import numpy as np
    import ujson as json
    from common.mqtt_behavior import connect, publish_json
  2. We can then create a class:
    class FixedDistanceAvoiderBehavior:
    def __init__(self):
    self.speed = 0.8
    self.threshold = 300
    Here we store a default speed of 0.8 and the fixed distance or threshold that we’ll turn at. We’ve picked 300 mm (30 cm) so the robot can act before running into an obstacle.
  3. We will be receiving MQTT messages with sensor data:
    def on_distance_message(self, client, userdata, message):
    # Sense
    sensor_data = np.array(json.loads(message.payload))
    grid = np.fliplr(sensor_data.reshape((8, 8)))
    top_lines = grid[4::]
    The sense phase of this behavior prepares the data. The first preparation is to select lines above the floor using the variable top_lines to slice the array. We select only the top 4 rows (4 to 8). Reducing the starting row to number 4 will include more of the bottom rows, showing more measurements of the floor.
  4. We then use more array slicing to get two regions for left and right:
    left_sensors = top_lines[::2]
    right_sensors = top_lines[:, -2:]
    left_distance = int(np.min(left_sensors))
    right_distance = int(np.min(right_sensors))
    The left and right regions still have many distances, so we use the np.min function on each to store the closest points (the minimum values). Because the values are numpy.int64, we need to convert that minimum to an integer with int.
  5. Publish this data, so we can debug things:
    publish_json(client, "fixed_distance_avoider/plot", {
    "left_distance": left_distance,
    "right_distance": right_distance,
    "time": time.time()
    })
    This makes our data available over MQTT, on a fixed_distance_avoider/plot topic, with the two distances and a time code.
  6. Now we’ve prepared the data, we can write the think part of our code:
    # Think
    left_motor_speed = self.speed
    right_motor_speed = self.speed
    if left_distance < self.threshold:
    right_motor_speed = -self.speed
    elif right_distance < self.threshold:
    left_motor_speed = -self.speed
    This code should look quite similar to the think portion of the flow diagram. If either side is closer than the threshold, we make the robot turn away from that side by reversing the opposing motor.
  7. Next, the code publishes this to the motors in an act section:
    # Act
    publish_json(client, "motors/wheels", [left_motor_speed, right_motor_speed])
  8. The next method is start, which will be connecting via MQTT:
    def start(self):
    client = connect(start_loop=False)
    client.subscribe("sensors/distance_mm")
    client.message_callback_add("sensors/distance_mm", self.on_distance_message)
    client.publish("sensors/distance/control/start_ranging", "")
    client.loop_forever()
    Along with connecting, we subscribe to the distance sensor data and connect that to the message handler. We then publish a message telling the distance sensor service to start sending ranging data. Currently, start will loop forever.
  9. Finally, we start this behavior running:
    behavior = FixedDistanceAvoiderBehavior()
    behavior.start()
    This finishes the file robot/fixed_distance_avoider.py.
  10. We can add this into deploy/deploy_services.py, after the distance plotter section:
    code = files.put(
    name="Update fixed distance avoider",
    src="robot/fixed_distance_avoider.py",
    dest="robot/fixed_distance_avoider.py")
    deploy_service("fixed_distance_avoider",
    "robot/fixed_distance_avoider.py",
    False, common.changed or code.changed)
  11. Run the deploy services with PyInfra to send this to the robot.

We will add a control web page, but let’s test via SSH for now:

  1. Set up a test space a few square meters wide.
  2. Ensure the robot is on battery power. Avoid reflective items like mirrors or thin obstacles such as chair legs.
  3. Use SSH to run robotpython robot/fixed_distance_avoider.py.

Warning: Avoid hard wall crashes – these can jolt the sensor! Use the test area!

The robot should start driving and avoid walls. When you are done, press Ctr l + C to stop it.

Some items that are flat or close to the floor will be in the rows we ignored, so it will not detect them. Let’s check you have this working.

If you are having trouble running the fixed-distance avoider, try these tips:

  • If the robot is turning too late and scraping the wall, adjust the speed to lower or the threshold to higher.
  • Try running journalctl ‑u distance_sensor_service.service ‑u to see the sensor logs.

This is working, but before we make more complicated behaviors, let’s add a page for it.

Let’s make a control page for this avoider with a title and start/stop buttons. We’ve created enough of a framework for this to be a small task.

Make the following changes:

  1. Create the file robot_control/fixed_distance_avoider.html and add the following:
    {% extends "robot_control/page.html.j2" %}
    {% block title %}Fixed distance avoider{% endblock %}
    {% block content %}
    <button id="start_avoider">Start avoider</button>
    <button id="stop_avoider">Stop avoider</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_avoider", "launcher/start", "fixed_distance_avoider");
    publish_when_clicked(mqttClient, "stop_avoider", "launcher/stop", "fixed_distance_avoider");
    const distance_chart = make_distance_chart(mqttClient);
    mqttClient.subscribe('sensors/distance_mm');
    mqttClient.on('message', (topic, message) => {
    if (topic == 'sensors/distance_mm') {
    distance_chart.update_data(JSON.parse(message));
    }
    });
    </script>
    {% endblock %}
    There’s a title block, then the content block begins with a start and stop button. We’ve also got the distance_chart view for the sensor we created in the previous chapter.
  2. We also need to insert a menu link for this in robot_control/index.html:
    <li><a href="drive_with_distance.html">Manual drive with distance</a></li>
    <li><a href="fixed_distance_avoider.html">Fixed distance avoider</a></li>
    <li><a href="power_off.html">Power off</a></li>
  3. Send these changes with pyinfra.

You can now run with the on/off from the web app and view the sensor data.

However, how will we visualize the behavior data with a plot?

We will be snooping on this behavior, and for more complicated behaviors, such snooping will be essential. Seeing graphs of the behavior information is essential to tune it. We will add another chart to the page to see this.

We left ourselves a debug log in the topic fixed_distance_avoider/plot, which we can use to produce our graph.

We will be using time series line graphs a lot, so we’ll make a helper for this:

  1. Create the file robot_control/chart_helper.js and add the following:
    import 'https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js';
    const options_for_timeseries = {
    scales: {
    x: { type: 'time' }
    },
    adaptors: {
    type: 'time',
    },
    responsive: true,
    };
    This code starts by importing an extension to Chart.js for interpreting dates/times. We then created a set of chart options, configuring the X axis as time. We also enabled a responsive option, which will allow the chart size to adapt on the page, making it good for mobile or desktop viewing.
  2. Just like the distance chart, we’ll need to prepare datasets. For time-series line type plots, there’s going to be a few values we track over time, so these will frequently have the same format. We can take advantage of that. This function will take a list of column names and make a dataset for them:
    function prepare_datasets(columns) {
    const data = []
    data.push(
    Object.fromEntries(columns.map(label => [label, 0]))
    );
    data[0].time = new Date().getTime();
    return {
    datasets: columns.map((label) => {
    return {
    label: label,
    data: data,
    parsing: {
    xAxisKey: "time",
    yAxisKey: label,
    }
    };
    })
    };
    }
    The code starts by creating an empty data list. It then converts the column names into a dictionary with the labels as keys, and each value containing 0. This is pushed as the first item onto the array, and we set its time to now. We then build a multiple-dataset structure around this list. Chart.js requires a dataset for each line, so we map each label to a dataset, referencing the same data, but using the parsing.yAxisKey property to specify a column key in each data item. The function returns this data structure for use in a chart.
  3. The code can now use these options to construct a chart:
    export function create_timeseries_chart(element_name, columns) {
    const chart_data = prepare_datasets(columns);
    const ctx = document.getElementById(element_name);
    const chart=new Chart(ctx, {
    type: 'line',
    data: chart_data,
    options: options_for_timeseries
    });
    return {
    update_data: (data_item) => {
    data_item.time = data_item.time * 1000;
    chart_data.datasets[0].data.push(data_item);
    chart.update();
    }
    }
    }
    The create_timeseries_chart function takes two parameters, the first being the name of an HTML canvas element to draw the chart in, and the second being the list of columns. It uses the columns to construct the chart_data structure, then fetches the canvas element. It constructs the new chart with a type of line (a Chart.js chart type as a string), using the options defined above. This will make a traditional line graph. This function then returns a data structure with an update_data function, which, like the similarly named function in the distance chart, pushes data onto our chart. We must multiply the time by 1,000, since JavaScript works in milliseconds, and Python provides times in seconds. The create_timeseries_chart function is exported so we can use it in our pages.
  4. We’ll also want a style that pairs nicely with that responsive option, by adding a line_chart class to robot_control/styles.css:
    .line_chart {
    width: 100vw;
    height: 40vh;
    position: relative;
    }
    This additional style defines the width of the line chart to be the full width of our viewport (the viewport is the visible part of our browser or phone), and its height to 40% of that. We also ensure that the position is relative to the page.

Let’s enhance our page with these new components.

We can now combine the chart_helper and line_chart CSS classes in our robot_control/fixed_distance_avoider.html page:

  1. Start by adding the chart’s new canvas. Make the highlighted change:
    <div style="width: 400px; height: 400px;">
    <canvas id="distance_chart" width="400" height="400"></canvas>
    </div>
    <div class="line_chart">
    <canvas id="plot"></canvas>
    </div>
    We now have two canvas objects, one with the distance chart, and one that is more adaptable with our style class line_chart and with the ID plot. We will be drawing our line graph there.
  2. We then need to import the new tool into our JavaScript 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';
    import { create_timeseries_chart } from './chart_helper.js';
    We have now made that chart library available for use.
  3. Let’s set up this time series chart:
    const distance_chart = make_distance_chart(mqttClient);
    const fixed_distance_chart = create_timeseries_chart('plot', ['left_distance', 'right_distance']);
    This creates the time series chart – we pass column labels that match the JSON we published above in the fixed-distance behavior.
  4. All that is left is to connect this chart to its data via MQTT. We are going to need to handle multiple message topics, so a case statement works better than an if statement here:
    mqttClient.subscribe('sensors/distance_mm');
    mqttClient.subscribe('fixed_distance_avoider/plot');
    mqttClient.on('message', (topic, message) => {
    switch (topic) {
    case 'sensors/distance_mm':
    distance_chart.update_data(JSON.parse(message));
    break;
    case 'fixed_distance_avoider/plot':
    fixed_distance_chart.update_data(JSON.parse(message));
    break;
    }
    });
    The last part of the code subscribes to the MQTT topics, then handles the messages. Depending on the topic the message came from, we decode the JSON and use it to update either of the charts.

With these changes, you should be able to send the code to the robot and get graphs showing how the sensor data is being processed into left and right sections.

We can now run the deploy services deployment again. If you reload the fixed_distance_avoider page, then click S tart avoider, you will see the distance plotter, and a graph of the left and right distances too.

Figure 9.11 – Behavior graph

Figure 9.11 – Behavior graph

Figure 9.11 – Behavior graph

This graph shows the distance in mm vs the time in seconds. You can now snoop on behaviors while they are running. You could swap the left/right distance data for the motor left/right data here too. However, mixing them on the same graph might look a bit odd as the scales are quite different.

Note that the avoider graph takes about 3-4 seconds to appear. You can use the following if you run into problems:

  1. Verify all the code.
  2. If the robot isn’t moving, check the troubleshooting steps from the previous example without the graph.
  3. If you are still unable to see a graph, use journalctl ‑u fixed_distance_avoider to see its log.
  4. Much of this is in the browser. JavaScript errors will show up by using the I nspect panel and looking in the Console tab.

You should now have a working avoider, with a neat visualization to see what the robot is doing. This avoidance works, turning away from walls, but could we use a different method to get smoother behavior?

The proportional control method is foundational in robotics. This method of control means that instead of hitting a threshold and changing, the robot will make adjustments that change proportionally with the sensor. In the case of obstacle avoiding, this would mean that the closer an object is to a sensor, the more the robot must turn.

This can be achieved by multiplying a measurement by a proportional factor. The distance measurement goes down as we get closer, so we can use 1 divided by the measurement to have a value that goes up instead, and then multiply that result.

If the output we are looking for is the turning curve speed, the core of this would be:

curve = (1 / nearest_distance*) ** proportional_factor

The following graph shows this relationship:

Figure 9.12 – The inverse distance relationship

Figure 9.12 – The inverse distance relationship

Figure 9.12 – The inverse distance relationship

This graph shows the curve above applied for distances from 70 mm through to 3000 mm. At the 1-meter dashed line, the robot is already starting to turn at a speed of 0.7. However, as the robot gets closer to 70 mm, the curve factor becomes more drastic, with 1 being the robot spinning on the spot at 70 mm. Although the graph can produce results higher than 1.0, you’ll see that we limit the curve output when applied to speeds. This graph uses a logarithmic scale for distance because changes in distance are more significant for distances closer to the robot.

The graph has a red point where the 70 mm line leads to a 1.0 curve speed. Changing that factor from 70 to higher or lower values will move the point at which the curve speed hits 1.

We have a bit of filtering to do. Let’s see how this looks in a flowchart:

Figure 9.13 – A proportional behavior

The preceding diagram shows the main part of the behavior. The first thing you will notice is that there are no decision branches (no if conditions). When distance information is received, it goes through the same P repare data step as before. However, in the T hink phase, we now have the selection of the nearest/furthest size. It then calculates the proportion and applies that to motor speeds. The Act phase then sends the motor messages, as before. The feedback is from the robot moving, thus producing new sensor data.

We can use our design, along with our previous fixed-distance avoider, to make the new behavior. Let’s see how:

  1. First, we make some copies of the fixed-distance avoider components. Make the following copies before we modify them. Copy robot/fixed_distance_avoider.py to robot/smooth_distance_avoider.py.
  2. Copy robot_control/fixed_distance_avoider.html to robot/smooth_distance_avoider.html.
  3. In deploy/deploy_services.py, add a section for this file:
    code = files.put(
    name="Update smooth distance avoider",
    src="robot/smooth_distance_avoider.py",
    dest="robot/smooth_distance_avoider.py")
    deploy_service("smooth_distance_avoider",
    "robot/smooth_distance_avoider.py",
    False, common.changed or code.changed)
  4. We can now modify those to our new needs. Open robot/smooth_distance_avoider.py. First, we modify the behavior class initialization. The highlighted sections are changed:
    class SmoothDistanceAvoiderBehavior:
    def __init__(self):
    self.speed = 0.6
    self.curve_proportion = 40
    We’ve renamed the class and replaced the threshold with curve_proportion. The speed is reduced too.
  5. In the sense section, we update the plot topic:
    publish_json(client, "smooth_distance_avoider/plot", {
  6. Now we need to change the Think part of the handler for the distance message. This replaces the whole Think section:
    # Think
    nearest_distance = min(self.left_distance, self.right_distance)
    inverse = 1/max(nearest_distance, 1)
    self.curve = self.curve_proportion * inverse
    furthest_speed = np.clip(self.speed - self.curve, -1, 1)
    nearest_speed = np.clip(self.speed + self.curve, -1, 1)
    if left_distance < self.right_distance:
    left_motor_speed = nearest_speed
    right_motor_speed = furthest_speed
    else:
    left_motor_speed = furthest_speed
    right_motor_speed = nearest_speed
    We calculated nearest_distance by taking the minimum value of either side. We then calculate the inverse, as seen in F *igure 9.*1 2. However, by taking the maximum of our distance or 1, we’ve prevented it from dividing by 0, which would be an error. The code then finds the curve by multiplying the inverse by curve_proportion. We then calculate two speeds by adding and subtracting the curve value. Because the motors cannot go outside the -1 and 1 bounds, we use the np.clip function to limit them. The next part of this is to apply these to the correct motor. This depends on which side is considered the nearest, i.e., has the lowest distance. This is a conditional, so it doesn’t exactly match our flowchart.
  7. We then need to change the bottom of the behavior to use the new named classes. Be sure to change all the highlighted code:
    behavior = SmoothDistanceAvoiderBehavior()
    behavior.start()
  8. In the HTML page, robot_control/smooth_distance_avoider.html, we can make similar changes – first, the title:
    {% block title %}Smooth distance avoider{% endblock %}
  9. Update the launcher buttons:
    publish_when_clicked(mqttClient, "start_avoider", "launcher/start", "smooth_distance_avoider");
    publish_when_clicked(mqttClient, "stop_avoider", "launcher/stop", "smooth_distance_avoider");
  10. Update the chart variable name and MQTT topic names:
    const distance_chart = make_distance_chart(mqttClient);
    const smooth_distance_chart = create_timeseries_chart('plot', ['left_distance', 'right_distance']);
    mqttClient.subscribe('sensors/distance_mm');
    mqttClient.subscribe('smooth_distance_avoider/plot');
    mqttClient.on('message', (topic, message) => {
    switch (topic) {
    case 'sensors/distance_mm':
    distance_chart.update_data(JSON.parse(message));
    break;
    case 'smooth_distance_avoider/plot':
    smooth_distance_chart.update_data(JSON.parse(message));
    break;
    }
    });
    These changes are simply about the naming of things; however, the page functions exactly the same way as the fixed-distance page.
  11. You will need to add a menu link.
  12. Then, deploy this with pyinfra, and it is ready to run.

Run the example and point it at a wall. It should turn and gently follow it.

If the robot isn’t behaving correctly, try the following:

  • Ensure you have run the pyinfra deploy commands.
  • Carefully check for typing mistakes.
  • If you are not seeing things start, use the journalctl tips above to look for tracebacks.
  • Carefully check the Python code.

This robot will be curving, sometimes wobbling, and might get stuck in corners. Is it a better wall follower than the fixed one? That depends on the context.

You should now have a working and smooth(ish) proportional wall avoider.

You will have seen the robot turn to avoid walls, and sometimes get a little confused if it gets cornered.

Try setting up a narrow lane for the robot to pass through. It will do so, but it may start oscillating as it does so. This is classic proportional overshoot behavior. We will learn how to use other factors to reduce this. Compare it with a fixed avoider, which would bounce instead of trying to follow the lane.

These two ways to approach obstacle avoidance are both valid, depending on the situation, like covering much of the room for a vacuum or following along a wall.

They are also quite simple approaches to the robot understanding where it is. We have other sensors on the robot, which we will make use of later in the book.

In this chapter, we used robot sensors for autonomous behavior. This is a major step in the robot behaving on its own and responding in some way to its environment. We built an environment for the robot to work in. We then created behaviors to avoid walls and looked at how to make a fixed-distance behavior and a smooth wall-following behavior. We looked at how to accommodate multiple visualizations and created a chart helper for further behaviors.

With this experience, you can consider how other sensors could be interfaced with your robot, and some code to interact with them. You can output data from sensors so you can debug their behavior and create a behavior to make a robot perform some simple navigation on its own.

In the next chapter, we will look at adding servo motors, letting us control and position articulated parts on the robot.

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

  • Our sensor is a little high from the ground, and close but low objects might be missed. How could we make it lower? How does that affect the data preparation?
  • Consider how you might graph other areas of our proportional behavior. Note that some values may have a very different scale from others.
  • You could attempt a version of this that uses only one side of the sensor with a proportional algorithm, trying to maintain a constant distance for a wall follower.
  • We’ve filtered the bottom lines of the sensor. Could we use those to detect edges and not drive off? Very carefully experiment with this using foam test areas only.

Please refer to the following links for more information:

  • There are many scholarly articles available on more interesting or sophisticated object-avoiding behavior. I recommend reading Simple, Real-Time Obstacle Avoidance Algorithm (https://pdfs.semanticscholar.org/519e/790c8477cfb1d1a176e220f010d5ec5b1481.pdf) for mobile robots for a more in-depth look at these behaviors.
  • Reading about proportional wall-avoiding will likely lead you to notice PID algorithms. We cover those in later parts of the book.