How to Create a ROS 2 Python Publisher – Jazzy

In this tutorial, we will create a Python publisher for ROS 2. Knowing how to write a publisher node is one of the most important skills in robotics software engineering. 

In ROS 2 (Robot Operating System 2), a Python publisher is a script written in Python that sends messages across the ROS network to other parts of the system.

On a real robot, you will write many different publishers that publish data that gets shared by the different components of a robot: strings, LIDAR scan readings, ultrasonic sensor readings, camera frames, 3D point cloud data, integers, float values, battery voltage readings, odometry data, and much more. 

The official instructions for creating a publisher are here, but I will walk you through the entire process, step by step.

Follow along with me click by click, keystroke by keystroke.

We will be following the ROS 2 Python Style Guide.

Let’s get started!

Prerequisites

Understand Important ROS 2 Vocabulary

Before we write our first publisher node, let’s understand some ROS 2 vocabulary.

What Are Publisher Nodes?

In a complex robot, you are going to have many pieces of code in your system that need to communicate with each other. 

For example, the code that is responsible for making navigation decisions needs to subscribe to laser scan messages from the LIDAR to be able to avoid obstacles properly. 

You might have another piece of code that reads from the robot’s battery and publishes the percentage battery remaining.

In ROS 2, the parts of your system that are responsible for publishing messages to the rest of the robot – like the distance to an obstacle – are known as publisher nodes. These nodes are usually written in C++ and Python.

You have many different types of built-in messages that you can publish over ROS 2. 

For example, if you want to send distance information from a LIDAR sensor, you have a special sensor message called LaserScan. You can see the definition of this message type on this link.

For battery health, you even have a special sensor message type for that called BatteryState.

You also have other sensor message types, which you can see on this list.

In a previous tutorial, we published the text message “Hello World” from a publisher node called talker. This message type is a string, which is one of the standard message types in ROS 2. 

On this link, you can see we have standard message types for integers, floating-point numbers, booleans (like True and False), and many more.

The beauty of ROS 2 is that there is a message type for 95% of robotic scenarios. For the other 5%, you can create your own custom message type. I will show you how to do that in a future tutorial.

What Are Subscriber Nodes?

The parts of your system that subscribe to messages sent from publishers are known as subscriber nodes. 

Subscriber nodes are pieces of code, usually written in C++ or Python, that are responsible for receiving information. 

For example, the robot’s path planning code could be a subscriber node since it subscribes to LIDAR data to plan a collision-free path from an initial location to a goal location.

What Are Messages?

Messages are the data packets that the publisher nodes send out. They can include information like LIDAR scan data, camera images, ultrasonic sensor readings, numbers, text, or even complex data structures. 

You can find a master list of the different types of messages by going here to the ROS 2 documentation. You even have other message types to represent things like bounding boxes for object detection.

What Are Topics?

Topics are the named channels over which messages are sent out. 

For example, in many real-world mobile robotics applications where you are using a LIDAR, messages about the distance to obstacles are sent on a topic named “/scan”. By convention, the name of a topic in ROS 2 has a leading forward slash before the name.

Topics allow different parts of a robot or rather different nodes in a robotic system to communicate with each other by subscribing to and publishing messages on these named channels.

Write the Code

Now that we have covered some fundamental terminology, let’s write some code.

cd ~/ros2_ws/ && code .

First, right-click on src/ros2_fundamentals/

Type “ros2_fundamentals_examples” to create a new folder for our Python script.

1-scripts-folder

Pay careful attention to the name of the folder where we will house our Python scripts. The name of this folder must have the same name as the package. 

Right-click on the ros2_fundamentals_examples folder to create a new publisher file called “py_minimal_publisher.py”.

Type the following code inside py_minimal_publisher.py:

#! /usr/bin/env python3

"""
Description:
    This ROS 2 node periodically publishes "Hello World" messages on a topic.
    It demonstrates basic ROS concepts such as node creation, publishing, and
    timer usage.
-------
Publishing Topics:
    The channel containing the "Hello World" messages
    /py_example_topic - std_msgs/String
-------
Subscription Topics:
    None
-------
Author: Addison Sears-Collins
Date: November 4, 2024
"""

import rclpy  # Import the ROS 2 client library for Python
from rclpy.node import Node  # Import the Node class for creating ROS 2 nodes

from std_msgs.msg import String  # Import the String message type for publishing


