Skip to content
ImagineWorld

Taking Your Robot Programming Skills Further

node_idnode-book_learn-robotics-programming_chapter-18-taking-your-robot-programming-skills-further
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num18
chapter_titleTaking Your Robot Programming Skills Further
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 18 — Taking Your Robot Programming Skills Further

Section titled “Chapter 18 — Taking Your Robot Programming Skills Further”

Taking Your Robot Programming Skills Further

Section titled “Taking Your Robot Programming Skills Further”

Throughout this book, you’ve learned how to plan, design, build, and program a robot using hands-on examples. By now, you should be comfortable working with this robot platform, but it is still primarily suited for lab-based use rather than real-world or competitive environments.

This is only the start of your robotics journey, with your skills and this robot having many opportunities for learning and improvement.

In this chapter, you will learn how to take your robot skills further by securing your robot, connecting with the wider robotics community, developing additional skills, and starting to plan your next robot project.

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

  • Securing your robot
  • Online robot-building communities
  • Meeting other robot builders
  • Further robot skill suggestions
  • Planning your next robot

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

  • Your robot and code from Chapter 17*,* Robot Localisation and Sensor Fusion with Python
  • Your computer with a PyInfra Python environment

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.

This robot currently stores MQTT usernames and passwords directly in code. That makes them easy to leak (through Git history) and easy to intercept on an unsecured network.

A simple first improvement is to move credentials out of the code base and load them from a configuration file that both the Python services and the web UI can read. Putting the hostname here too makes it more convenient to reuse or reconfigure.

We’re going to use a JSON file to configure the MQTT passwords for something both JavaScript and Python code can use. First, open the .gitignore file and add the following anywhere:

.env.json

This will prevent these passwords from going back into Git when you change them.

Next, we’ll create an example file for the passwords, similar to the env.js file we had in robot_control/.env.example.json:

{
"PI_HOSTNAME": "your-robot-hostname.local",
"MQTT_USERNAME": "your-mqtt-username",
"MQTT_PASSWORD": "your-mqtt-password"
}

Now make a copy of .env.example.json to robot_control/.env.json and substitute a password and username of your choice here.

We store the .env file in robot_control because the web service for the robot control pages only makes files under this folder available. Other services can then reference this file.

Let’s ensure this file is used by the Mosquitto service itself. In deploy/deploy_mqtt.py, add this to the imports section:

import json

We then need to load this file, syncing a copy to the server (so we can track if it changes). Insert this below the imports, and above the rest of the file:

with open('robot_control/.env.json') as f:
env_config = json.load(f)
mqtt_username = env_config["MQTT_USERNAME"]
mqtt_password = env_config["MQTT_PASSWORD"]
env_file = files.put(
name="Deploy MQTT environment config",
src="robot_control/.env.json",
dest="/etc/mosquitto/.env.json",
_sudo=True
)

This code loads the JSON file, decoding a username and password. It syncs that file to the /etc/mosquitto folder, which means the env_file state shows if it changed.

We now change the check for the code that sets the Mosquitto password:

if mosquitto_packages.changed or env_file.changed:

This ensures it will run the mosquitto_passwd step if the file is different.

Finally, we use this state to restart the Mosquitto service too:

if mosquitto_packages.changed or mosquitto_files.changed or env_file.changed:

This way, when we run pyinfra inventory.py ‑y deploy/deploy_mqtt.py, it will update the Mosquitto credentials and restart it. Rerunning the deployment without changes will not restart it, though.

Using the password config in the Python MQTT client

Section titled “Using the password config in the Python MQTT client”

The current MQTT client also uses hard-coded credentials. Let’s make sure the file is synced in a place Python and JavaScript can use, and that Python services are restarted. Open deploy/deploy_services.py. We will be moving the robot_control folder up to store this file there, so add this after the imports:

pages_folder = files.directory(
name="Create robot_control folder",
path="robot_control"
)
env_config = files.put(
name="Deploy environment configuration",
src="robot_control/.env.json",
dest="robot_control/.env.json"
)

Skip the deploy_service function, and after the Update common code stage, add the following to combine these states:

common_changed = common.changed or env_config.changed

This will be true if either the common code or env_config changes.

You now need to make an update throughout deploy_services – everywhere there is common.changed or code.changed, replace this with common_changed or code.changed. This is subtle – just the . becoming a _ to use our new common changed variable.

Now open robot/common/mqtt_behavior.py and, after the imports, add the following:

