Setting Up Your Robot
local graph
Chapter 2 — Setting Up Your Robot
Section titled “Chapter 2 — Setting Up Your Robot”This chapter begins with some background on my thoughts on what a robot is, and what robots are made of – a fairly standard list of parts and components. This chapter aims to allow you to duplicate the exercises and use the source code that is found throughout the book. I will describe how I set up my environments for development, what tools I used to create my code, and how to install the Robotic Operating System version 2 (ROS 2). The assembly of Albert, the robot I use for all the examples, is covered in the GitHub repository for this book. There are many other types and configurations of robots that can work with the code in this book with some changes. I’ll try to provide all the shortcuts I can, including a full image of my robot’s SD card, in the Git repo.
In this chapter, we will be covering the following topics:
- Understanding the anatomy of a robot
- Introducing subsumption architecture
- A brief introduction to ROS
- Software setup: Linux, ROS 2, Jetson Nano, and Arduino
Technical requirements
Section titled “Technical requirements”To complete the practical exercises in this chapter, you will need the requirements specified in the Preface at the beginning of this book. The code for this chapter can be found at https://github.com/PacktPublishing/Artificial-Intelligence-for-Robotics-2e/.
Understanding the anatomy of a robot
Section titled “Understanding the anatomy of a robot”A robot is a machine that is capable of carrying out complex actions and behaviors by itself. Most robots are controlled by a computer or digital programmable device. Some key characteristics of robots are as follows:
- Automation: Robots can operate automatically without direct human input, based on their programming. This allows them to do repetitive or dangerous tasks consistently.
- Sensors: Robots use sensors such as cameras, optics, lidar, and pressure sensors to gather information about their environment so they can navigate and interact. This sensory information is processed to determine what actions the robot should take.
- Programming: A robot’s brain consists of an onboard computer or device that runs code and algorithms that define how it will behave. Robots are programmed by humans to perform desired behaviors.
- Movement: Most robots are able to move around to some degree through wheels, legs, propellers, or other locomotion systems. This allows them to travel through environments to perform tasks.
- Interaction: Advanced robots can communicate with humans through voice, visual displays, lights, sounds, physical gestures, and more. This allows useful human-robot interaction and work.
- Autonomy: While robots are programmed by humans, they have a degree of self-governance and independence in how they meet their objectives. The ability to take action and make decisions without human oversight is their autonomy.
In summary, a robot integrates automation, sensing, movement, programming, and autonomy to reliably carry out jobs that may be complex, repetitive, unsafe, or otherwise unsuitable for humans. They come in many shapes and sizes, from industrial robotic arms to social companion robots to autonomous self-driving cars.
There is a fairly standard collection of components and parts that make up the vast majority of robots. Even robots as outwardly different as a self-driving car, the welding robot that built the car, and a Roomba vacuum cleaner have a lot of the same components or parts. Some will have more, and some will have less, but most mobile robots will have the following categories of parts:

Figure 2.1 – Block diagram of a typical mobile robot
Let’s look at these components in greater detail:
- Computer: A unit that runs the programming that controls the robot. This can be a traditional computer, a microcontroller, a single board computer (SBC) like we have, or some other sort of processor that sends and receives commands. Robot arms and some types of industrial robots will use a Programmable Logic Controller (PLC), which is a special type of controller that applies logic (AND, OR, NOT) to various inputs to produce an output. For a computer to send commands to the robot and receive telemetry, we’ll need some sort of sensor interface, such as a USB port, serial port, General Purpose Input/Output (GPIO) port, or a network interface such as Ethernet or Wi-Fi.
- Control Station or Human/Robot Interface (HRI): Robots are designed to perform tasks, which requires that the operator must have some means to send and receive data from the robot and to supervise that the robot is behaving correctly. We will be using a laptop or desktop computer for this function, and we will talk to the robot via a wireless network. Our control station sends commands to the robot and receives telemetry from the robot in the form of data, video, or audio.
- Radio or Data Link: Mobile robots such as the one we are designing in this book are capable of moving and exploring their environment. While it is possible to send commands to a robot over a tether or wire, the preferred way is to use a radio link. The ubiquitous availability of wireless networks such as Wi-Fi and cellular data services has made creating data links a lot easier. I have had a lot of robot projects where a network link was unavailable or impractical, and a custom radio solution needed to be devised. Other types of radio used in robots include Bluetooth, Zigbee, and various mesh network systems, such as Flutter.
- Motors or Effectors: Our definition of a robot includes the ability for self-propulsion; that is, the robot is able to move. In order to move, the robot needs a motor or set of motors. Our robot, Albert, has ten motors, four for driving and six to control the robot arm and hand. Motors convert electricity into motion. There are many different types, and picking the right motor is a challenge. You must match the torque (how hard the motor can pull), the speed of the motor shaft in revolutions per minute, and voltage. Here are some key factors to consider when selecting a motor for a robot drive system:
- Torque: Consider the torque required for your robot’s movements and payload handling. More torque allows faster acceleration and the ability to handle heavier loads. If there is insufficient torque, the robot will “bog down” or stall the motor. An electric motor pulls the most current when it is stalled (it is energized but not moving). All that power going nowhere gets turned into heat, which will eventually melt the wires or cause a fire.
- Speed: Determine the speeds your robot needs to operate at. Higher speeds require motors with higher RPM ratings. We only want our robot to go at a modest rate. The toys can’t get away.
- Duty cycle: Choose a motor that can run continuously for the robot’s required duty cycle without overheating. Intermittent duty cycles allow smaller, lighter motors. We will be driving or moving quite a bit – about 50% of the time, but not too fast.
- Size and weight: Large, heavy-duty motors provide a lot of power but may constrain robot design. Consider the full drive system size and weight. Remember the motor also has to move itself.
- Control: Brushless DC motors require electronic speed controllers. Stepper motors allow open-loop position control. Servomotors, such as the ones in the robot’s arm, have integrated encoders and are controlled by a serial interface. The drive motors I used are brushed motors, which are controlled by varying the voltage, which we control with Pulse Width Modulation (PWM).
- Voltage: High voltages allow more power in small motors. Select a voltage that is compatible with other electronics. My battery is 7.2 volts, which matches the motors selected.
- Noise: Quiet motors may be required for home/office robots. Brushless, gear-reduced motors are quiet but expensive. Geared drivetrains are also noisy.
- Cost: More powerful motors cost more. Balance performance needs with budget constraints. Albert’s brushed motors are very inexpensive. Some robot motors also feature gearboxes to reduce the motor speed, basically exchanging speed for torque. Albert’s electric motors have reduction gearboxes that let the motor run at a faster speed than the wheels. There are many ways to provide motion to a robot. We call these things that make the robot move effectors. Effectors are only limited by your imagination, and include pneumatics (things actuated by compressed air), hydraulics (things actuated by incompressible fluid), linear actuators (things that convert rotary motion into linear motion), revolving joints or revolute joints (angular joints like an elbow) and even exotic effectors such as shape-memory alloy or piezoelectric crystals, which change shape when electricity is applied.
- Torque: Consider the torque required for your robot’s movements and payload handling. More torque allows faster acceleration and the ability to handle heavier loads. If there is insufficient torque, the robot will “bog down” or stall the motor. An electric motor pulls the most current when it is stalled (it is energized but not moving). All that power going nowhere gets turned into heat, which will eventually melt the wires or cause a fire.
- Servos: Some of the motors in our robot are a special category of motors called servos. Servo motors feature a feedback mechanism and a control loop, either to maintain a position or a speed. The feedback is provided by some sort of sensor. The servos we are using consist of a small electric motor that drives a gearbox made up of a series of gears that reduce the speed and consequently increase the torque of the motor. The sensor used in our case is a potentiometer (variable resistor) that can measure the angle of the output gear shaft. When we send a command to the servo, it tells the motor to be set to a particular angle. The angle is measured by the sensor, and any difference between the motor’s position and the sensor creates an error signal that moves the motor in the correct direction. You can hear the motor making a lot of noise because the motor turns many times through seven reduction gears to make the arm move. The gearbox lets us get a lot of torque without drawing a lot of current.
Figure 2*.2* shows how a servo motor is controlled using Pulse Position Modulation (PPM). To control a servo, you must generate a pulse of a specific width:

Figure 2.2 – Servo motor control is via PPM signals
A short pulse moves the servo to the beginning of its range. A medium pulse (1,500 microseconds) is the center of the servo’s position. A late pulse causes the servo motor to go to the end of its range. The robot arm I use in this version of my robot has a servo controller that comes with the arm hardware. We will be controlling the robot arm via serial commands to this controller in Chapter 5.
- Motor Controller or Electronic Speed Control: Motors are not very useful by themselves – you need the ability to convert commands from the control computer into motion from the motors. Since motors need more voltage and more current than the control computer (our Jetson Nano) can provide, we need a device to turn small digital signals into large analog voltage and current. This device is called a motor controller. This controller I had to purchase separately, and is composed of two parts – an Arduino Uno and a motor controller shield that is attached:

Figure 2.3 – Motor controller shield I used for Albert
As shown in the image, the four motor wires are attached to the lettered connections.
- Since we have a tank-drive robot (we steer by running the motors at different speeds, also called differential drive), we also need the motors to be able to run forward or backward. The motor controller takes a special input signal called a Pulse Width Modulation (PWM). PWM is a repeating signal where the voltage turns on and off. The motor throttle (how fast the motor turns) is proportional to the amount the PWM signal stays in the ON position.
The motor controller has several kinds of connections, and has to be wired carefully due to the high voltages and currents provided. This can be done by performing the following steps:
- There are two control wire inputs – one for speed (the PWM signal) and the other is a direction signal. We put the motor in reverse by changing the direction signal – 1 is forward, and 0 is backward.
- The next thing we need is a ground – it is very important that the controller sending the PWM signal (in our case, it is the Ardunio Mega) and the motor control have their ground lines connected.
- Next, the motor controller needs the motor voltage and current, which we get directly from our battery.
- Finally, we connect two wires from each motor to the controller. It is interesting that we don’t care which wire goes to which side of the motor, since we can run both forward and backward. If the motor is turning the wrong way, just switch the two wires. This is the only time you get to say just reverse the polarity outside of a science fiction movie. We will be covering the specific wiring for the example robot – Albert – in the online appendix.
- There are two control wire inputs – one for speed (the PWM signal) and the other is a direction signal. We put the motor in reverse by changing the direction signal – 1 is forward, and 0 is backward.
- Sensors: In order for the robot, which is a machine that can move and react to its environment, to be able to see its surroundings, it needs sensors. Sensors take information from the outside or inside of the robot and convert it into a digital form. If we use a digital camera sensor, it takes light and turns it into digital pixels (picture elements), recorded as an array of numbers. A sonar sensor measures the distance to an object, such as a wall, by sending a pulse of energy (sound waves) and listening for the time delay before hearing an echo. Measuring the time delay gives us the distance to an object, since the speed of sound is fairly constant. For our Albert project, the robot has several types of sensors:
- Our primary sensor is a wide-angle video camera, which we will use for avoiding obstacles and detecting objects.
- We will also use a microphone to listen for sounds and perform speech recognition.
- We mentioned servo motors earlier in this list – each servo motor contains an angle sensor that detects the amount of rotation and allows us to direct the robot arm and hand.
- We have our Emergency Stop button, which is wired to the Arduino, and is a type of tactile (touch) sensor. When the button is pressed, a signal is sent that the robot can interpret as a stop command.
- The robot arm I chose has a handy voltage monitor that we will use to keep track of the battery life (charge) remaining.
- Our primary sensor is a wide-angle video camera, which we will use for avoiding obstacles and detecting objects.
In the next section, we will discuss robot software architectures, which act as a framework for the autonomy behaviors we will be creating.
Introducing subsumption architecture
Section titled “Introducing subsumption architecture”At this point, I want to spend a bit of time on the idea behind the subsumption architecture, and point out some specifics of how we will be using this concept in the design of our robot project. Many of you will be familiar with the concept from school or from study, so you can look at my diagram and then move on. For the rest of us, let’s talk a bit about this biologically inspired robot concept.
Subsumption architecture was originally described by Dr. Rodney Brooks, a professor at MIT, who would later help found iRobot Corporation and invent the Baxter robot. Rodney was trying to develop analogs of insect brains in order to understand how to program intelligent robots. Robots before this time (1986) were very much single-threaded machines that pretty much only did one thing at a time. They read sensors, made decisions, and then acted – and only had one goal at any one time. Creatures such as flies or ants have very simple brains but still manage to function in the real world. Brooks reasoned that there were several layers of closed-loop feedback processes going simultaneously.
The basic concept of subsumption has been around for some time, and it has been adapted, reused, refined, and simplified in the years since it was first introduced. What I am presenting here is my interpretation of how to apply the concept of subsumption to a robot in the context of what we are trying to accomplish.
The first aspect to understand is that we want our robot to act on a series of goals. The robot is not simply reacting to each stimulus in total isolation, but is rather carrying out some sort of goal-oriented behavior. The goal may be to pick up a toy or navigate the room, avoiding obstacles. The paradigm we are creating has the user set goals for the robot and the robot determines how to carry those goals out, even if the goal is simply to move one meter forward.
The problem begins when the robot has to keep more than one goal in mind at a time. The robot is not just driving around, but driving around avoiding obstacles and looking for toys to pick up. How do we arbitrate between different goals, to determine which one has precedence? The answer is found in the following diagram:

Figure 2.4 – An example subsumption architecture
We will divide the robot’s decision-making systems into three layers, each of which has a different level of responsibility and operates on a different time scale.
At the lowest levels are what we might call the robot’s autonomic nervous system – it contains the robot’s internal health-keeping and monitoring functions. These processes run very fast – 20 times a second or so, or 20 hertz (Hz), and only deal with what is inside the robot. This includes reading internal sensors, checking battery levels, and reading and responding to heartbeat messages. I’ve labeled this level Take Care of Myself.
Important note
What is a heartbeat message? Once a second, I have the control station send a special heartbeat message to the robot, which has a time tag down to the millisecond, which is the clock time of the host computer. This goes to the control computer and repeats the heartbeat message back to the host. We can see the delay in our message – our command latency – by comparing the time tags. We want to see a less than 25 milliseconds round trip for the heartbeat. If the onboard computer is not working or is locked up, then the time tag won’t come back and we know the robot is having problems.
The next level handles individual tasks, such as driving around or looking for toys. These tasks are short-term and deal with what the sensors can see. The time period for decisions is in the second range, so these tasks might have 1 or 2 Hz update rates, but slower than the internal checks. I call this level Complete the Task – you might call it Drive the Vehicle or Operate the Payload.
The final and top level is the section devoted to completing the mission, and it deals with the overall purpose of the robot. This level has the overall state machine for finding toys, picking them up, and then putting them away, which is the mission of this robot. This level also deals with interacting with humans and responding to commands. The top level works on tasks that take minutes, or even hours, to complete.
The rules of the subsumption architecture – and even where it gets its name – have to do with the priority and interaction of the processes in these layers. The rules are as follows (and this is my version):
- Each layer can only talk to the layers next to it. The top layer talks only to the middle layer, and the bottom layer also talks only to the middle layer. The middle layer can communicate with both the top and the bottom layer.
- The layer with the lower level has the highest priority. The lower level has the ability to interrupt or override the commands from higher layers.
Think about this for a minute. I’ve given you an example of driving our robot in a room. The lowest level detects obstacles. The middle level is driving the robot in a particular direction, and the top layer is directing the mission. From the top down, the uppermost layer is commanded to clean up the room, the middle layer is commanded to drive around, and the bottom layer gets the command left motor and right motor forward 60% throttle. Now, the bottom level detects an obstacle. It interrupts the drive around function and overrides the command from the top layer to turn the robot away from the obstacle. Once the obstacle is cleared, the lowest layer returns control to the middle layer for the driving direction.
Another example could be if the lowest layer loses the heartbeat signal, which indicates that something has gone wrong with the software or hardware. The lowest layer causes the motors to halt, overriding any commands from the upper layers. It does not matter what they want; the robot has a fault and needs to stop. This priority inversion of the lowest layers having the highest priority is the reason we call this a subsumption architecture, since the higher layers subsume – incorporate – the functions of the lower layers to perform their tasks.
The major benefit of this type of organization is that it keeps procedures clear as to which events, faults, or commands take precedence over others, and prevents the robot from getting stuck in an indecision loop.
Each type of robot may have different numbers of layers in their architecture. You could even have a supervisory layer that controls a number of other robots and has goals for the robots as a team. The most I have had so far has been five, used in one of my self-driving car projects.
Now let’s take a look at one of the most important concepts you’ll need in this book – ROS.
A brief introduction to ROS
Section titled “A brief introduction to ROS”OK, before we do all of the work described in the following section to be able to use ROS 2 – the second version of the Robotic Operating System – let’s answer your questions. What is ROS, and what are its advantages?
The first thing to know is that ROS is not an actual operating system, such as Linux or Windows. Rather it is a middleware layer that serves as a means of connecting different programs to work together to control a robot. It was originally designed to run Willow Garage’s PR2 robot, which was complex indeed. ROS is supported by a very large open source community and is constantly updated.
I used to be a ROS skeptic, and frankly, reading the documentation did not help my first impression that it was cumbersome at best and difficult to use. However, at the insistence of one of my business partners, we started using ROS for a very complex self-guided security guard robot called RAMSEE, designed for Gamma 2 Robotics:

Figure 2.5 – RAMSEE, the security guard robot, designed by the author
I quickly realized that while the initial learning curve with ROS was steep, the payoff was the ability to create and implement modular, easily portable services that could be developed independently. I did not need to combine everything into one program, or even in one CPU. I could take advantage of my multi-core computers to run independent processes, or even have more than one computer and move things freely from one to the other. RAMSEE has one computer with eight cores and another with four.
Important note
ROS can be described as a Modular Open System Software (MOSA). It provides a standard interface to allow programs to talk to one another through a Publish-Subscribe paradigm. This means that one program publishes data, making it available to other programs. The programs that need this subscribe to that data and are sent a message whenever new data is available. This lets us develop programs independently and create standardized interfaces between programs. It really makes creating robots much easier and far more flexible.
The other major advantage, and worth all the bother, is that ROS has a very large library of ready-to-go interfaces for sensors, motors, drivers, and effectors, as well as every imaginable type of robot navigation and control tool. For example, we will be using the OAK-D 3D depth camera, which has a ROS 2 driver available at https://github.com/luxonis/depthai-ros.
The RViz2 tool provides visualization of all of your sensor data, as well as showing the localization and navigation process. I greatly appreciated the logging and debugging tools included in ROS. You can log data – anything that crosses the publish/subscribe interface – to a ROSBag and play it back later to test your code without the robot being attached, which is very useful.
The following illustration below shows the output given by RViz2, showing a map being drawn by one of my robots:

Figure 2.6 – ROS RViz allows you to see what the robot sees, in this case, a map of a warehouse
Since this is the second edition of the book, we will be using ROS 2, the new and improved version of ROS. One of the most frustrating things about the old ROS was the use of ROSCORE, a traffic cop that connected all of the parts of the robot via the network. That is now gone, and the various components can find each other via a different sort of service, called Distributed Data Services (DDS). We will also need to use Python 3 instead of Python 2 for our code since Python 2 has been discontinued and is no longer supported.
Hardware and software setup
Section titled “Hardware and software setup”To match the examples in this book, and to have access to the same tools that are used in the code samples, you will have to set up three environments:
- A laptop or desktop computer: This will run our control panel, and also be used to train neural networks. I used a Windows 10 computer with Oracle VirtualBox supporting a virtual machine running Ubuntu 20.04. You may run a computer running Ubuntu or another Linux operating system by itself (without Windows) if you want. Several of the AI packages we will use in the tutorial sections of the book will require Ubuntu to run. We will load ROS 2 on this computer. I will also be using a PlayStation game controller on this computer for teleoperation (remote control) of the robot when we teach the robot how to navigate. I also have ROS 2 for Windows installed, which may obviate running the virtual machine. Either approach will work, since the Python programs we will use for control run in either mode.
- Nvidia Jetson Nano 8GB: This also runs Ubuntu Linux 20.04 (you can also run other Linux versions, but you will have to make any adjustments between those versions yourself). The Nano also runs ROS 2. We will cover the additional libraries we need in the following sub-sections.
- Arduino Mega 256: We need to be able to create code for the Arduino. I’m using the regular Arduino IDE from the Arduino website. It can be run on Windows or Linux. We will be using the Arduino to control the motors on the robot base and drive it around. It also gives us a lot of expansion to add additional controls, such as an emergency stop button.
Preparing the laptop
Section titled “Preparing the laptop”You will need to install ROS 2 for Windows for the robot control software to work. To do this, you can follow the instructions provided at https://docs.ros.org/en/foxy/Installation/Windows-Install-Binary.html.
I also used Virtual Network Computing (VNC) to talk to my Nano from the laptop, which saves a lot of time and fiddling with cables and keyboards. Otherwise, you would need to connect the Nano to a monitor, keyboard, and mouse to be able to work on your code that is on the robot. I used RealVNC, which can be found at https://www.realvnc.com/en/. You can also use UltraVNC, which is free software.
Installing Python
Section titled “Installing Python”The Linux Ubuntu system will come with a default version of Python. I am going to assume that you are familiar with Python, as we will be using it throughout the book. If you need help with Python,
Once you log on to your virtual machine, check which version of Python you have by opening a terminal window and typing python in the command prompt. You should see the Python version, like this:
>pythonPython 3.8.16 (default, Jan 17 2023, 22:25:28) [MSC v.1916 64 bit (AMD64)]You can see that I have version 3.8.16 in this case.
We are going to need several add-on libraries that add on to Python and extend its capabilities. The first thing to check is to see if you have pip installed. This is the Python Installation Package (PIP) that loads other packages from the internet to extend Python. Check to see if you have pip by typing in the following:
pipIf you get the output No command 'pip' found, then you need to install Pip. Enter the following:
sudo apt-get install python-pip python-dev build-essentialsudo pip install --upgrade pipNow we can install the rest of the packages we need. As a start, we need the Python math packages numpy, the scientific Python library scipy, and the math plotting library matplotlib. Let’s install them:
sudo apt-get install python-numpy python-scipy python-matplotlib python-sympyI’ll cover the other Python libraries we will use later (OpenCV, scikit-learn, Keras, etc.) as we need them in the appropriate chapters.
Setting up Nvidia Jetson Nano
Section titled “Setting up Nvidia Jetson Nano”For this setup, we will use an image to run Ubuntu 20.04 on our Jetson Nano, which is required for ROS 2. One source for this version is https://github.com/Qengineering/Jetson-Nano-Ubuntu-20-image.
The basic steps, which you can follow in the Git repo, are as follows:
- The first step is to prepare an SD card with the operating system image on it. I used Imager, but there are several programs available that will do the job. You need an SD card with at least 32 GB of space – and keep in mind you are erasing the SD card in this process. This means that you need a card greater than 32 GB to start with – I used a 64 GB SD card as a 32 GB SD card did not work, contrary to the instructions provided on the website.
- Follow the directions with your SD card – the Jetson Nano Ubuntu website (https://github.com/jetsonhacks/installROS2) advises us to use a Class 10 memory card with 64 GB of space. Put the SD card in your reader and start up your disk imager program. Double (and triple) check that you pick the right drive letter – you are erasing the disk in that drive. Select the disk image you downloaded. Hit the Write button and let the formatter create your disk image on the SD card:

Figure 2.7 – Imager program to write out disk images on SD cards
- You can follow the usual setup for setting up your language and keyboard, as well as setting up the network. I like to use a static IP address for the robot since we will be using it a lot.
- It is always a good idea to set a new user ID and change the default passwords.
Now let’s look at how we can install ROS 2.
Installing ROS 2
Section titled “Installing ROS 2”We need to install ROS 2 on the Jetson Nano. I used the Foxy version on my machine. You can follow the instructions at this link: https://github.com/Razany98/ROS-2-installation-on-Jetson-Nano.
You will have to set up the sources and point your computer at the ROS 2 repository. To do this, follow these steps:
- Set
localeusing thelocalesudo apt update && sudo apt install localessudo locale-gen en_US en_US.UTF-8sudo update-locale LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8export LANG=en_US.UTF-8locale - Set up the source repository
apt-cache policy | grep universe orsudo apt install software-properties-commonsudo add-apt-repository universesudo apt update && sudo apt install curl gnupg2 lsb-releasesudo curl -sSL https://raw.githubusercontent.com/ros/rosdistro/master/ros.key -o /usr/share/keyrings/ros-archive-keyring.gpgecho "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/ros-archive-keyring.gpg] http://packages.ros.org/ros2/ubuntu $(source /etc/os-release && echo $UBUNTU_CODENAME) main" | sudo tee /etc/apt/sources.list.d/ros2.list > /dev/null
- Install the
sudo apt updatesudo apt upgradesudo apt install ros-foxy-desktopsudo apt install ros-foxy-ros-base
- Set up
source /opt/ros/foxy/setup.bash
- Once you are done, you can check that your installation comepleted correctly by typing in
ros2 topic listros2 node list
Before we proceed, let’s take a look at how exactly ROS works.
Understanding how ROS works
Section titled “Understanding how ROS works”You can think of ROS as a type of middleware that works to connect different programs together. It provides Interprocess Communications (IPC) between programs so we don’t have to put all of our functions in one big block of code – we can distribute our robot’s capabilities and develop them independently.
Each individual part of a ROS robot control system is called a node. A node is a single-purpose programming module. We will have nodes that collect camera images, perform object recognition, or control the robot arm. With ROS, we can isolate these functions and develop and test them independently.
The various nodes (programs) talk to one another via topics. A topic is generally used to publish data for other nodes to use. ROS 2 uses a publish/subscribe mode to move information around the robot. For example, our camera software node takes images and then publishes that information on a topic called /image_raw. This standard message type includes data about the image format, as well as the image itself. We also publish camera data on the /camera_info topic, using the sensor_msgs/CameraInfo format, which is described in the following image:

Figure 2.8 – ROS 2 nodes, topics, and message types
The /camera_info topic has a lot of valuable information about the image, or frame, including the timestamp the data was collected and the frame number. It also provides calibration information to help us understand the geometry of the captured image, which we can use to map pixels to the 3D space around the robot.
There is generally an existing or ROS standard message format for whatever you need to convey between components. I like to use the generic string (std_msgs/String) on a topic called RobotCmd to send general commands, such as mode changes, to the robot from a control application.
ROS 2 allows us to set parameters externally to the node (program). Each node can have its own list of parameters, and we can set parameters at any time. These are generally configuration commands that we set once and make our programs more generic and modular. For example, we may have a parameter for the robot arm that locks the rotation base, so that the arm can only be in front of the camera. We can create a parameter called arm_base_lock, define it as a Boolean, and use the following command:
ros2 param set /robot_arm arm_base_lock trueThis will turn the rotation lock on. Then we can check this setting with this:
ros2 param get /robot_arm arm_base_lockWe get the following reply:
Boolean value is trueSince our robot will be composed of a number of nodes (programs) that all have to be started together, ROS 2 provides the concept of a launch file that lets us start all of our programs with one command. In ROS 1, launch files were built in YAML format. YAML stands for Yet Another Markup Language. In ROS 2 we can use YAML, Python, or eXtensible Markup Language (XML) to define a launch file. I’m used to creating files in YAML format, so we will stick to that. In our launch file, we can start nodes, change parameters, and create namespaces if we need to launch multiple copies of a node (for instance, if we had three cameras).
Virtual Network Computing
Section titled “Virtual Network Computing”One tool that I have added to my Jetson Nano is Virtual Network Computing (VNC). This utility, if you are not familiar with it, allows you to see and work with the Nano desktop as if you were connected to it using a keyboard, a mouse, and a monitor. Since the Nano is physically installed inside the robot that travels by itself, attaching a keyboard, mouse, and monitor is not often convenient (or possible). There are many different versions of VNC, which is a standard protocol used amongst many Unix – and non-Unix – operating systems. The one I used is called Vino. You need two parts: the server and the client. The server runs on the Nano and basically copies all of the pixels appearing on the screen and sends them out to the Ethernet port. The client catches all of this data and displays it to you on another computer. Let’s install the VNC server using the steps on this webpage: https://developer.nvidia.com/embedded/learn/tutorials/vnc-setup.
Load the viewer on your Windows PC, or Linux virtual machine, or do like I did, and load VNC on your Apple iPad. You will find the ability to log directly into the robot and use the desktop tools to be very helpful.
Important note
In order to get VNC to run on the Nano without a monitor attached, you must set the Nano to automatically log itself on. You can edit the /etc/gdm3/custom.conf file to enable automatic login:
# Enabling automatic login
AutomaticLoginEnable=true
AutomaticLogin=[your username]
Setting up the colcon workspace
Section titled “Setting up the colcon workspace”We will need a colcon workspace on your development machine—laptop or desktop—as well as on the Jetson Nano. Follow the instructions at https://docs.ros.org/en/foxy/Tutorials/Beginner-Client-Libraries/Colcon-Tutorial.html.
If you are already a user of ROS, then you know what a workspace is, and how it is used to create packages that can be used and deployed as a unit. We are going to keep all of our programs in a package we will call albert.
Summary
Section titled “Summary”This chapter covered several important topics. It started with some of the basics of robotics, for readers who needed a bit more background. We talked about common robot parts, such as sensors, computers, and motors/actuators. We discussed the subsumption architecture in more depth and showed how it helps the robot arbitrate between responding to different events and commands. The next section covered the software setup for running the robot, including the offboard development environment and the onboard Jetson Nano computer environments. We set up the ROS and installed the Python tools.
The final section covered ROS 2 and explained what it is and what it does for us. ROS 2 is a middleware layer that lets us build modular components and multiple single-use programs, rather than having to lump everything into one executable. ROS also has logging, visualization, and debugging tools that help our task of designing a complex robot. ROS 2 is also a wonderful repository of additional capabilities that we can add, including sensor drivers, navigation functions, and controls.
In the next chapter, we will discuss how to go from a concept to a working plan for developing complex robot AI-based software using systems engineering practices such as use cases and storyboards.
Questions
Section titled “Questions”- Name three types of robot sensors.
- What does the acronym PWM stand for?
- What is analog-to-digital conversion? What goes in and what comes out?
- Who invented the subsumption architecture?
- Compare my diagram of the three-layer subsumption architecture to the Three Laws of Robotics postulated by Isaac Asimov. Is there a correlation? Why is there one, or why not? Hint: Think about how the laws change the behavior of the robot. Which is the lowest level law (from a subsumption perspective)? Which is the highest?
- Do you think I should have given our robot project – Albert – a name? Do you name your robots? What about your washing machine? Why not?
- What is the importance of the environment variable
ROS_ROOT?
Further reading
Section titled “Further reading”- Scripts to install ROS 2 on Jetson Nano: https://github.com/jetsonhacks/installROS2
- Helpful troubleshooting in case you have problems with your ROS 2 installation can be found at https://docs.ros.org/en/rolling/How-To-Guides/Installation-Troubleshooting.html
- ROS 2 documentation: https://docs.ros.org/en/foxy/index.html
- Dr. Rodney Brooks’s paper on the subsumption architecture: https://people.csail.mit.edu/brooks/papers/AIM-864.pdf