class MinimalPyPublisher(Node):
    """Create MinimalPyPublisher node.

    """

    def __init__(self):
        """ Create a custom node class for publishing messages

        """

        # Initialize the node with a name
        super().__init__('minimal_py_publisher')

        # Creates a publisher on the topic "topic" with a queue size of 10 messages
        self.publisher_1 = self.create_publisher(String, '/py_example_topic', 10)

        # Create a timer with a period of 0.5 seconds to trigger the callback function
        timer_period = 0.5  # seconds
        self.timer = self.create_timer(timer_period, self.timer_callback)

        # Initialize a counter variable for message content
        self.i = 0

    def timer_callback(self):
        """Callback function executed periodically by the timer.

        """
        # Create a new String message object
        msg = String()

        # Set the message data with a counter
        msg.data = 'Hello World: %d' % self.i

        # Publish the message on the topic
        self.publisher_1.publish(msg)

        # Log a message indicating that the message has been published
        self.get_logger().info('Publishing: "%s"' % msg.data)

        # Increment the counter for the next message
        self.i = self.i + 1


def main(args=None):
    """Main function to start the ROS 2 node.

    Args:
        args (List, optional): Command-line arguments. Defaults to None.
    """

    # Initialize ROS 2 communication
    rclpy.init(args=args)

    # Create an instance of the MinimalPublisher node
    minimal_py_publisher = MinimalPyPublisher()

    # Keep the node running and processing events.
    rclpy.spin(minimal_py_publisher)

    # Destroy the node explicitly
    # (optional - otherwise it will be done automatically
    # when the garbage collector destroys the node object)
    minimal_py_publisher.destroy_node()

    # Shutdown ROS 2 communication
    rclpy.shutdown()


if __name__ == '__main__':
    # Execute the main function if the script is run directly
    main()

I added detailed comments to the code so you can understand what each piece is doing.

To generate the comments for each class and function, you follow these steps for the autoDocstring package.

Your cursor must be on the line directly below the definition of the function or class to generate all the comments.

Then press enter after opening docstring with triple quotes (“””).

What we are going to do in this node is publish the string “Hello World” to a topic named /py_example_topic. The string message will also contain a counter that keeps track of how many times the message has been published.

We chose the name /py_example_topic for the topic, but you could have chosen any name.

Create the __init__.py file

Now, we need to configure our package so that ROS 2 can discover this Python node we just created. To do that, we need to create a special initialization file.

Right-click on the name of the ros2_ws/src/ros2_fundamentals_examples/ros2_fundamentals_examples folder, and create an empty script called

__init__.py

Here is what the file should look like:

2-init-py

The presence of _ _init_ _.py explicitly designates a directory as a Python package. This enables Python’s import machinery to recognize and treat it as a cohesive collection of Python code.

Create a README.md

Now let’s create a README.md file. A README.md file is a plain text file that serves as an introduction and explanation for a project, software, or package. It’s like a welcome mat for anyone encountering your work, providing essential information and guidance to get them started.

Right-click on the package (…/src/ros2_fundamentals_examples/), and create a new file named README.md.

3-readme-file

You can find a syntax guide on how to write a README.md file here on GitHub.

To see what the README.md file looks like, you can right-click on README.md on the left pane and click “Open Preview”.

# ROS 2 Fundamentals Examples

This package contains examples demonstrating fundamental ROS 2 concepts and patterns.

## Description

The package includes minimalist ROS 2 code to demonstrate important ROS 2 concepts and patterns.
- Following ROS 2 Python style guidelines

## Prerequisites

- ROS 2 installed
- Python 3
- Created ROS 2 workspace (`ros2_ws`)

## Author

Addison Sears-Collins

Modify the package.xml File

Now let’s open the package.xml file. Make sure it looks like this.

<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
  <name>ros2_fundamentals_examples</name>
  <version>0.0.0</version>
  <description>Basic examples demonstrating ROS 2 concepts</description>
  <maintainer email="automaticaddison@example.com">Addison Sears-Collins</maintainer>
  <license>Apache-2.0</license>
 
  <!--Specify build tools that are needed to compile the package-->
  <buildtool_depend>ament_cmake</buildtool_depend>
  <buildtool_depend>ament_cmake_python</buildtool_depend>
 
  <!--Declares package dependencies that are required for building the package-->
  <depend>rclcpp</depend>
  <depend>rclpy</depend>
  <depend>std_msgs</depend>
 
  <!--Specifies dependencies that are only needed for testing the package-->
  <test_depend>ament_lint_auto</test_depend>
  <test_depend>ament_lint_common</test_depend>
 
  <export>
    <build_type>ament_cmake</build_type>
  </export>
</package>