def load_config():
with open('robot_control/.env.json', 'r') as f:
return json.load(f)

This code opens the robot_control/env.json file, loading the JSON data from it.

We can then use this at the top of the connect function, replacing the hard-coded password:

def connect(on_connect=default_on_connect, start_loop=True):
env_config = load_config()
mqtt_username = env_config["MQTT_USERNAME"]
mqtt_password = env_config["MQTT_PASSWORD"]

This extracts the username/password from the config and uses them to make the connection. When you rerun deploy services, they will now restart using this password.

The inventor hat service came before the MQTT behavior wrappers, so we need to modify it to do so. Open robot/inventor_hat_service.py and remove the import paho.mqtt.client as mqtt line.

Now modify the import line for the client:

from common.mqtt_behavior import publish_json, connect

We can now make use of that. Find the line that starts atexit and swap the code from there to message callbacks for this:

atexit.register(exit_handler)
client = connect(on_connect=on_connect, start_loop=False)
client.message_callback_add("motors/#", all_messages)

Here, five lines of code have become a single call to the shared connect library, and can benefit from the new functionality.

There’s a change needed in robot/common/camera_core.py too. In the imports, modify the MQTT behavior import to include load_config:

from common.mqtt_behavior import publish_json, load_config

Then make the following changes to the camera_app_url function:

def camera_app_url(client, userdata, message):
config = load_config()
publish_json(client, "camera_view/url", f"http://{config["PI_HOSTNAME"]}:5001/")

This ensures the hostname matches the one in config.

Let’s make sure the web pages know how to use this too.

Using the password in the JavaScript frontend

Section titled “Using the password in the JavaScript frontend”

The last part here is making these credentials available to our robot control pages. First, you can now remove robot_control/env.js and robot_control/env.js.example as we will replace them with this JSON.

Open the robot_control/mqtt_client.js file and first remove the import {env} line. Then add the following after the file imports:

const response = await fetch('/.env.json?t=' + new Date().getTime());
let env = await response.json();

This code will load the env.json file from our robot.

Using the current datetime as a query parameter forces the browser to load a fresh copy when we load a page, a technique known as cache-busting. Without it, our pages will not reflect password changes.

The loaded data goes into the env variable, which we are already using to store this information. Run pyinfra inventory.py ‑y deploy/deploy_services.py to deploy all these changes. You will need to refresh any web page windows to ensure they pick up a new version of the mqtt_client library the first time you use this.

Everything should connect with the new MQTT password here.

This can leave services not connecting, so you need to check things are all reconnected. A good run through the robot’s functionality is merited.

  • Ensure you refresh the web page; it will have cached the old libraries.
  • Start with the manual control pages and ensure they work. If they do not, use a computer browser and the I nspect panel to look for errors.
  • Ensure you have run both the deploy_mqtt and deploy_services scripts, otherwise the two ends will mismatch.
  • If you try manual Mosquitto commands, mqttui, or other MQTT interfaces, don’t forget you’ll need to update the password you use with these.
  • Use journalctl to inspect services that aren’t behaving. A typo in mqtt_behavior.py or inventor_hat_service.py could cause this not to work.

Now the passwords are no longer hard-coded; you can choose a different password, and it should deploy throughout.

