Skip to content
ImagineWorld

ROS 2 Navigation Stack: Nav2

node_idnode-book_mastering-ros-2-for-robotics-programming_chapter-08-ros-2-navigation-stack-nav2
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num8
chapter_titleROS 2 Navigation Stack: Nav2
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 8 — ROS 2 Navigation Stack: Nav2

Section titled “Chapter 8 — ROS 2 Navigation Stack: Nav2”

This chapter will discuss one of the popular robotics capabilities in ROS 2: autonomous navigation and mapping. This capability is one of the main reasons ROS has become popular. Many robots use this capability to navigate in different environments. Autonomous/self-driving robots can map the environment and navigate autonomously from point A to point B. The Nav2 project is a popular ROS 2-based project that provides ready-made packages and nodes for any mobile robot to implement autonomous navigation quickly without re-implementing the wheel.

We will start the chapter with an introduction to Nav2, a brief overview of its architecture, and the installation of Nav2 in ROS 2 Jazzy. After that, we will see how to set up and configure mapping and navigation using SLAM Toolbox and Nav2 for our robot. After configuring the robot, we will see how to create a behavior-tree-based application in Nav2. Finally, we will look at a case study using Nav2 to deploy a mobile robot in hospitals.

After completing this chapter, you will have practical experience configuring and tuning the Nav2 for our robot.

In this chapter, we’re going to cover the following main topics:

  • Getting started with Nav2
  • Configuring Nav2 and Slam Toolbox for your robot
  • Mapping and navigation using Nav2 and Slam Toolbox
  • Case study: Using Nav2 for healthcare robots
  • Developing a BT (behavior tree) application using Nav2

To follow this chapter, you should install Ubuntu 24.04 LTS with the ROS 2 Jazzy desktop. This can be done in a VM, Docker, WSL 2, or on a physical machine. The reference materials and code for this chapter can be found in the Chapter08 folder of the following GitHub repository: https://github.com/PacktPublishing/Mastering-ROS-2-for-Robotics-Programming/tree/main/Chapter08.

In this section, we will go through the basic concepts of the Nav2 project, which include the definition, history, architecture, and features of the project. Let’s first look at the Nav2 project in detail.

The Nav2 project [1] offers autonomous navigation capabilities for mobile robots based on ROS 2. This project aims to enable navigation for nearly any mobile robot in complex environments. Developers using ROS 2 can readily integrate Nav2 capabilities into their robotics applications.

The Nav2 project offers modules for planning, control, localization, perception, visualization, and more to develop a stable and reliable autonomous system. It includes a collection of pre-built ROS 2 nodes and plugins that developers can use to configure the modules above. Nav2 can accept a list of waypoints as input and dynamically plan the path to these points. It can also avoid obstacles and ultimately compute the velocities of the robot’s motors.

Nav2 is integrated with the behavior tree (BT) library [2], which assists developers in creating intelligent navigation motions by facilitating communication with the individual modules in Nav2.

The Nav2 project is the successor of the ROS Navigation stack [3] in ROS 1. The ROS Navigation stack was intended for research applications, but Nav2 can be used for both research and commercial products. More than 100 companies worldwide use Nav2, including NVIDIA, Toyota, and Bosch, which leverage it for autonomous navigation in their robotics platforms.

Figure 8.1: Nav2 Logo

Figure 8.1: Nav2 Logo

Figure 8.1 shows the logo of the Nav2 project. The following section outlines the major milestones in the Nav2 project.

The Nav2 project is developed and maintained by Open Navigation LLP [4], under the leadership of Steve Macenski [5]. He has played a key role in the development of several important ROS 2 projects, including Nav2 and SLAM Toolbox, and has contributed to components like rclcpp.

As we have already discussed, Nav2 began as a successor to the ROS Navigation stack, which was available in ROS 1. Here are the key milestones of this project [31]:

  • 2018: The Nav2 project was initiated to develop a modular, scalable, and flexible navigation stack for ROS 2, starting with early distributions like Bouncy and Crystal.
  • 2019: Basic features were implemented as Nav2 matured alongside ROS 2 Dashing. It gained traction among ROS 2 developers.
  • 2020: Lifecycle management and behavior trees were added to support ROS 2 Eloquent and Foxy.
  • 2021: New planners and costmap improvements were compatible with ROS 2 Foxy and Galactic.
  • 2022: Stability, obstacle handling, and multi-robot features improved with ROS 2 Galactic and Humble.
  • 2023: Simulation, SLAM, and hybrid planning were enhanced in sync with ROS 2 Humble and Iron.
  • 2024: Tools and plugin support expanded to align with ROS 2 Iron and Jazzy releases.
  • 2025: AI integration and cloud-based fleet coordination are advancing with support for ROS 2 Jazzy and the upcoming K-Turtle.

We have gone through the Nav2 milestones. Now let’s explore various features of Nav2.