The package.xml file is an important part of any ROS 2 package. Think of package.xml as your ROS 2 package’s identification card. Just like how your ID card contains essential information about you – your name, date of birth, ID number, and address – package.xml holds key details about your package.

Here’s a breakdown of the key elements you’ll find in a typical package.xml file. You don’t need to memorize this. Just come back to this tutorial if you are ever in doubt:

1. Basic Information:

  • name: The unique identifier for the package, often corresponding to the folder name.
  • version: The package’s version.
  • description: A brief explanation of the package’s purpose and functionality.
  • maintainer: Who is maintaining the package.
  • license: Specifies the license under which the package is distributed, indicating how others are permitted to use, modify, and redistribute the package’s code and other assets.

2. Dependencies:

  • buildtool_depend: Build tools (like compilers) needed for building the package.
  • depend: Package dependencies that are required for building the package. Since we are publishing a message of type std_msgs/String, we need to make sure we declare a dependency on the std_msgs ROS 2 package.
  • test_depend: Tools used for checking the code for bugs and errors.

3. Build Configuration:

  • export: Defines properties and settings used during package installation.
  • build_type: Specifies the build system (e.g., ament_cmake).

Modify the CMakeLists.txt File

Now let’s configure the CMakeLists.txt file. A CMakeLists.txt file in ROS 2 defines how a ROS 2 package should be built. It contains instructions for building and linking the package’s executables, libraries, and other files.
I have commented out sections which we are going to use in the future:

cmake_minimum_required(VERSION 3.8)
project(ros2_fundamentals_examples)

# Check if the compiler being used is GNU's C++ compiler (g++) or Clang.
# Add compiler flags for all targets that will be defined later in the
# CMakeLists file. These flags enable extra warnings to help catch
# potential issues in the code.
# Add options to the compilation process
if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
  add_compile_options(-Wall -Wextra -Wpedantic)
endif()

# Locate and configure packages required by the project.
find_package(ament_cmake REQUIRED)
find_package(ament_cmake_python REQUIRED)
find_package(rclcpp REQUIRED)
find_package(rclpy REQUIRED)
find_package(std_msgs REQUIRED)

# Define a CMake variable named dependencies that lists all
# ROS 2 packages and other dependencies the project requires.
set(dependencies
  rclcpp
  std_msgs
)

# Add the specified directories to the list of paths that the compiler
# uses to search for header files. This is important for C++
# projects where you have custom header files that are not located
# in the standard system include paths.
include_directories(
  include
)

# Tells CMake to create an executable target named minimal_cpp_publisher
# from the source file src/minimal_cpp_publisher.cpp. Also make sure CMake
# knows about the program's dependencies.
#add_executable(minimal_cpp_publisher src/minimal_cpp_publisher.cpp)
#ament_target_dependencies(minimal_cpp_publisher ${dependencies})

#add_executable(minimal_cpp_subscriber src/minimal_cpp_subscriber.cpp)
#ament_target_dependencies(minimal_cpp_subscriber ${dependencies})

# Copy necessary files to designated locations in the project
install (
  DIRECTORY ros2_fundamentals_examples
  DESTINATION share/${PROJECT_NAME}
)

install(
  DIRECTORY include/
  DESTINATION include
)

# Install cpp executables
#install(
#  TARGETS
#  minimal_cpp_publisher
#  minimal_cpp_subscriber
#  DESTINATION lib/${PROJECT_NAME}
#)

# Install Python modules for import
ament_python_install_package(${PROJECT_NAME})

# Add this section to install Python scripts
install(
  PROGRAMS
  ros2_fundamentals_examples/py_minimal_publisher.py
  DESTINATION lib/${PROJECT_NAME}
)

# Automates the process of setting up linting for the package, which
# is the process of running tools that analyze the code for potential
# errors, style issues, and other discrepancies that do not adhere to
# specified coding standards or best practices.
if(BUILD_TESTING)
  find_package(ament_lint_auto REQUIRED)
  # the following line skips the linter which checks for copyrights
  # comment the line when a copyright and license is added to all source files
  set(ament_cmake_copyright_FOUND TRUE)
  # the following line skips cpplint (only works in a git repo)
  # comment the line when this package is in a git repo and when
  # a copyright and license is added to all source files
  set(ament_cmake_cpplint_FOUND TRUE)
  ament_lint_auto_find_test_dependencies()
endif()

# Used to export include directories of a package so that they can be easily
# included by other packages that depend on this package.
ament_export_include_directories(include)

# Generate and install all the necessary CMake and environment hooks that
# allow other packages to find and use this package.
ament_package()