You have now moved the password from being hard-coded to an environment file. This is just the start of securing the robot. Here are areas worth considering to harden it further:

  • The launcher is a particularly powerful service – swapping the arbitrary start/stop endpoints for a fixed list would reduce the ways in which a robot could be made to run unwanted code.
  • User logins – we are still sending the .env file to anyone who visits the web pages. Adding a mechanism for the user to log in, keeping the credentials, and sending them in secure headers would mean that only an authorized user could interact with the robot.
  • We want the access to the robot to be encrypted and secure. Services such as Tailscale (http://tailscale.com/) and Cloudflare Tunnel (https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/) can help with this, or the Caddy reverse proxy (https://caddyserver.com/). The important thing is to put both the MQTT WebSocket and web pages behind an encrypted secure layer. Currently, all robot communications are in plain text and easily intercepted.

Securing a device is a deep subject, but worth researching to ensure that the robot is not a security hole in any network you put it on.

There are many places to find robot builders and robot-building advice online.

This book, and my other robotics publications, have a Discord community at https://discord.gg/aqTrUaBWjW – the Danny Staple Robotics server. We discuss different robot-building aspects, and it’s a good place to seek advice on this book.

There are websites that link to multiple social media and carry projects and tutorials for robot building.

Robot parts vendors online often have great projects blogs, along with community influence. They are also good places to learn about parts to try out:

This is just the tip of the iceberg for such communities, with us builders on BlueSky, Threads, Facebook, and LinkedIn. I’m present on all of these as OrionRobots, although I use Discord and Facebook most frequently.

There are great robotics and gadget YouTube channels other than those in the preceding communities:

  • James Bruton (https://www.youtube.com/user/jamesbruton), also known as XRobots, makes very complicated and large 3D printed robotic builds and uses them to make creations that rival the great university robots, robotic costumes with real functionality, and self-balancing walkers.
  • Computerphile (https://www.youtube.com/user/Computerphile) is a YouTube channel with great videos on programming, including aspects of robotics, visual processing, and artificial intelligence. It includes interviews with some of the significant figures still around in computing.
  • The Tested channel (https://www.youtube.com/user/testedcom) features Adam Savage from the MythBusters team, with very skilled makers doing in-depth builds and sharing their work and techniques.
  • Makezine (https://www.youtube.com/user/makemagazine) has a very tutorial-based channel and can help you get to know what is available.

These YouTube communities are good if you want to see what people are working on and see robot builders at work. There are also specific places on the internet to ask for help.

As you start to build more, meeting up with other makers is a must. First, you will gain from the experience and knowledge in the community, but there is also a great social aspect to this. Some events are free, but the larger ones will have fees associated with them.

Makerspaces are collectives for any kind of maker, be it robotics, crafting, arts, or radio specialists. They usually have tools and space to use them.

You can expect to find a collection of Computer Numerical Control (CNC) machines, such as 3D printers, laser cutters, lathes, and mills for cutting materials and drills. They also usually have a full electronics bench and many kinds of hand tools in these spaces.

Some have the materials for making Printed Circuit Boards (PCBs). Makerspaces also have a community of people to introduce to these tools, and may have courses on getting you familiar with them.

Makerspaces are a great place to learn about making and practice skills. Some, such as the Cambridge makerspace, have robot clubs. Makerspaces are also known as maker collectives, Hackerspaces, and fab labs.

There’s a global directory of these spaces at https://makerspace.com/, but it’s not comprehensive. Also, use search engines to find things close to you. Local festivals (such as a May fair) are likely to have a stand for your local makerspace.

Another place to meet face-to-face makers is at regular events.

Maker Faires (https://makerfaire.com/) are festivals of making, with people showcasing skills, projects, and products supporting building at home. They also often have makerspaces represented at them. Robotics is often featured, or even wandering around. At Makers Central in the UK, you may encounter home-built robots of all kinds, including builds of popular Sci Fi franchises realized by robot builders. These festivals may be a few hours or a whole weekend, like the British EMF Camp festival. We also have the 3D printing-oriented SMRRF event with lots of robots.

Coder Dojos (https://codeclub.org/en/coderdojo-community) are groups that meet to practice and improve their programming and, sometimes, maker skills. A Coder Dojo is a community programming workshop. Find out what groups there are locally, if any, and what they are aiming at. Becoming a mentor for kids at a Dojo is a great way to get to know other interested makers and programmers.

There are also Raspberry Jams aimed at younger builders, and Raspberry Pints, aimed at older makers. These are either tutorials or showcases of interesting things people have built, with home-built robots frequently appearing.

The BETT shows often have many robotics systems, with robots, makers, and vendors appearing. Unless you are in education, these are relatively expensive to attend.

There are robotics competitions where you will get to meet other robotics builders. FIRST robotics (https://www.firstinspires.org/) runs competitions across the world, an engineering initiative getting people to build robots and technology, then compete with them.

Most countries do have some kind of Science Technology Engineering and Mathematics (STEM) organization, such as https://www.stem.org.uk/ in the UK. They sometimes host robotics competitions, which you will be able to find out about on their websites and newsletters; be sure to see if they are open to the general public or just schools. Volunteering is a good way to get involved in these.

There are many smaller competitions, which also serve as robotic festivals and have small markets of parts too.

In the UK, the Pi Wars (https://piwars.org/) competition is run annually and involves many autonomous and manual challenges set around the Cambridge University School of Computing. It has a strong community element and is a great place to meet robot builders as a competitor, volunteer, or spectator.

Another competition is Micromouse (http://www.micromouseonline.com/), which is about maze-solving robots, though other kinds of robots are exhibited by makers.

The Robotex International (http://robotex.international) robotics exhibition is held in Estonia, combining show and tell with days of competitions and serious prizes.

If you bring robots to an event, they can be fragile. It’s worth considering steps to make them less fragile, but also how to pack the robots.

Consider a large enough box, with bubble wrap or packing foam, to safely transport your robot(s) to and from such events. I’ve found a wheeled makeup case to be great and have space for tools.

I advise that you remove the batteries to reduce the possibility of a stray wire causing a short, and pack them into a plastic bag to insulate them from any metal. Consider cable routing in robot design to reduce this possibility.

Bring a field repair kit, with wires, spare batteries, a charger, screwdrivers, replacement components, standoffs, and possibly a multimeter. Robots often need some tuning and repair when you arrive at an event.

In this section, you’ve learned about some of the places where you can meet robot makers, use tools, and find some competition. Next, let’s look at more skills you can utilize to build your robot.

The robotics journey takes you into learning many skills. One of its positives is the number of different areas you can research and use to improve your builds. Let’s take a tour of some of these skills that would really help.

The preceding communities will help you learn and practice the skills in this section. Let’s see some skill areas for you to research.

We’ve used block diagrams and simple drawings throughout this book. However, to become more serious about robot building, you’ll want to design parts or check that bought parts will integrate with your robot.

For quick designs and illustrations, tools such as Inkscape (https://inkscape.org/) and draw.io (now known as https://app.diagrams.net/) are worth getting familiar with.

You will want to create cases, chassis, sensor mounts, brackets, wheel types, and any number of parts, for which 3D Computer-Aided Design (CAD) is key. I recommend getting to know FreeCAD (https://www.freecad.org/) for this.

Once you have CAD drawings of parts, you can send them off to have them made or learn about techniques you can use to manufacture them yourself.

While the easiest parts to use are those you can buy, there’s a point where you will want to shape your own custom parts.

As a general recommendation, the MIT How To Make Almost Anything course at https://fab.cba.mit.edu/classes/MAS.863/ (updated annually) is a fantastic resource for finding ways to put things together – although they look plain, the links there are very useful. As we mentioned in the Online robot - building communities section, YouTube and other channels are rich with practical examples and hands-on tutorials when it comes to making things.

CNC milling, laser cutting, and 3D printing allow you to create solid parts and can give great results; however, each is a field of its own with skills to learn along the way:

  • Laser cutting allows you to make flat parts, but with some ingenuity, flat parts can be assembled (like so many types of furniture) into sophisticated, solid 3D objects
  • CNC milling lets you cut material from blocks, including very dense metals, for large robots needing to carry lots of weight or taking part in robot fighting competitions
  • 3D printing lets you build parts layer by layer, with the printer extruding melted materials (usually plastic), making solid and complex parts

You can also build things with hand tools, saws, drills, and templates.

All of these techniques can be used to make moulds for poured material such as rubber, low-melting-point metals, or concrete. CNC milled wood can also be used to make a buck, a mould for vacuum formed plastic where melted plastic sheets are pulled into shapes – a great way to make a cover or exterior for a robot.

If you just want the 3D printed or cut parts, there are places online that will make things for you. PCBWay and JLCPCB are well-known services that offer this globally at a low cost. You may want to find local services that can do this too.

3D printers, laser cutters, and CNC machines require routine maintenance and upkeep tasks, such as leveling a 3D print bed or tramming the CNC chuck. They also require consumables such as stock (plastic filament, wood to mill or laser cut), replacement components, and bed adhesive materials. Unless you are printing a lot, it is rarely economical to own your own when you have access to another via a makerspace or an online market.

You can dive further into materials science and mechanical connections for more interesting creations. Construction systems such as LEGO® are a good gateway to experiment with structural and mechanical systems.

Another place that can cross over between mechanical, structural, and electronics parts for robots is toy-hacking, or salvaging – the practice of taking industrially designed products such as toys and modifying them to repurpose as robot parts. I’ve used the tracked base from an RC digger or tank to build robots, where the motors, gear chains, and wheel arrangement have already been designed.

With a pointer to where you can learn how to make the structural and mechanical parts, what about the electrical parts?

Another key area of learning is electronics skills. We’ve been using the Raspberry Pi with hats and modules to build our robot. There’s a world of modules, but there’s also parts. Those modules may become bulky when we want to connect more of them or build our perfect motor driver.

Learning more about the electronic components and common circuits’ functions will help you understand your robot further, expand it, find ways to reduce its size, or eliminate problems on the robot.

Power electronics will give you a better understanding of your robot’s motor controller and battery regulation circuits. Digital electronics will let you connect other logic devices, use new sensors, or aggregate them in useful ways. Analog electronics will also open up new types of sensors and actuators and give you tools to diagnose many electrical problems that can crop up.

For this, you should learn how to draw and read schematic circuits for the common parts. Online courses and YouTube channels teach electronics step by step, with books such as Make: Electronics, by Charles Platt, giving a very hands-on learning path.

The EEV b log (https://www.eevblog.com/episodes/) channel is less step-by-step but offers more general immersion in terms of electronic engineering concerns.

There are many skills worth getting to know in this area:

  • Breadboarding: This allows you to join multiple electronics components and modules, and start practicing electronics principles. These are a very accessible way to experiment and learn.
  • Soldering: As you start to customize electronics, soldering is a key skill to work with electronic parts.
  • Electronics design: Electronics captured with schematics will help you design out how components connect, taking a block diagram and turning it into wires between devices. You can do some of this with pen and paper, or in non-specialist tools such as Inkscape and draw.io (https://app.diagrams.net/), but I recommend getting to know KiC ad. I recommend the video course KiCad Like a Pro, Peter Dalmaris.
  • Creating PCBs (p rinted circuit boards): This lets you turn designs into more professional creations, where you can control the placement of parts, connectors, and devices. This will lead you to being able to make your own sensors and HATs. It also opens up the world of miniature surface-mount components.

While it is possible to etch your own PCBs (a makerspace would help with this), there are inexpensive places that will make PCBs for you, and even do PCBA (p rinted circuit board and a ssembly service), which includes assembling many parts on it ready for use.

This book has uncovered some of the programming techniques for robotics. However, there are even more areas to dive further into and understand robotics further.

Among the most important is ROS 2 – the Robotics Operating System. This uses a number of similar principles to this book, with a shared communications bus to which all robot systems connect. ROS and the ROS community serve as an important hub for collecting robot code, for building de facto robotics standards for industry, and researching further stages. ROS can be a little complicated to get started, but rewarding as you become familiar with it. Most of the algorithms and techniques that follow likely have implementations in ROS, which can be very plug-and-play in its ecosystem.

The next thing to acknowledge is the role that machine learning is playing in robotics. Many sensor processing and other algorithms are being replaced by trained neural networks, much like we have used for face processing and voice interaction. It’s likely that any of the algorithms discussed may be replaced by an ML equivalent. Getting to know PyTorch, ONNX, TensorFlow, and the technologies used to run these will be incredibly useful, as well as higher-level systems such as ollama (ollama.com), which could be used to put an LLM (large language model) on your robot.

There is a huge world of robotics algorithms. Among the more important are SLAM (simultaneous location and mapping), a probabilistic algorithm for mapping a location and travelling through it.

I recommend the book OpenCV with Python By Example, Prateek Joshi, if you wish to continue learning about OpenCV and computer vision.

In this section, we will think about your next robot. We’ll answer questions such as the following: Why are you building your next robot? How will you plan and design it? Which new skills would you need to research and experiment with?

There are plenty of reasons to build your next robot. Every robot starts with a bit of inspiration. Perhaps there is a competition you want to try; maybe you’ve seen something such as another robot or an animal you want to mimic (crabs are fascinating!). Other inspirations may come from seeing a unique new part or wanting to learn/play with a new skill. I’ve built robots just to try out a sensor or control board I’ve received.

You may even have made a list of amazing robots you want to try to build.

Other times, it’s because you will be competing in a robot competition with specific challenges: weight, size, or cost limits. You may want to try your hand at solving a problem, building a machine that might be a robot or simply a gadget that uses the same skillset.

Each of these choices will come with constraints and trade-offs. Knowing what you will build it for, or whether you are making the robot for fun, will make initial design ideas easier. You can even keep design ideas you didn’t use for other gadgets and robots!

Now you have an idea why you want to build it, what should it look like?

Visualizing your robot – how will it look?

Section titled “Visualizing your robot – how will it look?”

When we started this book, in , Introduction to Robotics, and Chapter 2*,* Exploring Robot Building Blocks – Code and Electronics, we explored what some robots look like, along with a chassis, size, and wheel layout. You’ve explored servo motors and may even consider stepper motors too. We started the robot we built with sketches, and your new robot should start with sketches, too.

I suggest making quick drawings, and not to worry if they are rough; this is perfect at this stage. This is the time to use a pencil and paper.

Before building a robot, make a short bullet-point list of what it will do, which sensors/outputs it will have, and what it might have to deal with. This list lets you focus your efforts. Here is the list I made for my SpiderBot project, seen in Chapter 10, Using Python to Control Servo Motors:

  • It will have six legs (an insect, not really a spider)
  • I’ll use it to experiment with leg control and walking gaits
  • It will be able to avoid walls

Your quick sketches could be a six-legged walking stick figure here, with some rectangles to represent an ultrasonic distance sensor, and annotations to show what they mean.

The following figure shows my SpiderBot sketches (I love graph paper for this):

Figure 18.1 – SpiderBot sketched on paper

The preceding figure shows a sketch in pencil and ballpoint pen on graph paper, but I’ll use any paper I have. I’ll visualize from the top, making detailed pull-outs. I may have 2D profile sketches or vague 3D sketches. Here are a few tips:

  • Draw lightly, then use firmer strokes when you are more confident in a design.
  • Annotate it a lot with anything that comes to mind.
  • Don’t worry about scale, dimensioning, or perfect drawing; this is about capturing ideas. You’ll tidy up and add more detail later.
  • It is a good idea to add a working project name and date to it, even if you come up with a better name later.
  • Feel free to combine block-style representations with sketchy visual representations.
  • Keep a pen/pencil and scrap paper/notebook handy so you can jot down or sketch ideas. A whiteboard and phone photo is excellent if you have one.
  • Get big ideas down first; come back to details. It’s easy to get lost in the details of one aspect and forget other big ideas. You can always make a reminder note about it.

You can revisit this process any time in the robot build, for more ideas, problem-solving, or to refine the robot. Most ideas start with some notes and a scribbled sketch; computer drawings and refined documents come later. Get the idea down first.

It’s a good idea to start digitizing notes and collecting them in a folder. You should also make a list of the constraints you are aware of so far.

Armed with rough notes and sketches, you can formalize this with block diagrams.

In Chapter 2, Exploring R obot B uilding B locks – Code and Electronics, we looked at making block diagrams of the robot’s physical components and of the software architecture. You can represent any robot in this way.

These diagrams show blocks for inputs, outputs, and controllers, and use lines to interface them. Don’t worry about the diagram being perfect or following a system; the main point is that the picture conveys which parts you intend to connect to others. It’s quite likely this diagram will change as you build the robot and discover further constraints.

Here are two block diagram stages for SpiderBot:

Figure 18.2 – SpiderBot block diagrams

Figure 18.2 – SpiderBot block diagrams

Figure 18.2 – SpiderBot block diagrams

In the preceding figure, Panel 1 shows me identifying that I’d have a distance sensor, 3 legs on each side, and that each leg would have 3 servo motors. I also mentioned Wi-Fi so I could control this robot remotely.

In Panel 2, I’ve refined it by adding in controllers and made rough connections. I put this together using app.diagrams.net.

Any part that seems complicated may need a detailed diagram, either embedded like the leg servo motors, or referencing further diagrams.

Now that you have sketches, notes, and diagrams, you are ready to start choosing parts to build a robot.

Throughout this book, we’ve emphasized that choosing parts requires understanding the parts and the trade-offs between them. You’ll need to use constraints and trade-offs to choose sensors, chassis kits, controllers, and so on, including the time trade-off of buying parts or fabricating your own, depending on your goals. Other trade-offs are cost, weight, complexity, and availability (avoid irreplaceable parts).

SpiderBot was inspired by a hexapod kit, and you may make a robot based on or inspired by a robot arm or caterpillar track chassis. Using kits will constrain other choices you need to make – what motor sizes, power requirements, and controllers you need. SpiderBot needed to support 18 servo motors, and I had a 16-motor servo driver board available, so I elected to use that alongside the main controller, with 2 motors controlled by the main controller’s GPIO pins instead. This added software complexity.

Another SpiderBot trade-off was the main controller; I was able to use the small, cheap, and low-power ESP8266 as I didn’t need complex code, but did want Wi-Fi and to avoid adding too much weight to the chassis.

For power, those servo motors would need a lot of current, so I used a lithium polymer (LiPo) battery to power it, along with charging and protection circuits.

Before buying parts, you should test-fit them.

Robot parts can be expensive; even when they are relatively cheap, it’s still going to be frustrating to buy them and realise there’s not enough space for them.

Doing a test fit, as we did in Chapter 2, Exploring R obot B uilding B locks – Code and Electronics, is essential to check that parts will fit and where. Based on the parts you’ve considered, collect their dimensions from websites or datasheets. You can then either use dimensions (or multiples of them) in simple rectangles in drawing software, or make cardboard cutout parts, and arrange them.

Ensure you can see where they will go, and that there’s space for things such as wiring too. Is there a clear path to interfacing the choice of motor driver board with the chosen main controller?

You are now in a place to start buying robot parts. The robot/gadget part market is dynamic and volatile, but there are some vendors I’ve used for a long time:

  • Pimoroni
  • ThePiHut
  • Adafruit
  • SparkFun

You can look for stockists of Pimoroni, SparkFun, Adafruit, Cytron, Seeed Studio, Waveshare, Raspberry Pi, Espressif, Pololu, and DFRobot parts in your region to help you find the right kind of store. You might not be able to find all the parts at the same place though.

Alternatives are Amazon, Alibaba, Temu, eBay, Element14, Mouser, DigiKey, and RS. You need to be very clear about what you are buying and how much support you will get if you buy parts that are off-brand.

Parts are mostly sold online, although there are some high-street sellers of electronic modules and mechanical parts.

This is also the time to design and fabricate parts, using CAD, 3D printing, or workshop skills.

It’s also good to have an existing stock of parts, which you will build up as you make more robots and gadgets. You can also salvage modules or try your hand at toy-hacking. In this case, the test-fit diagram will help you see what you might need to alter to make things work with salvaged parts.

Now you are ready to assemble your new robot. The building guides in Chapter 5, Building Robot Basics – Wheels, Power, and Wiring, along with the preceding skills section, will get you started.

Read datasheets and documents to be clear on wiring. Take time to assemble in sections, test those combinations, and check wiring before carrying on. Avoid constructions that allow electrical shorts, and consider how you will maintain the robot if things need to change. I rarely use glue, so I can access the internals of robots to fix or upgrade them.

You may need very simple test code – move a motor gently to its extent and check that you get data from a sensor. Don’t attempt to build everything without testing.

Now that you have the parts and have started building the robot, it’s time to get more serious about its code.

In this book, we’ve built an architecture using an MQTT bus, with modular code services. It’s strongly advised to keep code modular somehow, and systems such as ROS 2 use a similar bus architecture.

We started planning our code structure in Chapter 2, Building Robot Basics – Wheels, Power, and Wiring, and we also planned each code section as we went through.

There are some main planning styles that are important here. First, think in system layers:

Figure 18.3 – Software layers

Divide code into modules and layers, then consider how the layers will communicate. The preceding diagram shows three layers:

  • At the bottom of the stack, there are v endor l ibraries. These usually come from a hardware supplier or community code. An example would be the library for communicating with the distance sensor module. This layer may include your own custom IO control code. Libraries such as OpenCV and NumPy also exist in this layer.
  • The next layer is l ibraries and middleware. We build many MQTT middleware services at this layer to control the Inventor HAT Mini for the sensors. We also have common code, such as a PID library or the MQTT service helper, at this layer. Abstractions we create here can adapt common middleware interfaces to different vendor libraries.
  • The top layer is behaviors and interfaces. These glue the lower layers, allowing you to connect sensor inputs to algorithms and build sense-think-act cycles. It’s also the layer for the robot control interfaces or dashboards.

For a smaller and simpler robot running on an Arduino or ESP8266, these layers could be simply different functions or classes in the code. As the control power and complexity increase, greater abstractions such as a shared software bus (like our MQTT bus) will help.

You will build up libraries of code for different situations that you can adapt and reuse for different robot ideas, so you don’t have to build from the ground up every time. There’s also a lot of code shared in online robotics communities that you can make use of as libraries, or as inspiration for your own code at every layer of the stack. How much you build yourself versus reuse is usually a trade-off between time and flexibility.

Another important code diagram type, for exploring complex algorithms, is a data flow diagram. We used these in Chapter 12, Encoder-Based Localisation with Python, and Chapter 17, Robot Localisation and Sensor Fusion with Python, to see how sensor data is numerically altered along with the data types involved.

Spend time here on trickier areas where the maths or data manipulation gets complicated. A good diagram will help you build the code and reason about it better if you run into trouble.

You can also consider formal diagrams such as Unified Modeling Language (UML) or flowcharts. Most diagram software has helpful libraries of diagram elements. The most important aspect of a diagram is to capture and convey the information so you can explore the concepts and understand what you meant 6 months later too.

All of the diagrams show how building smaller blocks results in a library for more complicated and interesting blocks. The straight-line behavior resulted in building blocks for path driving behavior.

You can now program your new robot, being prepared to go around loops of planning, implementing, testing, and enhancing the code and robot hardware. Do not be disheartened by testing failures, but see those as learning opportunities. Most learning is done in planning and examining test failures. If it all works the first time, there are fewer opportunities to learn how things really function. Each code section in this book represents multiple attempts to get it right; tuning is a trial-and-error process.

Testing your robot in lab conditions is OK, but the most rigorous testing happens outside, at competitions and demonstrations. You will shake out new bugs, find new problems to solve in these cases, and create a network of robot-building friends and peers. Robotics has a stereotype of being a very solitary hobby or profession, but this need not be the case, as there are plenty of people making something, so make something with them.

You’ve planned your code, and you’re now building the robot. How do you let the world know you are making something and find help?

While you build the robot, you are likely to have questions and need help. This is the right time to talk with online communities (see the preceding Online robot - building communities section).

You can then use social media to share your creation or the story of your build with others. The robotics community loves to see each other’s builds and what kind of issues they encountered. You don’t need to wait until the robot is complete; share the steps as you take them, the frustrations you encounter, and even the failures you’ve learned from. Failure situations make for some of the best stories, and can be just the right motivation for someone else to persist with a complicated build.

Use a combination of YouTube, Instructables, and online blogs to practice new skills, or find a nearby makerspace to practice new skills with others who are also making and learning.

Building with a team can be very rewarding and challenging. It will allow you to create more ambitious builds than going it alone. Getting involved in any of the communities, especially local ones, will probably represent your best chance of finding team members.

Being a robot and gadget builder will make you a lifelong student of technology; there’s always more to learn on the subject, and the boundaries are being pushed all the time. You can improve your skills and grow to mentor other robot makers. Perhaps you will come up with the kits, modules, and code to lower the barrier of entry further for the next generation of robot builders!

You’ve now reviewed how to reach out to the wider world of robot builders and find help, inspiration, and competition. You’ve seen how robotics can be a collaborative and social hobby. Perhaps you’ve also been inspired to start your own robotics blog or YouTube channel. I look forward to seeing you in our community!

You’ve now seen, throughout this book, how to build and program your first robot. In this final chapter, you saw where to find out more and how to extend your knowledge. We summarized what you’ve learned and suggested how to use this to plan, build, and program your next robot, as well as taking it on tour and being a member of the robotics community.

You saw how to design and plan a robot and how to build, program, and test a robot. You learned hardware skills such as soldering, about simple software to move a robot, and we touched lightly on complex areas such as computer vision and inertial measurements. You’ve shaken out bugs, made trade-offs, finely tuned systems, and learned how to keep backups. You’ve made user interfaces, smart behaviors, and taken control of a robot with a smartphone.

You have reached the end of this book, but I hope this is just the start of your robotics journey.

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

  1. Reach out to some of the preceding robot communities.
  2. Plan your next robot or gadget and the skills you’ll need for it.
  3. Build more gadgets and robots.
  4. Share your progress, ask for help.

The following are further practical robotics books that are available that I enjoy:

  • Python Robotics Projects, Prof. Diwakar Vaish: This book offers more Raspberry Pi and Python robotics projects for you to practice with.
  • Robot Building for Beginners, David Cook,Apress: This book leads you through building S andwich, a scratch-built robot based on a lunchbox. It is a little more maker- and electronics-based, but it is quite a fun project to follow.
  • Learning Raspberry Pi,Samarth Shah: You can dig further into what can be done with a Raspberry Pi here and find inspiration for enhancing your robots within the sections of this book.
  • Robot Builder’s Bonanza (5th Edition),Gordon McComb,McGraw-Hill Education TAB: This was an influential book and is quite extensive in terms of how to make a robot. This is the best book for going beyond buying kits and constructing bigger and more mechanically complicated robots.