Here are the important features of the Nav2 project:

  • Modular and flexible design: Nav2 is built to be modular, enabling developers to customize and replace each component as necessary. It employs behavior trees, which facilitate flexible navigation tasks.
  • Navigation core components: Nav2 consists of the following core components for navigation:
    • Localization: It integrates with AMCL (Adaptive Monte Carlo Localization) to estimate the robot pose with respect to the map.
      • Path planning: It has global and local planners. The global planner plans a path from the current position to the goal position, whereas the local planner is a segment of the global planner where the robot tries to move. The common global planners are A* and Dijkstra’s algorithm, and the common local planners are DWB (Dynamic-Window Approach) or TEB (Timed Elastic Band).
      • BT framework: The BT framework is integrated into Nav2, assisting in orchestrating task execution, including navigating to a goal, recovering from failure, and executing custom motion behaviors.
      • Controller server: This will execute the path computed by the local planner and move the robot.
      • Recoveries: The recovery behaviors are a set of predefined motions or routines executing when the Nav2 fails to move the robot. Simple motion can be spinning, and routines can clear obstacles on the costmap.
      • Lifecycle management: The Nav2 nodes are built on the lifecycle nodes of ROS 2, which can enhance startup and shutdown processes.
  • Dynamic obstacle avoidance: Nav2 can dynamically avoid obstacles during navigation. It has plugins for the obstacle layer and a costmap for dynamic environments.
  • Multi-robot support: Nav2 supports multi-robot navigation, allowing multiple robots to operate simultaneously in the same environment.
  • SLAM integration: The Slam Toolbox is a separate project that performs mapping and localization. It is not a part of Nav2, but it works well with Nav2 for generating maps in real time.
  • Customizable: Nav2 can be customized to adapt to different types of robots and environments. The BT customization allows developers to extend the application logic as well.
  • Multi-map and map-less navigation: Nav2 supports switching the map dynamically for multi-floor and multi-environment scenarios.
  • Integration with sensors: Nav2 supports a variety of sensors like LIDAR, depth cameras, and ultrasonic sensors for mapping, localization, and obstacle detection.
  • 3D Visualization and control: Nav2 provides a set of Rviz panels to visualize and modify various navigation parameters for the robot during its navigation.
  • Advanced Nav2 capabilities: Nav2 offers advanced features in navigation, including auto-docking, charging, collision monitoring, assisted teleoperation, and waypoint execution. These features are continuously evolving.
  • Simulation support: Nav2 can be easily used with robotics simulators like Gazebo Classic or Gazebo Sim. We can test the Nav2-based application using a simulator before testing it on the robot hardware.
  • Extensive documentation and tutorials: Nav2 comes with extensive documentation and tutorials, allowing developers to get started quickly with Nav2.

Now that we have seen the important features of Nav2, we can discuss the architecture of Nav2 and how it works.

Figure 8.2 illustrates the Nav2 architecture. Let’s explore this architecture and, after understanding the important nodes in Nav2, we can see how it functions in a robot.