The standard sections of a CMakeLists.txt file for ROS 2 are as follows:

1. cmake_minimum_required(VERSION X.X)

Specifies the minimum required version of CMake for building the package. This is typically set to a version that is known to be compatible with ROS 2.

2. project(ros2_fundamentals_examples)

Specifies the name of the ROS 2 package. 

3. find_package(ament_cmake REQUIRED)

Finds and loads the necessary dependencies for the ROS 2 package. 

4. set(dependencies…):

Lists all the packages and libraries needed by the project.

6. include_directories(include):

Tells the compiler where to find header files for C++ code. We aren’t going to use this line yet because our publisher is written in Python.

7. add_executable(…): 

Creates an executable program using the specified source file. We will add this publisher in the next tutorial.

8. ament_target_dependencies(<program name>. ${dependencies}): 

Links the program with the required dependencies.

9. install(DIRECTORY <project_name> scripts DESTINATION share/${PROJECT_NAME}): 

Copies folders to the project’s install directory for sharing.

10. install(DIRECTORY include/ DESTINATION include): 

Installs header files to the project’s install directory.

11. install(TARGETS <program names go here separated by space> DESTINATION lib/${PROJECT_NAME}): 

Installs the built C++ programs to the project’s install directory. We will write these C++ programs later. 

12. ament_python_install_package(${PROJECT_NAME}): 

Installs Python modules for the project.

13. if(BUILD_TESTING) … endif():

Sets up code checking (linting) if testing is enabled.

14. ament_export_include_directories(include): 

Allows other packages to use this package’s header files.

15. ament_package(): 

Generates necessary files for other packages to find and use this package.

Build the Workspace

Now that we have created our script and configured our build files, we need to build everything into executables so that we can run our code.

Open a terminal window, and type:

build

If this command doesn’t work, type these commands:

echo "alias build='cd ~/ros2_ws/ && colcon build && source ~/.bashrc'" >> ~/.bashrc
build

Run the Node 

Let’s run our node. Here’s the general syntax:

ros2 run <package_name> <python_script_name>.py

Here’s a breakdown of the components:

  • <package_name>: Replace this with the name of your ROS 2 package containing the Python script.
  • <python_script_name>.py: Replace this with the name of your Python script file that contains the ROS 2 node.

Note that, you can use the tab button to autocomplete a partial command. For example, type the following and then press the TAB button on your keyboard. 

ros2 run ros2_fundamentals_examples py [TAB]

After autocompletion, the command looks like this:

ros2 run ros2_fundamentals_examples py_minimal_publisher.py

Now, press Enter.

Here is what the output looks like:

4-output-terminal

Examine Common ROS 2 Commands

Topics

Open a new terminal window.

Let’s see a list of all currently active topics.

ros2 topic list
5-ros2-topic-list

We see we have three active topics:

/parameter_events and /rosout topics appear even when no nodes are actively running due to the presence of system-level components and the underlying architecture of the ROS 2 middleware. 

The /parameter_events topic facilitates communication about parameter changes, and the /rosout topic provides a centralized way to access log messages generated by different nodes within the ROS 2 network. You can ignore both topics.

/py_example_topic is the topic we created with our Python node. Let’s see what data is being published to this topic.

ros2 topic echo /py_example_topic

You can see the string message that is being published to this topic, including the counter integer we created in the Python script.

6-ros2-topic-echo

Press CTRL + C in the terminal to stop the output.

At what frequency is data being published to this topic?

ros2 topic hz /py_example_topic

Data is being published at 2Hz, or every 0.5 seconds.

7-ros2-topic-hz

Press CTRL + C in the terminal to stop the output.

What type of data is being published to this topic, and how many nodes are publishing to this topic?

ros2 topic info /py_example_topic
8-ros2-topic-info

To get more detailed information about the topic, you could have typed:

ros2 topic info /py_example_topic --verbose
9-py-example-topic-verbose

You can see a list of the ROS 2 topic commands at this page here.

Nodes

What are the currently active nodes?

ros2 node list
10-ros2-node-list

Let’s find out some more information about our node.

ros2 node info /minimal_py_publisher
11-minimal-py-publisher

Check out how all the nodes are communicating using this command:

rqt_graph

Close the Node

Now go back to the terminal where your py_minimal_publisher.py script is running and press CTRL + C to stop its execution.

To clear the terminal window, type:

clear

Congratulations! You have written your first publisher in ROS 2.

In this example, you have written a publisher to publish a basic string message. And although it is not the most exciting node, it is similar to the kinds of nodes you will write again and again over the course of your robotics career.