Figure 8.2: Nav2 architecture (source: https://docs.nav2.org/index.html)

Figure 8.2: Nav2 architecture (source: https://docs.nav2.org/index.html)

Nav2 is a collection of nodes and plugins designed to perform navigation tasks. All nodes are based on ROS 2 lifecycle nodes, and each node functions as an action server. The Nav2 Lifecycle Manager oversees the state of each server within Nav2. It can start the nodes in a specified order and establish a bond connection with the server to ensure they remain operational. If any node fails or crashes, it can transition other nodes to a down state to prevent critical failure. Nav2 utilizes a wrapper around the ROS 2 Lifecycle Manager, simplifying the management process.

Each node in Nav2 is highly configurable with ROS 2 parameters. The following section will explore how to configure these parameters and their references.

Here are the different components in the Nav2 architecture.

The Nav2 nodes are implemented as ROS 2 lifecycle nodes. The Lifecycle Manager module includes methods for transitioning the states of the Nav2 nodes in a deterministic manner. Users can configure the Lifecycle Manager with a set of Nav2 nodes, enabling it to activate or change the state of each node individually. It can also deactivate all Nav2 nodes if any are unresponsive or have crashed. Additionally, it establishes a bond connection with each node, ensuring that all nodes remain operational and running.

The complete list of parameters for configuring the Lifecycle Manager is available in [6].

The BT Navigator Server serves as the core of Nav2. This node orchestrates various Nav2 nodes using a behavior tree. The developer may load a specific behavior tree file into this node or choose the default option. The BT XML file specifies how to process the incoming goal pose. This node operates as an action server, capable of receiving navigation goals from clients such as waypoint followers or external autonomy systems that can interact with this server to set goals. It facilitates communication and coordination between the planner, controller, and smoother servers to enable seamless robot navigation. Furthermore, this node can load a custom BT plugin to implement tailored navigation behavior.

The complete parameters of BT Navigator are documented in [7], and the complete behavior tree plugins are listed in [8].

This action server node is responsible for global path planning. It can compute an optimal path from the robot’s current position to the goal while avoiding obstacles on the map. The Planner Server uses a global costmap to calculate an obstacle-free path. The costmap is a grid-based map wherein each cell contains a numerical value ("cost") that indicates how difficult and risky it is for the robot to navigate through that location. There are two types of costmap: the global costmap and the local costmap.

The global costmap covers the entire known area of the robot’s map. This costmap is used for finding an optimal route to a destination using a static map. The local costmap focuses on the area immediately around the robot, which is used for real-time obstacle avoidance and short-term decision-making. The robot map created by SLAM is the input to the global and local costmaps. These two costmaps add separate layers on the top of the actual map. There are different layers we can add to the global costmap, like the obstacle layer and inflation layer, which can make an additional layer in the actual map to avoid obstacles in advance. The Planner Server can load different global planner plugins based on the configuration.

The complete Planner Server parameters are listed in [9].

The Controller Server is mainly responsible for the local planning of robot navigation. The local planner tries to follow a segment of the global plan created by the Planner Server. The Controller Server has a representation of the local costmap. The local planner can compute a feasible path in the local costmap and generate velocity control commands for the robot to follow.

The Controller Server can also load plugins that function as local planners. There are progress checker and goal checker plugins within the Controller Server that monitor navigation progress and verify whether the specified goal has been reached.

The complete list of parameters that we can use to configure the Controller Server is available in [10].

The Behavior Server can host different behavior plugins that handle behaviors like recoveries after a navigation failure. Whenever navigation fails due to sensor failure or any other factor, the Behavior Server can trigger the set of behavior plugins to invoke it. Some available behaviors are spinning, waiting, assisted teleop, etc.

Behaviors such as spinning can assist if the robot is trapped in a corner and unable to find a way out. After performing a spin, it might discover a route to escape from the corner. In the event of total failure, we can initiate a recovery procedure to alert an operator via email, SMS, Slack, etc.

The complete Behavior Server parameter configuration is given at this link [11].

As the name suggests, this server assists in refining and smoothing the generated planner path to enhance its quality and eliminate abrupt rotations. While smoothing the path, it also considers obstacles and high-cost areas, as it can access the robot’s costmap and footprint. The Smoother Server typically receives a path from the Planner Server and returns an improved version.

The complete parameters for the Smoother Server can be found in [12].

Traditional path planning may not be efficient in large and complicated environments. The Route Server is a node that can complement the Nav2 Planner Server. Instead of working on an occupancy grid, it creates a pre-generated navigation graph to plan routes. This can significantly reduce the planning computation load and make navigation more efficient, especially in complex environments or large spaces.

The velocity command sent from the Nav2 controller server can be fed to a velocity smoother node to smooth velocity, acceleration, and other parameters. This can reduce wear and tear on the robot motors and help avoid jerky movements. The local planner can generate jerky movements that can be fixed by Velocity Smoother nodes.

The Velocity Smoother node can also be configured using parameters, and the reference is at the following link [13].

The Collision Monitor is another node that adds a layer of safety to robot navigation. The planners can even detect dynamic collisions. However, in some instances, particularly with fast-moving robots, entities may move at high speed. If the planner fails to identify the obstacle, the Collision Monitor can sense it using incoming sensor data, bypassing the costmap and trajectory planners. This node can avert a potential collision.

The complete configuration of the Collision Monitor can be found at the following link [14].

The primary input required from the user for Nav2 is the list of waypoints it needs to navigate. The Waypoint Follower node in Nav2 can execute the waypoints using the NavigateToPose [15] action provided by the BT Navigation Server. It will take a set of ordered waypoints from the user and execute them sequentially. Additionally, it can perform custom behaviors such as waiting at a waypoint, taking a picture, or executing tasks via its waypoint task executor plugin.

The complete list of parameters for configuring the Waypoint Follower node is available in [16].

We have discussed the key components of the Nav2 architecture; now, let us explore how it functions.

This section describes how Nav2 works if the robot has to move from point A to point B in a known environment. Figure 8.3 illustrates the robot configuration necessary for integration with Nav2.

Figure 8.3: Workings of Nav2

Figure 8.3: Workings of Nav2

In the Nav2 architecture, we have noticed some input to Nav2, correct? Figure 8.3 depicts the primary input into Nav2 from the robot and the main output relayed to the robot from Nav2.

We can identify the important topics that we need to supply to Nav2, which include tf (transformation), /odom, /map, and sensor topics such as /scan with sensor_msgs/LaserScan, or topics that publish sensor_msgs/PointCloud or sensor_msgs/Range. The tf frames we must establish before initiating navigation with Nav2 are map->odom->base_footprint->base_link->(tf of robot links). The robot’s controller or driver nodes running on the robot can publish the /odom topic and transform it from odom->base_link.

If you use Gazebo Sim or another simulator, ensure it also publishes the odom->base_link transformation. The remaining transformation, map->odom, is provided by the AMCL node in Nav2. The AMCL node localizes the robot on the map. It can publish the current pose estimates via tf and has a particle cloud that indicates the probability of the robot’s pose estimates. A particle cloud that is spread out indicates a less accurate pose.

The /map topic can be published by the Nav2 Map Server from a saved file, or we can use Slam Toolbox to generate the dynamic map.

Let’s now discuss how Nav2 works when providing a single target position: Point B. Ensure that the robot correctly supplies all other Nav2 input topics:

  1. Initial position to localization: When we start Nav2 and all the nodes shown in Figure 8.3, we may see the robot map on Rviz, the robot simulation in Gazebo, or the real robot starting up once Nav2 is initiated. The first thing we may need to do is not set the goal position; however, before that, we must ensure proper localization so that the robot can accurately locate itself on the map. Only if the localization is correct will navigation function properly. AMCL localization is one way of localizing the robot on the map. When we start Nav2, the user may need to provide an initial map position to AMCL for it to begin. Once it has a proper initial pose, it can localize the map using sensor data such as LiDAR. Once localization is complete, you will find all the global and local costmaps appear, ready for goal acquisition.
  2. Goal setup: Using the Waypoint Follower node, we can provide a single or multiple goal positions to Nav2. Nav2 includes waypoint follower panels, which simplify the process of feeding waypoints from Rviz.
  3. Global planning: When Nav2 receives the goal position, the Planner Server calculates a path from the current robot location (Point A) to Point B, utilizing a global costmap. This global plan is typically static, meaning it does not account for dynamic obstacles like moving people or vehicles, so it may become outdated in dynamic environments.

Moreover, the global path is often coarse and somewhat jerky, as it’s meant to provide a high-level route rather than fine-grained motion. Local planning is then used to refine this path and handle real-time changes.

  1. Local planning: After generating the global plan using the Planner Server, Nav2 uses the control server to generate the local plan. The local planner uses real-time sensor data (e.g., from LiDAR or cameras) along with the local costmap to avoid dynamic obstacles and adjust the robot’s movement accordingly. The local planner ensures the robot follows the global path smoothly and safely, dynamically re-planning short segments to prevent collisions and navigate around unforeseen obstacles. This ensures the robot can move smoothly along the path by avoiding obstacles on the local map.
  2. Execution: The Controller Server sends velocity commands to the robot’s controller board, which then transmits the wheel commands to the actuators (e.g., wheels or motors) to follow the planned path.
  3. Obstacle detection: If any unexpected obstacles are detected, the local planner recalculates a new path around them, computing the robot’s movement in real time. The Collision Monitor also helps the robots avoid immediate collisions.
  4. Arrival: The task is considered complete once the robot reaches the goal position (Point B). We can also provide goal tolerance if needed.

We have gone through the fundamental concepts of how Nav2 works. The next section will demonstrate how to install Nav2 and set it up for our robot.

Installing Nav2 on ROS 2 Jazzy is straightforward.

The following command will install all Nav2 packages on ROS 2 Jazzy:

sudo apt install ros-${ROS_DISTRO}-navigation2

The navigation2 package is a meta-package that installs the necessary dependent packages for navigation.

Along with the main package, we may need an additional package called nav2-bringup:

sudo apt install ros-${ROS_DISTRO}-nav2-bringup

This package includes a set of ROS 2 launch files that facilitate the launching of the Nav2 nodes and provide the necessary configuration. These launch files enable developers to set up Nav2 for their robot quickly.

After installing Nav2 on ROS 2 Jazzy, we can set up a demo simulation with its Nav2 configuration package to test its features.

We will install the simulation and navigation package for the TurtleBot 3 demo here.

Here’s the command to install the simulation and navigation packages:

sudo apt install ros-${ROS_DISTRO}-nav2-minimal-tb*

After installing the package, we can execute the following command to initiate the simulation in Gazebo Sim:

ros2 launch nav2_bringup tb3_simulation_launch.py headless:=False

The headless argument is set to False to visualize the simulation in Gazebo Sim; if it is True, it will simulate without a Sim window.

After executing the command above, we will have the Gazebo Sim, Nav2 nodes running, and the Rviz window, as shown in Figure 8.4.

Figure 8.4: Nav2 demo using TurtleBot 3

Figure 8.4: Nav2 demo using TurtleBot 3

When we initiate navigation, the robot might not be able to localize the map. An initial position is required to start localization. We can set the initial pose using Rviz. After clicking the 2D Pose Estimate button, you can select the robot’s position on the map. You may need to rotate the map orientation to align it with the Gazebo world. Once the robot’s initial pose is established, the navigation nodes will begin, and you can view the global costmap and local costmap on the main map. You can check the status of navigation and localization in the Navigation 2 toolbar in Rviz to make sure everything is initialized correctly.

Figure 8.5: Nav2 demo navigation

Figure 8.5: Nav2 demo navigation

Once Nav2 is initialized, you can find an additional layer on the top of the static map, which appears as light blue, which is called the global costmap. The global costmap inflates the obstacle in the static map to make navigation safer. The global planner in Nav2 uses a global costmap for computing the high-level path from start to goal. The global costmap will not update frequently with dynamic obstacle data.

The local costmap focuses on the area immediately around the robot, which appears mostly as a violet color, and updates using real-time sensor data. It can capture dynamic obstacles like people or moving objects. The local costmap is used by the local planner to make safe, short-term motion decisions.

We can now set individual goals or waypoints in Rviz using the Nav2 Goal button. Click the Nav2 Goal button and click on a point on the map to provide a goal position. Figure 8.5 illustrates a sample goal position given for navigation.

The Navigation2 widget displayed in Rviz features a button labeled Waypoint. After clicking the Waypoint button, we can set multiple waypoints on the map using the Nav2 Goal button. Once the waypoints are created, click Start Nav Through Pose to begin the waypoint navigation.

Figure 8.6 shows single waypoint vs multi-waypoint navigation in the map.

Figure 8.6: Single waypoint (left) vs multi waypoint (right) navigation demo

Figure 8.6: Single waypoint (left) vs multi waypoint (right) navigation demo

You can set up Nav2 on an Ubuntu 24.04 desktop version or test it in a Docker container. When working with real robots, using Docker will simplify deployment significantly. In the next section, we’ll explore setting up Nav2 in Docker.

You can find the Dockerfile and shell script to create a custom image for running Nav2-based simulation and application in Chapter08/docker_nav2.

Here is the command to build the Nav2 image:

./build_image.sh ros2_nav:v0.1 master_ros2_ws robot

Here, ros2_nav:v0.1 is the name of the custom image, master_ros2_ws is our ROS 2 workspace where we can put our custom robot simulation and navigation packages, and the robot is the user’s name inside the container.

After building the Nav2 image, we can create the container using the following command:

./create_container.sh ros2_nav:v0.1 master_ros2_ws ros2_nav

We need to provide the image name, the ROS 2 workspace name, and the container name we need to make.

After creating the container, you can start running the navigation and mapping commands. The following demo simulation launch file can be used to test the container:

ros2 launch nav2_bringup tb3_simulation_launch.py headless:=False

If you want to open more terminals for the same container, you can use the following command:

./start_container.sh ros2_nav

This will attach a new terminal if the container is already running, or start the container if it has stopped. You need to provide the container name as the argument for this script.

After attaching a new terminal, make sure you have sourced the ros_entry_point script using the following command:

source /ros_entrypoint.sh

We can test all the packages in this chapter using this Docker image. You can create a new package by placing it in the ROS 2 workspace and building it.

Here are the instructions to build, create, and run a container using Docker Compose.

In this section, we will see how to build and start containers for simulation using Docker Compose.

Switch to the Chapter08/docker_compose_nav2 folder and execute the following commands to start building the Docker image and start the container.

  • Use the following command if you are using a non-NVIDIA graphics card on your PC:
    docker compose -f docker-compose-gui.yml build
    docker compose -f docker-compose-gui.yml up
  • If you do have an NVIDIA graphics card and the driver is properly installed, use the following command to start the container:
    docker compose -f docker-compose-nvidia.yml build
    docker compose -f docker-compose-nvidia.yml up

Once you start this command, the image will be built first, the container will start, and you will have to use another terminal to attach to the container. You don’t have to close this terminal; if you cancel the command by pressing Ctrl + C, it will stop the running container.

You can create a new terminal from the running container using the following command:

./start_container.sh ros2_nav

Now source the ROS 2 environment:

source /ros_entrypoint.sh

Build the ROS 2 workspace:

colcon build

Source the ROS 2 workspace:

source install/setup.bash

Now, we can launch the simulation launch file:

ros2 launch nav2_bringup tb3_simulation_launch.py headless:=False

After starting the container, if you want to stop the container and remove it, you can execute the command from a new host terminal. Make sure you are executing inside the docker_compose_nav2 folder:

  • If you are using a non-NVIDIA graphics card:
    docker compose -f docker-compose-gui.yml down
  • If you are using an NVIDIA graphics card:
    docker compose -f docker-compose-nvidia.yml down

In the next section, we will see how to set up VS Code Dev Containers for running a simulation.

If you are interested in setting up a dev container in VS Code, make sure you have created the ROS 2 workspace named master_ros2_ws and open the Chapter08 folder using VS Code. This folder has a .devcontainer folder, which has the devcontainer.json file, which has the instructions to use the Docker Compose file we used in the above section for the container. When you open the folder, it will prompt you to install the Dev Containers extension and Reopen in Container. If you select this option, it will build the container, set the environment, mount the ROS 2 workspace as a volume, and connect the editor to it. We can also see the mounted volume, which is the master_ros2_ws folder in VS Code itself.

We have seen how to set up the Nav2 demo on Docker, Docker Compose, and Dev Containers. In the next section, we will explore how to use the Slam Toolbox to create a map of the robot’s environment.

In this section, we will explore what the slam_toolbox project is and how to use it with Nav2.

Slam Toolbox [17] is a ROS 2 project that includes nodes for implementing 2D SLAM [18] in mobile robots. SLAM (Simultaneous Localization and Mapping) is a set of algorithms in robotics used to localize and map the robot environment using different sensors like cameras or lasers to see the surroundings. The generated map can be stored and can later be used for navigation. Examples of 2D SLAM are FastSLAM, Hector SLAM, and Cartographer.

With 2D SLAM, we can create a 2D map of the robot’s environment, which can later be used for navigation.

Steve Macenski, who also leads the Nav2 project, created the Slam Toolbox project. Samsung Research and the open-source community are currently maintaining the project.

Here are the main features of Slam Toolbox:

  • 2D mapping: It has 2D SLAM, built for creating and saving a map. It also has features to refine, remap, and continue mapping a saved pose graph.
  • Life-long mapping: This is the concept of being able to map a space, entirely or partially, and over time, you can refine and update the map as you continue to interact with the space.
  • Synchronous and asynchronous mapping: It supports synchronous mapping, suitable for real-time navigation, whereas asynchronous mapping is ideal for offline mapping and large environments.
  • Rviz plugin: It has the Rviz plugin for interacting with the mapping.

Figure 8.7 illustrates the topics subscribed to and published by the slam_toolbox node and its various components.

Figure 8.7: Block diagram of slam_toolbox node

Figure 8.7: Block diagram of slam_toolbox node

The node subscribes to the laser scan topic /scan and the robot’s TF /tf (odom->base_link). Once the node has subscribed to these topics, it processes the data for graph construction. This includes filtering the data, reducing noise, and preparing for scan matching. After processing the data, the node constructs a graph of the environment. In the graph, each node represents a robot pose, while each edge represents the spatial relationship between poses. The processed data is then used for scan matching, which aligns the current LiDAR scans with previous ones to estimate the robot’s relative position. This process is crucial for localization and mitigating map drift. Loop closure [32] detects when the robot revisits a previously mapped area, adding constraints to the graph that correct drift over time. The optimizer refines the entire graph and produces a consistent map, which minimizes errors in the graph’s pose estimation and ensures map alignment. The mapping section generates and publishes the final optimized graph.

The node publishes map data and the robot’s pose to the map frame.

The slam_toolbox node also exposes many services like save map, serialize map, and deserialize map.

The Slam Toolbox for ROS 2 provides different modes of operation. Commonly used modes of operations are:

  • Online Synchronous (sync): In this mode, SLAM runs in sync with incoming sensor data. Each scan is processed and updates the map before the next arrives. This method is CPU-efficient because it does not do the queuing of the sensor messages. This method is used where real-time responsiveness is crucial. It is suited more for a low-speed robot.
  • Online Asynchronous (async): In this mode, sensor data is queued and processed in a separate thread asynchronously. This is useful if the scan rate is slower than the scan arrival. This will be useful where SLAM needs time to process. It takes more CPU because of queuing and multi-threading. It is suited to high-speed robots with high data rates.

We will see how to use both in the upcoming section on configuring Slam Toolbox.

We have explored important features of Slam Toolbox; now we will see how to install ROS 2 Jazzy.

To install Slam Toolbox in ROS 2 Jazzy, we can use the following command:

sudo apt install ros-${ROS_DISTRO}-slam-toolbox

SLAM Toolbox is already included in the Dockerfile if you use the provided Docker container.

After installing slam-toolbox, let’s see a mapping demo using TurtleBot 3 simulation.

To test the mapping process, we can utilize the same launch file within the nav2_bringup package we previously tested for Nav2.

Here is the demo launch file we can use to start mapping:

ros2 launch nav2_bringup tb3_simulation_launch.py headless:=False slam:=True

As you can see, we are using the same demo launch file to test navigation, but here, we set slam to True to enable mapping.

Here’s how the mapping process works. The launch file starts the TurtleBot 3 simulation in Gazebo and initiates the slam_toolbox and Nav2 nodes. We can see a section of the map that was created and visualize it in Rviz. To complete the mapping process, we have to teleoperate the robot around the environment. As the robot moves, Slam Toolbox can start generating and updating the map.

In Rviz, you can see a map being created while you move the robot. You can move the TurtleBot3 robot using the following command:

ros2 run teleop_twist_keyboard teleop_twist_keyboard

We can use keyboard buttons to drive the robot. We can also use the rqt and Robot Steering plugin to drive the robot. If we use Gazebo Sim, we can teleoperate the robot from the GUI panel itself. In addition to the robot’s manual driving and mapping, we can also perform mapping with Nav2. In the tb3_simulation_launch.py launch file that we used above, we are running slam_toolbox alongside Nav2. We can command the robot to reach a goal position on the incomplete map, and the robot can move to that position while simultaneously building a map.

You can click on the Nav2 Goal button in Rviz and provide the goal position, and it will build the map like we do using keyboard teleoperation. You can use the automatic mapping technique until the map is fully finished. This configuration is also used for exploration algorithms capable of automatically moving around an unknown environment and building a map without providing the manual goal position.

After navigating the robot through the environment several times, you can view the entire map, as shown in Figure 8.8.

Figure 8.8: Manual mapping using Slam-toolbox

Figure 8.8: Manual mapping using Slam-toolbox

After completing the map, we can save the map using another command:

ros2 run nav2_map_server map_saver_cli -f ~/map

The map_saver_cli node can save the map with the name provided as an argument. The name is map.pgm, and the map configuration file is map.yaml.

The map can also be saved from Rviz. Slam Toolbox provides an Rviz panel with the option to save, serialize, or deserialize the map. To load the panel, go to Panel | Add New Panel | slam_toolbox | SlamToolboxPlugin. We will get the following panel in Rviz.

Figure 8.9: Slam Toolbox Rviz panel

Figure 8.9: Slam Toolbox Rviz panel

The map’s name can be mentioned in the box beside the Save Map button. After mentioning the name, you can click the Save Map button. The map will be saved in the path where we start the mapping launch file.

You can find the different parameters of the SLAM Toolbox in the README of the project [19].

In the next section, we will explore how to create a navigation package for the new simulated robot we developed in Chapter 5.

Configuring Nav2 and Slam Toolbox for your robot

Section titled “Configuring Nav2 and Slam Toolbox for your robot”

This section shows how to create a ROS 2 package to implement autonomous navigation for our robot using Nav2. The package mainly contains launch and parameter files for starting and configuring Nav2 nodes. It can be found in the Chapter08/rosbot_nav2_bringup folder.

The rosbot navigation package contains the following files:

Figure 8.10: rosbot navigation 2 package structure

Figure 8.10: rosbot navigation 2 package structure

You can find a set of launch files in the launch folder: nav2.launch.py, which starts the Nav2 nodes, slam_online_async.launch.py and slam_online_sync.launch.py for mapping, and slam_nav2.launch.py for mapping in conjunction with navigation. In the maps folder, we can see a saved map of a hospital environment. Following the launch files, the next important part of the package is the params folder. It contains parameters for the AMCL node, Nav2 nodes, and Slam Toolbox. Configuring the Nav2 stack involves setting these parameters. We have observed the list of parameters for each module in Nav2. What we are doing in this package is simply configuring those parameters for our robot and initiating all nodes using the launch file.

At first glance, the process seems simple: getting the robot up and running with the Nav2 stack, but the real challenge lies in tuning the parameters. With over 500 parameters for all these nodes, fine-tuning them to enhance navigation is quite difficult.

In this chapter, we will not discuss the individual parameters of Nav2. However, we will provide a general overview of how to set up a Nav2 package with default parameters and a reference for each parameter.

We will use rosbot_description, which we have generated and modified by converting the Fusion 360 model to URDF for interfacing with Nav2.

So, let’s start interfacing the rosbot simulation with Nav2.

Here are the prerequisites for the robot in simulation or for the actual robot to interface with Nav2:

  • Publishing TF of the robot: We must ensure the robot publishes the TF frame from odom->base_footprint-> base_link(robot_link). When we activate the navigation and localization nodes, the AMCL node will also publish the transformation from the map-> odom. In short, we must confirm that when we start navigation, we see the TF from map-> odom-> base_footprint-> base_link-> (robot_link). If Nav2 is not functioning correctly, the first check you should perform is to visualize the TF tree in rqt. If the TF tree is broken, we need to address that.
  • Setting ROS 2 topics: Here are the important checks we must do in ROS 2 topics before interfacing with Nav2:
    • We must ensure that the sensor topics are published, including the /scan topic for the laser and the /odom topic for the wheel encoder.
      • We also need to confirm that the Gazebo Sim differential drive plugins or ROS 2 controllers are configured properly.
      • We need to verify that the robot driver nodes are functioning correctly on the actual hardware.
      • Another important topic to check is the robot’s command velocity, which drives the robot.
      • We need to make sure that the command velocity topic, by default /cmd_vel, aligns with the robot driver or the Gazebo Sim differential drive plugin topic. The robot can only move if the topics align; otherwise, it will plan a path but will not be able to move. Therefore, if the robot is not moving, we need to verify that the command velocity topic is published and subscribed to correctly.
      • Additionally, we must ensure that the map topic is being published. If the map is not published, Nav2 will not function. We must ensure map_server is configured correctly and the map file is provided appropriately for navigation. If we are using slam_toolbox and Nav2, we must ensure that slam_toolbox nodes are publishing the map data correctly.

We can start interfacing Nav2 with our custom rosbot robot if these modifications are done.

Let’s start discussing the Nav2 launch files in the next section.

In this section, we will discuss writing the Nav2 launch file for navigation and the Slam Toolbox launch file for mapping. We will see the important nodes and configurations we use inside these launch files.

Once the robot prerequisites are met, we can create a launch file to start the Nav2 node, AMCL, and map server. Nav2 has already been given a package called nav2_bringup, with launch files to start navigation. It will make the entire process easier. In our example, the rosbot_nav2_bringup/launch/nav2.launch.py file includes bringup_launch.py and passes the arguments to this launch file. The nav2.launch.py file will start the AMCL and map_server nodes, and the nav2_bringup/launch/bringup_launch.py file will start nodes such as nav2 life cycle manager, controller_server, smoother_server, planner_server, behavior_server, velocity_smoother, collision_monitor, bt_navigator, waypoint_follower, and docking_server. Along with loading all the nodes, this launch file also loads parameter files like rosbot_nav2_bringup/params/nav2_params.yaml and amcl_params.yaml, which have a configuration of all the nodes for navigation.

In this section, we can see how to run the Slam Toolbox in async and sync mode, which we have seen in the description of Slam Toolbox.

The rosbot_nav2_bringup /launch/slam_online_async.launch.py launch file runs the nodes to run Slam Toolbox in async mode by loading the parameter file called rosbot_nav2_bringup/params/slam_toolbox_async.yaml, whereas rosbot_nav2_bringup/launch/slam_online_sync.launch.py starts Slam Toolbox in sync mode by loading the parameter file called rosbot_nav2_bringup/params/slam_toolbox_async.yaml.

If we want to run Nav2 and slam_toolbox, we can use rosbot_nav2_bringup /launch/slam_nav2.launch.py. This launch file starts all Nav2 and slam_ toolbox nodes except AMCL. The Slam Toolbox node itself carries out the localization.

We can use these launch files as templates and can use them for any other robot. The main changes we may have to make for a new robot are in the Nav2 parameter file, which will be discussed in the next section.

Our robot navigation configuration file is at rosbot_nav2_bringup/params/nav2_params.yaml. By checking this file, we can find the parameter configuration for each node we have started. This configuration contains more than 500 parameters, making it difficult to learn about each one. The basic adjustments you may need to make pertain to any changes in the topic’s name, the name of the TF frames, etc.; we might need to change those. We can leave the other parameters as they are.

The list of parameters for each node is provided in [20], where you can find information on all the parameters. The detailed tuning guide is available in [21].

In the next section, we will explore how to launch the navigation and mapping of the rosbot robot.

Launching rosbot simulation and navigation

Section titled “Launching rosbot simulation and navigation”

You can keep the rosbot_description and rosbot_nav2_bringup in your ROS 2 workspace. If you use Docker, copy to the master_ros2_ws/src folder and build the workspace.

The following launch commands will start the navigation with the available map:

  • This command will start the rosbot simulation in Gazebo Sim:
    ros2 launch rosbot_description gazebo.launch.py
  • We can start the navigation launch using the following command:
    ros2 launch rosbot_nav2_bringup nav2.launch.py

After starting the navigation, you can give the initial pose for AMCL and start putting waypoints using the Rviz 2D Nav goal button, and you can see the robot is moving, as shown in Figure 8.11.

Figure 8.11: rosbot Gazebo simulation with Nav2 in Rviz

Figure 8.11: rosbot Gazebo simulation with Nav2 in Rviz

To manually start mapping, launch the following file:

ros2 launch rosbot_nav2_bringup slam_online_async.launch.py

This will activate the rqt steering plugin, allowing you to drive the robot manually and create the map.

The following launch file can be used to map the world using Slam Toolbox and Nav2:

ros2 launch rosbot_nav2_bringup slam_nav2.launch.py

As we did for TurtleBot 3, we can start providing waypoints, and the robot will traverse an unknown area to complete the map.

After successfully setting up the rosbot navigation package, let’s examine a case study of Nav2 utilizing mobile robots in hospitals to deliver medicine to patients during COVID-19.

Case study: Nav2-based robots during COVID-19

Section titled “Case study: Nav2-based robots during COVID-19”

During COVID-19, some hospitals deployed robots to deliver items like medicines to patients to avoid transmitting the virus [30]. While most of these robots were tele-operated, we would like to implement a robot in the rest of this chapter that delivers medication to patients in an automated manner. In this section, we will look at a Nav2-based application that provides medication to patients in the room.

The simulation world we saw in the last section was a section inside the hospital. As you will understand, this is a very simplified version of the actual environment. The actual environment is much more complex and has more tasks to do, like opening doors, avoiding pedestrians, etc. We need much more robust techniques to deploy in the actual scenario. This simulation application and the environment are for demonstration purposes only. Figure 8.12 shows the hospital map, with different sections marked.

You can find Room 1, Room 2, and a medicine shop. The robot’s initial position will be on the left side of the map. Whenever the robot receives instructions from the user to deliver medicine to a room, such as Room 1, the robot first goes to the medicine shop from its initial position. It will wait for a moment to collect the medicine from there. The robot then moves to Room 1 to deliver the medicine to the patient. After the delivery, it will return to its initial position and dock for charging.

The robot will follow the next instruction once it returns to the initial position.

Figure 8.12: Markings of the hospital map

Figure 8.12: Markings of the hospital map

The following section will look at a simple Nav2-based C++ application to achieve this task.

Developing Nav2-based applications using ROS 2 and C++

Section titled “Developing Nav2-based applications using ROS 2 and C++”

This section will discuss the ROS 2 C++ application designed to deliver medicine to a specific room.

Figure 8.13 shows how our application communicates with Nav2.

Figure 8.13: Communication between navigation application and Nav2

Figure 8.13: Communication between navigation application and Nav2

The application we are developing is a Nav2 action client. We know Nav2 has a BT Navigator Server node, which serves as an action server with an action name called /navigate_to_pose and an action type of nav2_msgs/action/NavigateToPose [22], as well as /navigate_through_poses with an action type of nav2_msgs/action/NavigateThroughPoses [23]. When we call the action /navigate_to_pose with a goal position on the map, the BT Navigator can begin planning the path and move the robot to that location. The request will fail if the pose is invalid or obstructed.

The action /navigate_through_poses allows the robot to move through several waypoints. These actions can also be called from the Rviz Navigation2 panels. We have already experimented with these options in the previous sections.

In our robot application, we use the /navigate_to_pose action, which allows us to send one point at a time.

You can find the application package in Chapter08/nav2_client. Inside this package, you will find nav2_client/include/navigation_client.hpp and nav2_client/src/navigation_client.cpp. This includes defining a NavigationClient class with the action client to send the goal position.

In the header file, you can find the following action client declaration:

using NavigateToPose = nav2_msgs::action::NavigateToPose;
rclcpp_action::Client<NavigateToPose>::SharedPtr action_client_;

In this code, we can see we are using the same action type we saw earlier. Along with declaring the action client, we can see the goal response, feedback, and results declaration.

In the navigation_client.cpp file, predefined poses are hardcoded in the constructor. These poses correspond to each section of the map, including those for rooms 1 and 2, the medical shop, and the robot’s initial pose.

The navigate2Pose() function takes the pose as an argument and executes the action. This is one of the key functions of this class:

bool NavigationClient::navigate2Pose(double x, double y, double z, double orientation_w)

The function’s arguments are x, y, z, and orientation_w in quaternion. In our case, the z value will be zero because we are moving a plane.

The deliverMedicine() function is another important function that can take order_number, and, based on order_number/room_no, it can call the hard-coded positions in a specific order:

bool NavigationClient::deliverMedicine(int order_number)

For example, if order_number is 1, it will first navigate the robot to the medical_shop location using the navigate2Pose() function and then load it with the room 1 position and then to the initial position. The same logic applies to order_number 2.

The nav2_client/src/main.cpp is the main application code. It will include the navigation class we created and pass the order number from the user to function inside the class. Once it passes the order_no, the deliverMedicine() function will be executed, and after completion of the order, the user can enter the next order.

In the next section, we will see how to build and run the application.

You can copy the nav2_client package to master_ros2_ws and build the ROS2 workspace. After building the ROS 2 workspace, execute the following command to start the application:

  • The following command will start the simulation of rosbot in Gazebo Sim:
    ros2 launch rosbot_description gazebo.launch.py
  • We can start the navigation launch using the following command:
    ros2 launch rosbot_nav2_bringup nav2.launch.py

After the navigation launch, you can provide the initial pose of the robot using the 2D Pose Estimate button in Rviz and start the following command in another terminal to start the application:

ros2 run nav2_client navigation_client

The application will ask the user to input the order number like this:

[navigation_client]: Navigation client initialized
Enter order number (1 for Room1, 2 for Room2, q to quit):

After inputting the order number, the robot plans the path and the remaining distance to the goal in the terminal, as shown in Figure 8.14.

Figure 8.14: Nav2 application for medical robot

Figure 8.14: Nav2 application for medical robot

We have utilized basic conditional logic to implement the navigation in this application, but what about creating a complex navigation system? In such cases, simple conditional logic may not be reliable or scalable. Imagine that, instead of two rooms, the hospital has 100 rooms. What if there are specific rules for navigating the floor? Additionally, what if we need to include tasks like people detection? This is when we need to consider incorporating state machines or behavior trees into our application.

The following section will explore incorporating a behavior tree into the Nav2 application code.

Developing Nav2-based applications using BT and C++

Section titled “Developing Nav2-based applications using BT and C++”

In this section, we will see how to use BT to make complex applications using Nav2.

There are two main areas where we can use BT along with Nav2:

  • BT Navigator Server in Nav2
  • In a Nav2 action client

Let’s explore each use case in detail here.

We have seen that the core part of Nav2 is the BT Navigator Server. A BT file is one of the main inputs to the BT Navigator Server. The BT Navigator Server can be completely configured with our BT file. The BT file decides what to do once it receives a goal pose or set of goal positions. The BT file has different nodes which decide how navigation has to perform and how to provide the recovery. Based on the nodes in the BT file, the Navigator Server can trigger each node, such as the Planner Server, Controller Server, and Behavior Server.

We can configure this node and the input BT node by setting this node’s default_nav_to_pose_bt_xml and default_nav_through_poses_bt_xml parameters. If we are not setting any values, it can take some default files. We can find all the existing BT files from [24].

Nav2 provides a set of navigation-specific nodes that can be included in the behavior trees. Here is an introduction to all the Nav2-specific behavior trees [25]. Here is the reference on existing behavior tree nodes in Nav2 [26]. You can find multiple action plugins, condition plugins, control plugins, and decorator plugins for Nav2 from the list that can be used to construct our BT file.

We can create a custom BT file for the navigator node to change the navigation behavior. We can also write new BT nodes as Nav2 plugins to implement different functions in Nav2. Here is a reference to implement new BT node plugins in Nav2 [27].

Here is the complete reference of BT and Nav2 [28].

In the next section, we will see how we can implement BT in a Nav2 client.

In this approach, we use BT outside Nav2 as a Nav2 action client, which uses an action called /navigate_to_pose.

This approach is the same as before for the medical robot; the only difference is that, instead of just a condition statement, we have used a BT-based application. The BT-based Nav2 action client example package is available in Chapter 08/nav2_bt_client. The BT file is placed in nav2_bt_client/bt_xml/nav_tree.xml. Figure 8.15 shows the visualization of nav_tree.xml in the Groot 2 editor.

Figure 8.15: BT in nav2_bt_client package

Figure 8.15: BT in nav2_bt_client package

There are two main BT action nodes implemented within this package: SetLocations and GotoPose. The SetLocations node reads predefined map locations from the file nav2_bt_client/config/map_locations.yaml and outputs a list of locations, including the name of each location and the corresponding map locations. The GotoPose node can receive inputs such as the location’s name and the location pose. This GotoPose BT node has the Nav2 action client implementation, and it will call the /navigate_to_pose action with the appropriate location. So basically, the above BT application will read the location from the YAML file and move the Nav2-based robot to three map locations.

The nav2_bt_client/src/navigation_behaviors.cpp has the implementation of custom BT nodes, and nav2_bt_client/src/nav2_bt_node.cpp is the ROS 2 node, which initializes the BT and executes it.

Running the node is similar to the action client we have executed for the medical robot. The only difference is that we have to set up a Groot 2 editor to visualize the flow of the BT.

Download the installer script from the following link to set up Groot2 [29]. After downloading the installer, you can execute the following command, and a GUI-based installer will pop up:

./Groot2-v1.6.1-linux-installer.run

You can click Next and install Groot in the home folder. Ensure the groot2 executable is available in /home/<user_name>/Groot2/bin/groot2. You can set up Groot 2 in Docker as well. Copy the installer to the mounted volume and install Groot, or you can also include it in the Dockerfile.

Once we set up Groot 2 correctly, we can copy the nav2_bt_client package to the workspace and build the workspace.

We can execute the following commands to start the BT-based Nav2 action client:

This command will start the simulation of rosbot in Gazebo Sim:

ros2 launch rosbot_description gazebo.launch.py

We can start the navigation launch using the following command:

ros2 launch rosbot_nav2_bringup nav2.launch.py

After launching the navigation, you can provide the initial pose of the robot using the 2D Pose Estimate button in Rviz and start the following command in another terminal to start the BT application:

ros2 launch nav2_bt_client start_bt_app.launch.py

This launch file starts the Nav2 BT action client node and Groot2 with the nav_tree.xml behavior tree. Once you see the window, you can switch to the real-time mode in Groot 2 to see the status of the BT application. Click on Real-time mode and click the Connect button to start monitoring the status of the BT application.

Figure 8.16 shows the execution of the BT in the Groot 2 editor.

Figure 8.16: Groot2 real-time monitor

Figure 8.16: Groot2 real-time monitor

As you can see, each action node is executed individually, and the robot moves to each position on the map. We can expand the application by writing more BT nodes and changing the BT tree. Note that, in real robotic applications, the implementation of BT nodes can be very complex. The above example is just for demonstrating the capabilities of a BT in robot navigation.

This chapter explained how to use the ROS 2 Navigation Stack, called Nav2, for autonomous robot navigation. Nav2 helps robots move from one place to another by planning paths, avoiding obstacles, and controlling movement. The chapter introduced Nav2, its installation on ROS 2 Jazzy, and how to set it up with Slam Toolbox to create maps of the environment. It covered key components like localization, path planning, behavior trees, and lifecycle management, which help in making navigation smooth and efficient. The chapter also included practical steps to configure Nav2 for a robot and demonstrated its use in a hospital scenario for medicine delivery during COVID-19. Additionally, it explained how to develop navigation applications using C++ and behavior trees to automate robot movement. The chapter included guides on installing, configuring, and running Nav2 in simulations and on re al robots.

In the next chapter, we will see how to work with a robotic arm using ROS 2 and MoveIt2!