On a real robot, you will write many different publishers that publish data that gets shared by the different components of a robot: strings, LIDAR scan readings, ultrasonic sensor readings, camera frames, 3D point cloud data, integers, float values, battery voltage readings, odometry data, and much more. 

The code you wrote in this tutorial serves as a template for creating these more complex publishers. All publishers in ROS 2 are based on the same basic framework as the node you just wrote, py_minimal_publisher.py.

That’s it. Keep building!

How to Create a ROS 2 Package – Jazzy

In this tutorial, we will create a ROS 2 package. The official instructions for creating a package are here, but I will walk you through the entire process, step by step.

Follow along with me click by click, keystroke by keystroke.

Prerequisites

What is a Package?

In ROS 2, a package is a folder that contains files related to a specific functionality or a component of a robotic system.

This folder includes things like:

  • The actual code that makes the package do what it’s supposed to do.
  • Files that help define how the code should be started and set up.
  • Any special message types or configurations the package needs to work properly.

ROS 2 packages are designed to perform specific jobs. For example, consider a robot that needs to determine its position and orientation within a given environment. 

In ROS 2, you could create a package called “localization” to handle this specific task.

The “localization” package would contain:

  • The code that processes data from the robot’s sensors (e.g., cameras or LIDAR) and uses algorithms to estimate the robot’s position and orientation.
  • A file, known as a README file, that explains the purpose of the package and how to install the code.
  • Any custom message the package needs to share localization data with other parts of the robot’s software, such as the estimated position and orientation.

By organizing the localization functionality into its own ROS 2 package, you can focus on developing and refining the algorithms and code specific to localization without worrying about other aspects of the robot’s software. 

This modular approach makes it easier to maintain, debug, and improve the localization capabilities of your robot, and allows you to reuse the package across different projects or robots that require similar localization features.

For a real-world robotics project, you will combine multiple packages together to create a complete robotic application that performs various tasks and functions. 

Create the Package

Let’s create our first ROS 2 package.

Open a terminal window.

Type the following commands

cd ~/ros2_ws/src

Best practice is to create your ROS 2 packages inside the src directory.

Now let’s run the ros2 command for creating our first package.

ros2 pkg create --build-type ament_cmake --license Apache-2.0 ros2_fundamentals_examples

This command creates a new ROS 2 package named ros2_fundamentals_examples. We could have called our package any name, but I chose to call it ros2_fundamentals_examples.

  • –build-type ament_cmake specifies that the package should use the ament_cmake build system, which is the recommended build system for ROS 2 packages written in C++. Think of it as a set of instructions and tools that help you put together all the pieces of your ROS 2 package, making sure everything is properly compiled, linked, and ready to run.
  • –license Apache-2.0 sets the license for the package to Apache License 2.0, which is a license that has minimal restrictions on how others can use, modify, and distribute the software.

Now let’s build our new package. First navigate to the root of the workspace.

cd ~/ros2_ws
colcon build 
1-colcon-build

Let’s see if our new package is recognized by ROS 2.

Either open a new terminal window or source the bashrc file like this:

source ~/.bashrc
ros2 pkg list

You can see the newly created package right there at the top.

2-ros2-fundamental-package

Add the “build” Alias to the Bashrc File

Now open a terminal window, and type this:

echo "alias build='cd ~/ros2_ws && colcon build'" >> ~/.bashrc && source ~/.bashrc

This single command adds the alias called “build” to your .bashrc file. Anytime you want to build all the packages in your ros2 workspace, all you have to do now is type:

build
3-build-alias

To build a specific package, you would type:

colcon build --packages-select ros2_fundamentals_examples

Press Enter to execute the command and build the selected package.

7-build-specific-package

Install Useful Packages (Optional but Recommended)

Let’s install some useful external packages that will help us along the way. 

If you don’t have Terminator, install it now. Terminator lets you have multiple terminal windows open within a single interface.

Type the following command:

sudo apt-get update -y && sudo apt-get upgrade -y && sudo apt-get install terminator -y

To open terminator, you can either click the ring in the bottom left of your Desktop (i.e. “Show Apps” button) and search for “terminator,” or you can type terminator in a regular terminal window.

8-show-apps
9-terminator

You can right-click to split the terminal into different panels.

Let’s install some useful ROS 2 packages. You don’t need to worry about what these packages do for now. 

Open a terminal window, and type the following:

sudo curl -sSL https://raw.githubusercontent.com/ros/rosdistro/master/ros.key -o /usr/share/keyrings/ros-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/ros-archive-keyring.gpg] http://packages.ros.org/ros2/ubuntu noble main" | sudo tee /etc/apt/sources.list.d/ros2.list
sudo apt update
sudo apt-get install -y ros-${ROS_DISTRO}-ros-gz ros-${ROS_DISTRO}-gz-ros2-control ros-${ROS_DISTRO}-gz-ros2-control-demos ros-${ROS_DISTRO}-joint-state-publisher-gui ros-${ROS_DISTRO}-moveit ros-${ROS_DISTRO}-xacro ros-${ROS_DISTRO}-ros2-control ros-${ROS_DISTRO}-ros2-controllers libserial-dev python3-pip

That’s it! Keep building!

How to Use the Standard Template Library (STL) in C++

In this tutorial, we will learn how to use the Standard Template Library (STL) in C++.

Prerequisites

Working with Double-Ended Queues (Deques)

Let’s explore how to use deques in C++ for managing sensor data streams and other robotics applications. Deques are particularly useful when you need to process data from both ends of a collection efficiently. 

Open a terminal window, and type this:

cd ~/Documents/cpp_tutorial 
code . 

Now, let’s create a new C++ file and name it sensor_data_handling.cpp.

Type the following code into the editor:

#include <iostream>
#include <deque>

int main() {
    // Simulating a stream of sensor data
    std::deque<float> sensor_data;

    // Adding new readings at the back
    sensor_data.push_back(2.5);
    sensor_data.push_back(3.1);
    sensor_data.push_back(4.7);

    // Processing new reading at the front
    std::cout << "Processing sensor reading: " << sensor_data.front() << std::endl;
    sensor_data.pop_front();

    // More readings are added
    sensor_data.push_back(5.5);
    sensor_data.push_back(6.8);

    // Processing another reading
    std::cout << "Processing sensor reading: " << sensor_data.front() << std::endl;
    sensor_data.pop_front();

    // Display remaining data
    std::cout << "Remaining sensor data:";
    for (float reading : sensor_data) {
        std::cout << ' ' << reading;
    }
    std::cout << std::endl;

    return 0;
}

Run the code.

1-sensor-handling

You should see how the sensor readings are processed and the status of the queue after each operation.

This example demonstrates how deques can be effectively used in robotics to handle data streams where the newest data might need immediate processing and older data needs to be cleared after handling. This is important for maintaining real-time performance in systems like autonomous vehicles or robotic sensors.

Employing Iterators

Let’s explore how to employ iterators in C++ for robotics applications. Iterators provide a flexible way to traverse and manipulate elements in containers, such as vectors and arrays, which are commonly used in robotics to store and process data.

Let’s start by creating a new C++ file and naming it iterator_example.cpp.

Type the following code into the editor:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> sensor_data = {10, 20, 30, 40, 50};
    
    // Using iterators to traverse and print the vector
    for (auto it = sensor_data.begin(); it != sensor_data.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;
    
    // Using iterators to modify elements in the vector
    for (auto it = sensor_data.begin(); it != sensor_data.end(); ++it) {
        *it *= 2;
    }
    
    // Printing the modified vector
    for (const auto& value : sensor_data) {
        std::cout << value << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

In this code, we include the necessary headers: iostream for input/output operations and vector for the vector container.

In the main function, we create a vector named sensor_data to represent a collection of sensor readings. We initialize it with some sample values.

We use iterators to traverse and print the elements of the vector. We create an iterator it and initialize it to sensor_data.begin(), which points to the first element. 

We iterate until it reaches sensor_data.end(), which is the position after the last element. Inside the loop, we dereference the iterator using *it to access the value at the current position and print it.

Next, we use iterators to modify the elements in the vector. We create another iterator it and iterate over the vector as before. This time, we dereference the iterator and multiply the value by 2, effectively doubling each element.

Finally, we print the modified vector using a range-based for loop, which automatically uses iterators under the hood to traverse the vector.

Run the code.

2-iterator-example

You should see the original vector printed, followed by the modified vector with each element doubled.

Working with Deques, Lists, and Forward lists

Let’s explore how to work with deques, lists, and forward lists in C++ for robotics applications. These container types offer different characteristics and are useful in various scenarios when dealing with robotic data and algorithms.

Let’s start by creating a new C++ file and naming it container_example.cpp.

Type the following code into the editor:

#include <iostream>
#include <deque>
#include <list>
#include <forward_list>

int main() {
    // Working with deques
    std::deque<int> robot_positions = {10, 20, 30};
    robot_positions.push_front(5);
    robot_positions.push_back(40);
    std::cout << "Deque: ";
    for (const auto& pos : robot_positions) {
        std::cout << pos << " ";
    }
    std::cout << std::endl;

    // Working with lists
    std::list<std::string> robot_actions = {"move", "rotate", "scan"};
    robot_actions.push_back("grasp");
    robot_actions.push_front("initialize");
    std::cout << "List: ";
    for (const auto& action : robot_actions) {
        std::cout << action << " ";
    }
    std::cout << std::endl;

    // Working with forward lists
    std::forward_list<double> sensor_readings = {1.5, 2.7, 3.2};
    sensor_readings.push_front(0.8);
    std::cout << "Forward List: ";
    for (const auto& reading : sensor_readings) {
        std::cout << reading << " ";
    }
    std::cout << std::endl;

    return 0;
}

In this code, we include the necessary headers: iostream for input/output operations, deque for the deque container, list for the list container, and forward_list for the forward list container.

In the main function, we demonstrate working with each container type:

  • Deque: We create a deque named robot_positions to store integer positions. We use push_front() to add an element at the front and push_back() to add an element at the back. We then print the contents of the deque using a range-based for loop.
  • List: We create a list named robot_actions to store string actions. We use push_back() to add an element at the back and push_front() to add an element at the front. We print the contents of the list using a range-based for loop.
  • Forward List: We create a forward list named sensor_readings to store double readings. We use push_front() to add an element at the front. We print the contents of the forward list using a range-based for loop.

Run the code.

3-container-example

You will see the contents of each container printed in the terminal.

Deques allow efficient insertion and deletion at both ends, lists provide constant-time insertion and deletion anywhere in the container, and forward lists offer a singly-linked list with efficient insertion and deletion at the front.

Handling Sets and Multisets

Let’s explore how to handle sets and multisets in C++ for robotics applications. Sets and multisets are associative containers that store unique and duplicate elements, respectively, and they can be useful for managing distinct or repeated data in robotic systems.

Let’s start by creating a new C++ file and naming it set_example.cpp.

Type the following code into the editor: 

#include <iostream>
#include <set>

int main() {
    // Handling sets
    std::set<int> unique_landmarks = {10, 20, 30, 20, 40, 30};
    std::cout << "Unique Landmarks: ";
    for (const auto& landmark : unique_landmarks) {
        std::cout << landmark << " ";
    }
    std::cout << std::endl;

    // Handling multisets
    std::multiset<std::string> repeated_commands = {"move", "rotate", "scan", "move", "grasp"};
    std::cout << "Repeated Commands: ";
    for (const auto& command : repeated_commands) {
        std::cout << command << " ";
    }
    std::cout << std::endl;

    return 0;
}

In this code, we include the necessary headers: iostream for input/output operations and set for the set and multiset containers.

In the main function, we demonstrate handling sets and multisets:

  • Set: We create a set named unique_landmarks to store unique integer landmarks. We initialize it with some values, including duplicates. The set automatically removes the duplicate elements and stores only the unique values. We print the contents of the set using a range-based for loop.
  • Multiset: We create a multiset named repeated_commands to store repeated string commands. We initialize it with some values, including duplicates. The multiset allows duplicate elements and stores all the occurrences. We print the contents of the multiset using a range-based for loop.

Run the code.

4-set-example

You will see the unique landmarks printed from the set and the repeated commands printed from the multiset.

Sets are useful when you need to store and efficiently retrieve unique elements, such as distinct landmarks or sensor readings. Multisets, on the other hand, allow you to store and manage duplicate elements, which can be helpful for tracking repeated commands or measurements in robotic systems.

Using Map and Multimaps

Let’s explore how to use map and multimap in C++ for robotics applications. Map and multimap are associative containers that store key-value pairs, allowing efficient lookup and retrieval of values based on their associated keys.

Let’s start by creating a new C++ file and naming it map_example.cpp.

Type the following code into the editor:

#include <iostream>
#include <map>
#include <string>

int main() {
    // Using map
    std::map<std::string, int> sensor_readings;
    sensor_readings["temperature"] = 25;
    sensor_readings["humidity"] = 60;
    sensor_readings["pressure"] = 1013;

    for (const auto& reading : sensor_readings) {
        std::cout << reading.first << ": " << reading.second << std::endl;
    }

    // Using multimap
    std::multimap<std::string, std::string> robot_commands;
    robot_commands.insert({"move", "forward"});
    robot_commands.insert({"move", "backward"});
    robot_commands.insert({"rotate", "left"});
    robot_commands.insert({"rotate", "right"});

    for (const auto& command : robot_commands) {
        std::cout << command.first << ": " << command.second << std::endl;
    }

    return 0;
}

In this code, we include the necessary headers: iostream for input/output operations, map for the map and multimap containers, and string for string manipulation.

In the main function, we first demonstrate the usage of map. We create a map named sensor_readings that associates sensor names (keys) with their corresponding values. We insert key-value pairs into the map using the [] operator. We then iterate over the map using a range-based for loop and print each key-value pair.

Next, we demonstrate the usage of multimap. We create a multimap named robot_commands that associates command types (keys) with their corresponding parameters (values). We insert key-value pairs into the multimap using the insert() function. 

Multimap allows duplicate keys, so we can have multiple entries with the same command type. We iterate over the multimap using a range-based for loop and print each key-value pair.

Run the code.

5-map-example

You will see the sensor readings and robot commands printed in the terminal, demonstrating the usage of map and multimap.

Map is useful when you need to associate unique keys with their corresponding values, such as storing sensor readings or configuration parameters. 

Multimap allows duplicate keys and is helpful when you need to store multiple values for the same key, such as mapping command types to their parameters.

Manipulating Stack and Queue

Let’s explore how to manipulate stacks and queues in C++, essential data structures for various robotics applications.

Create a new C++ file called stack_queue_example.cpp.

Type the following code into the editor:

#include <iostream>
#include <stack>
#include <queue>

int main() {
    // Stack example
    std::stack<int> my_stack;
    my_stack.push(10);
    my_stack.push(20);
    my_stack.push(30);

    std::cout << "Top element of the stack: " << my_stack.top() << std::endl;
    my_stack.pop(); // Removes the top element (30)

    std::cout << "Updated top element: " << my_stack.top() << std::endl;

    // Queue example
    std::queue<std::string> my_queue;
    my_queue.push("Sensor data");
    my_queue.push("Robot command");
    my_queue.push("Navigation goal");

    std::cout << "Front element of the queue: " << my_queue.front() << std::endl;
    my_queue.pop(); // Removes the front element ("Sensor data")

    std::cout << "Updated front element: " << my_queue.front() << std::endl;

    return 0;
}

First, we create a stack my_stack to store integers. We push the values 10, 20, and 30 onto the stack using the push method. 

We then print the top element of the stack using the top method, which returns 30. 

Next, we remove the top element from the stack using the pop method. 

Finally, we print the updated top element, which is now 20.

For the queue example, we create a queue my_queue to store strings. 

We add the strings “Sensor data”, “Robot command”, and “Navigation goal” using the push method. 

We then print the front element of the queue using the front method, which returns “Sensor data”. 

Next, we dequeue (pronounced as “dee-queue”) the front element using the pop method. 

Finally, we print the updated front element, which is now “Robot command”.

Run the code.

stack

You will see the top and front elements of the stack and queue, respectively, printed in the terminal.

Implementing Priority Queues

Let’s explore how priority queues can be utilized in C++ to manage robotic tasks efficiently. 

Priority queues are particularly useful in robotics for scheduling tasks based on their priority level, ensuring that critical operations like obstacle avoidance or emergency stops are handled first.

Let’s begin by creating a new C++ file named robotic_tasks_priority_queue.cpp.

Type the following code into the editor:

#include <iostream>
#include <queue>
#include <vector>
#include <functional>  // For std::greater

struct Task {
    int priority;
    std::string description;

    // Operator overloading for priority comparison
    bool operator<(const Task& other) const {
        return priority < other.priority;  // Higher numbers mean higher priority
    }
};

int main() {
    // Create a priority queue to manage tasks
    std::priority_queue<Task> tasks;

    // Insert tasks
    tasks.push({2, "Navigate to charging station"});
    tasks.push({1, "Send sensor data"});
    tasks.push({3, "Emergency stop"});

    // Execute tasks based on priority
    while (!tasks.empty()) {
        Task task = tasks.top();
        tasks.pop();
        std::cout << "Executing task: " << task.description << std::endl;
    }

    return 0;
}

In this code, we define a Task struct with a priority and description. 

We overload the < operator to compare tasks based on their priority. 

We then create a priority queue that holds tasks and insert three sample tasks into it. 

We simulate the execution of tasks in order of their priority, with the emergency task taking precedence.

Run the code.

7-priority-queue

You will see the tasks being executed in order of their priority, with the emergency stop being handled first.

Thanks, and I’ll see you in the next tutorial.

Keep building!