<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shashank Goyal on Medium]]></title>
        <description><![CDATA[Stories by Shashank Goyal on Medium]]></description>
        <link>https://medium.com/@shashank-goyal-blogs?source=rss-e85e3a6012ba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*f6BFa9ezvvqGThmHRm3Nzw.jpeg</url>
            <title>Stories by Shashank Goyal on Medium</title>
            <link>https://medium.com/@shashank-goyal-blogs?source=rss-e85e3a6012ba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:15:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shashank-goyal-blogs/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Mastering ROS2: Orchestrating Your Robot’s Architecture with Nodes and Launch Files]]></title>
            <link>https://faun.pub/mastering-ros2-orchestrating-your-robots-architecture-with-nodes-and-launch-files-2e8aae3fc917?source=rss-e85e3a6012ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e8aae3fc917</guid>
            <category><![CDATA[ros2]]></category>
            <category><![CDATA[robot-operating-system]]></category>
            <category><![CDATA[begginers-guide]]></category>
            <category><![CDATA[robotics-development]]></category>
            <category><![CDATA[robotics]]></category>
            <dc:creator><![CDATA[Shashank Goyal]]></dc:creator>
            <pubDate>Mon, 13 Jan 2025 00:34:19 GMT</pubDate>
            <atom:updated>2025-01-31T12:43:49.150Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*s1mKAoHEhar1hXkavPFnkQ.png" /></figure><h4><strong>Introduction</strong></h4><p>Have you ever wondered how ROS2 applications seamlessly coordinate multiple processes — from sensor drivers to complex control nodes? That’s where nodes and launch files come into play. In the ROS2 world, nodes are the building blocks of your robotics software, each node responsible for a specific functionality. But managing numerous nodes across different packages can quickly become challenging. Launch files come to the rescue by giving you a unified approach to start, configure, and orchestrate multiple nodes at once.</p><p>If you’re new here or want a refresher on how to set up a ROS2 environment (with GUI support) in a Docker container, check out my <a href="https://medium.com/@shashank-goyal-blogs/ros2-humble-gui-docker-container-a-step-by-step-guide-c541b73fe141"><strong>ROS2 Humble GUI-Docker Container</strong></a> blog. For a deep dive into fundamental ROS2 concepts like topics, services, and actions, see my earlier blog on <a href="https://shashank-goyal-blogs.medium.com/mastering-ros2-your-ultimate-beginners-guide-to-robotics-a72179db4c84"><strong>Mastering ROS2: Your Ultimate Beginner’s Guide to Robotics</strong></a>. To learn about creating custom interfaces and harnessing ROS2 parameters, explore my subsequent blogs on <a href="https://shashank-goyal-blogs.medium.com/mastering-ros2-building-robust-communication-with-custom-messages-services-and-actions-9a49b4cd8b16"><strong>Building Robust Communication with Custom Messages, Services, and Actions</strong></a>, and <a href="https://shashank-goyal-blogs.medium.com/mastering-ros2-harnessing-the-power-of-ros2-parameters-for-real-time-configuration-afd4c3890fc9"><strong>Harnessing the Power of ROS2 Parameters for Real-Time Configuration</strong></a>.</p><p>In this blog, we’ll unravel the power of nodes and launch files in ROS2. We’ll also showcase how to work with arguments and parameters to configure your nodes, both individually and in a multi-node orchestration scenario.</p><h3>Nodes: The Fundamental Units of ROS2</h3><h4>What Are Nodes, and Why Do They Matter?</h4><p>Nodes are the executables in a ROS2 system, each designed to handle a specific task. A node could be responsible for reading sensor data, another could handle motor control, and yet another might process computer vision. This distributed approach prevents monolithic codebases and allows you to develop, debug, and deploy components independently.</p><h4>Defining Nodes in Code</h4><ul><li><strong>In C++</strong>, a node is typically a class inheriting from rclcpp::Node. You’d place its declaration in a header file (e.g., include/my_package/my_node.hpp) and its definition in a corresponding source file (e.g., src/my_node.cpp). A separate main.cpp (or similarly named file) creates an instance of that node and spins it.</li><li><strong>In Python</strong>, you usually define a node class that inherits from rclpy.node.Node and place it in a .py file. You might also have an __init__.py to treat the directory as a Python module.<br>Sometimes people prefer adding the respective main() function calls to spin the node within the node definition file such as my_node.cpp or my_node.py.</li></ul><h4>Interacting with the ROS2 Ecosystem</h4><p>Nodes can publish and subscribe to topics, offer or call services, and even use actions for complex tasks. They also support parameters and arguments, allowing you to configure behaviors at runtime without modifying the codebase.</p><h4>Creating, Running, and Stopping Nodes</h4><ul><li><strong>Creating:</strong> Use ros2 pkg create &lt;package_name&gt; to scaffold a new ROS2 package. Then implement your node in either C++ or Python files.</li><li><strong>Running:</strong> Use ros2 run &lt;package_name&gt; &lt;executable_name&gt; for executables (C++) or ros2 run &lt;package_name&gt; &lt;python_script&gt; for Python nodes.</li><li><strong>Stopping:</strong> Press Ctrl + C in the terminal where the node is running.</li><li><strong>Debugging:</strong> Add RCLCPP_INFO, RCLCPP_WARN, or RCLCPP_ERROR (C++) or self.get_logger().info(), warn(), or error() (Python) for logging. You can also attach a debugger (like GDB for C++ or use pdb for Python).</li></ul><h4>Using Arguments and Parameters in Nodes</h4><ol><li><strong>Arguments:</strong> Typically passed via --ros-args -p param_name:=value or custom arguments that your node parses.</li><li><strong>Parameters:</strong> Declared in code with declare_parameter() and retrieved with get_parameter(). You can also load them from YAML files or set them at runtime.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9m9ChFakKPEj2GsJwCoHoA.png" /><figcaption>Node Interactions in the ROS2 Ecosystem</figcaption></figure><p>The above diagram offers a comprehensive overview of a ROS2 node:</p><ul><li><strong>ROS2 Node Core:</strong> We see that each node is an independent executable with unique identification, core task-specific logic, and dynamic configuration through parameters and arguments. This underscores that nodes manage their own resources, accept runtime parameters (potentially loaded from YAML files), and support command-line arguments for flexible behavior.</li><li><strong>Implementation Choices:</strong> We should note the decision factors—performance, team expertise, integration requirements—guiding the choice between languages, and file structuring.</li><li><strong>Node Lifecycle Management:</strong> We can see that the lifecycle stages of a node are: <br>- <strong>Creation:</strong> Using ROS2 CLI commands to scaffold packages. <br>- <strong>Execution:</strong> Running the node which initializes and spins within an event loop. <br>- <strong>Termination:</strong> Stopping the node cleanly with Ctrl+C or programmatically, ensuring resources are released.</li><li><strong>Inter-Node Communication:</strong> Finally, we see the different communication methods — publishers, subscribers, services, and actions — depicting how nodes exchange data and coordinate tasks. It emphasizes the variety of patterns (one-to-many with topics, synchronous requests with services, long-running actions) that ROS2 nodes use to interact within the network.</li></ul><h3>Launch Files: The Orchestrators of ROS2</h3><h4>Why Use Launch Files?</h4><p>When your application has more than a couple of nodes, starting them one by one becomes tedious and prone to errors. Launch files let you define the entire startup sequence in one place. You can specify nodes, their arguments, parameters, environment variables, and more.</p><h4>Anatomy of a Launch File</h4><p>In ROS2, launch files are typically Python scripts (.launch.py). Here’s what you can do inside a launch file:</p><ul><li><strong>Start Multiple Nodes:</strong> Each node is defined by a Node() object specifying package, executable, and optional parameters or arguments.</li><li><strong>Set Parameters:</strong> Load YAML configurations or set parameters inline.</li><li><strong>Use Arguments:</strong> Parse command-line arguments to customize node behavior (e.g., to choose between simulation and real hardware).</li><li><strong>Remapping:</strong> Change topic or service names at runtime.</li><li><strong>Namespaces:</strong> Group nodes logically under a namespace, helping to avoid name collisions.</li><li><strong>Include Other Launch Files:</strong> Reuse launch files within bigger launch setups.</li><li><strong>Environment Variables:</strong> For advanced control, pass environment variables to nodes.</li><li><strong>get_package_share_directory():</strong> A function from ament_index_python.packages that retrieves the path to a package’s share directory. This is crucial for referencing config files or other resources within your launch scripts.</li></ul><h4>.launch.py vs .launch (XML in ROS1)</h4><p>ROS1 frequently used XML-based launch files. In ROS2, the recommended standard is Python-based launch files (.launch.py) because Python scripts are more flexible, readable, and powerful. XML-based launch files can still work, but they’re not recommended for new ROS2 projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2V-bhqNBBgj2Nx6FxLoRpQ.png" /><figcaption>ROS2 Launch Files Ecosystem</figcaption></figure><p>This visualization shows how launch files serve as the “orchestrators” of ROS2 applications, providing a centralized way to manage complex robot systems with multiple nodes, configurations, and dependencies. The modular design allows for scalable and maintainable robot applications.</p><h3>Sample ROS2 Packages</h3><p>Below are two interconnected sample packages to demonstrate nodes and launch files in action. Here, we are using two packages only for the sake of demonstration. Depending on the complexity of the system, we may also organize the below listed different sub-components under one unified package as well:</p><ul><li>config : Directory for the Configuration YAML files.</li><li>include : Directory for the Declaring the CPP Classes.</li><li>robot_arms_control : Directory for the Python Nodes.</li><li>src : Directory for defining the CPP Classes and CPP Nodes.</li><li>launch : Directory containing the Launch Files.</li><li>CMakeLists.txt : Integrated CMakeLists.txt from the below two packages.</li><li>setup.py : Setup Script for the Python Nodes.</li><li>package.xml : Integrated package.xml from the below two packages.</li></ul><h4>Sample Package 1: robot_arms_control</h4><p>This package contains the fundamental nodes (in both C++ and Python) to control different parts of a robotic arm: the hand, elbow, and shoulder. Each node is responsible for controlling a specific part of the robot arm.</p><p><strong>Creating Package</strong></p><pre>ros2 pkg create --build-type ament_cmake robot_arms_control</pre><p><strong>Package Structure</strong></p><pre>robot_arms_control<br>├── package.xml<br>├── CMakeLists.txt<br>├── setup.py<br>├── robot_arms_control<br>│   ├── elbow_node.py       # Main function for elbow node<br>│   ├── elbow.py            # Elbow controller logic<br>│   ├── __init__.py         # Python __init__ to treat folder as a module<br>│   ├── shoulder_node.py    # Main function for shoulder node<br>│   └── shoulder.py         # Shoulder controller logic<br>├── include<br>│   └── hand<br>│       └── hand.hpp        # Class declaration<br>└── src<br>    ├── hand.cpp            # Hand controller logic<br>    └── hand_node.cpp       # Main function for hand node</pre><h4>Source Files</h4><p><strong>1. Hand Controller (</strong><strong>hand.hpp and </strong><strong>hand.cpp)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c32d16924337727a1c778164354ccd7/href">https://medium.com/media/5c32d16924337727a1c778164354ccd7/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52d49695221ebdca2c4e126d1ee5b0bd/href">https://medium.com/media/52d49695221ebdca2c4e126d1ee5b0bd/href</a></iframe><p>The hand.cpp file implements the logic declared in hand.hpp for controlling the robot’s hand. It defines the constructor for the Hand class, which initializes parameters, sets up callbacks for dynamic parameter updates, and logs the initial state of the hand (such as finger lengths and namespace). Key functions include declare_parameters() for setting default values and retrieving them, and parameters_callback() for updating the finger lengths when parameters change at runtime.</p><p><strong>2. Hand Node (</strong><strong>hand_node.cpp)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5dfb5e1115157d3f46de92e411a6b5a0/href">https://medium.com/media/5dfb5e1115157d3f46de92e411a6b5a0/href</a></iframe><p>The hand_node.cpp file serves as the entry point for the hand node. It initializes the ROS2 system with rclcpp::init, creates an instance of the Hand node from the robot_arms_control package, starts spinning to process callbacks, and finally shuts down ROS2 gracefully with rclcpp::shutdown. This file ties together the hand controller logic with the ROS2 execution framework.</p><p><strong>3. Shoulder Controller (</strong><strong>shoulder.py</strong> <strong>)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a0f90f08172a360b171449794e086bf/href">https://medium.com/media/7a0f90f08172a360b171449794e086bf/href</a></iframe><p>The shoulder.py file contains the logic for the shoulder controller. It defines a Shoulder class that inherits from rclpy.node.Node. Inside its constructor, it declares parameters for the shoulder’s x, y, and z coordinates, retrieves these parameters, and logs the shoulder&#39;s initial position along with its namespace. This file focuses on initializing and configuring the shoulder node’s operational parameters.</p><p><strong>4. Shoulder Node (</strong><strong>shoulder_node.py)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60802b3f6b1296e6789cc0ed5782ef4b/href">https://medium.com/media/60802b3f6b1296e6789cc0ed5782ef4b/href</a></iframe><p>The shoulder_node.py file acts as the launch point for the shoulder controller. It imports the Shoulder class from shoulder.py, initializes the ROS2 Python client library with rclpy.init(), creates a Shoulder node instance, and spins it to keep it running. This script ensures the shoulder node is active until it receives a shutdown signal, handling keyboard interrupts appropriately.</p><p><strong>5. Elbow Controller (</strong><strong>elbow.py )</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d858d7886c5528c88c1dd0381a71a56/href">https://medium.com/media/1d858d7886c5528c88c1dd0381a71a56/href</a></iframe><p>The elbow.py file provides the implementation of the elbow controller logic. Similar to the shoulder, it defines an Elbow class that inherits from rclpy.node.Node. The class declares parameters for the elbow’s x, y, and z coordinates, retrieves these values upon initialization, and logs the elbow’s position and namespace. This setup prepares the elbow node to process elbow-specific tasks using the provided parameters.</p><p><strong>6. Elbow Node (</strong><strong>elbow_node.py)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14e51c788049ab69caf777c6887c28b2/href">https://medium.com/media/14e51c788049ab69caf777c6887c28b2/href</a></iframe><p>The elbow_node.py file serves as the entry script for the elbow controller. It imports the Elbow class, initializes the ROS2 system, creates an instance of the Elbow node, and spins it to handle callbacks. This file ensures the elbow node remains active, processing incoming parameter updates and other ROS2 events until interrupted.</p><h4>Setup Files</h4><p><strong>1. </strong><strong>setup.py</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bee695e1f04a9baba65a868fa4493982/href">https://medium.com/media/bee695e1f04a9baba65a868fa4493982/href</a></iframe><p>The setup.py file for robot_arms_control configures the package for Python installation. It specifies the package name, version, dependencies, and entry points for console scripts. It defines entry points for launching the shoulder and elbow nodes, ensuring that they can be invoked directly via ros2 run. The script also includes metadata like maintainer information, license, and description, and integrates the package with ROS2’s ament build system.</p><p><strong>2. </strong><strong>CMakeLists.txt</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ce55d6e33fb6a467fa3770c62d6c4cb/href">https://medium.com/media/7ce55d6e33fb6a467fa3770c62d6c4cb/href</a></iframe><p>The CMakeLists.txt file sets up the build configuration for the robot_arms_control package. It specifies the required C++ standard, sets compiler options, and finds necessary dependencies such as rclcpp and rclpy. The file declares the C++ executable hand_node, links it with ROS2 libraries, and installs it along with the necessary include directories. It also handles Python module installation and script deployment, ensuring that both C++ and Python nodes are built and installed correctly.</p><p><strong>3. </strong><strong>package.xml</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3ab35f6c82a3d8c541e3eb2ee0e5df4/href">https://medium.com/media/a3ab35f6c82a3d8c541e3eb2ee0e5df4/href</a></iframe><p>The package.xml file defines metadata for the robot_arms_control package, including its name, version, description, maintainer, and license. It lists build and run dependencies (ament_cmake, ament_cmake_python, rclcpp, and rclpy) required by the package. This file informs ROS2’s build system of the package’s dependencies and configuration, ensuring correct compilation and integration within a ROS2 workspace.</p><h3>Sample Package 2: robot_arms_bringup</h3><p>This package is responsible for orchestrating the various arm nodes defined in robot_arms_control. It uses launch files to start nodes for the left arm and right arm, each with their own namespaces, parameters, and arguments.</p><p><strong>Creating Package</strong></p><pre>ros2 pkg create --build-type ament_cmake robot_arms_bringup</pre><p><strong>Package Structure</strong></p><pre>robot_arms_bringup/<br>├── config/<br>│   ├── left_hand.yaml       # YAML config for Left Hand finger lengths<br>│   ├── right_hand.yaml      # YAML config for Right Hand finger lengths<br>│   └── bringup.yaml         # Contains positions (XYZ) for left &amp; right arm<br>├── launch/<br>│   ├── robot_bringup.launch.py<br>│   ├── left_arm.launch.py<br>│   └── right_arm.launch.py<br>├── CMakeLists.txt<br>└── package.xml</pre><h4>Config Files</h4><p><strong>1. Left Hand Configuration (</strong><strong>config/left_hand.yaml)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bf08a97c614f4cdb6af5357ab05de65/href">https://medium.com/media/0bf08a97c614f4cdb6af5357ab05de65/href</a></iframe><p>The left_hand.yaml configuration file sets parameters specifically for the left hand node. Under the namespace /left_arm, it defines the finger_lengths parameter as a list of values. These parameters are loaded at runtime to configure the behavior of the hand node on the left arm, such as setting the lengths of each finger.</p><p><strong>2. Right Hand Configuration (</strong><strong>config/right_hand.yaml)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cecec2f44425abdf7468fb3861e1a9b5/href">https://medium.com/media/cecec2f44425abdf7468fb3861e1a9b5/href</a></iframe><p>The right_hand.yaml file configures parameters for the right hand node. It specifies the finger_lengths parameter under the /right_arm namespace, using values that may differ or be mirrored compared to the left hand. This file allows separate configuration for the right hand, facilitating distinct control for each arm.</p><p><strong>3. Bringup Configuration (</strong><strong>config/bringup.yaml)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a77e4d14563982cb37b606b909a692a/href">https://medium.com/media/4a77e4d14563982cb37b606b909a692a/href</a></iframe><p>The bringup.yaml file provides comprehensive configuration for both left and right arms, including hand, shoulder, and elbow nodes. The use of the /**/ wildcard before node-specific paths (e.g., /**/left_arm/hand_node) applies these parameters to all nodes matching the pattern, regardless of deeper nested namespaces. This allows broad configuration without needing to list every possible path explicitly. For example, using /**/robot_arms_control/hand_node could apply settings to any hand_node in the system. The file sets parameters such as finger lengths and joint positions for both arms.</p><h4>Launch Files</h4><p><strong>1. Left Arm Launch (</strong><strong>left_arm.launch.py)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6109407188c9a35a8274765f001f045/href">https://medium.com/media/f6109407188c9a35a8274765f001f045/href</a></iframe><p>The left_arm.launch.py file creates a launch description for the left arm. It declares a namespace argument, retrieves the package share directory to locate configuration files, and defines nodes (hand, elbow, shoulder) with their respective namespaces under /left_arm. It loads parameters from the specified YAML configuration and outputs logs to the screen. This launch file simplifies starting all left-arm-related nodes with consistent parameters and namespace settings.</p><p><strong>2. Right Arm Launch (</strong><strong>right_arm.launch.py)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0159a0b54d2e6ac2ce08ed23abc4d7c5/href">https://medium.com/media/0159a0b54d2e6ac2ce08ed23abc4d7c5/href</a></iframe><p>Similarly, the right_arm.launch.py file sets up the launch configuration for the right arm. It declares a namespace argument, locates necessary config files, and creates nodes for the hand, elbow, and shoulder under /right_arm. It uses the same YAML configuration file and logging practices as the left arm launch file, tailored for right arm namespaces and settings.</p><p><strong>3. Robot Bringup Launch (</strong><strong>robot_bringup.launch.py)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c8486f78bfc686ebc0031834fd826c7/href">https://medium.com/media/3c8486f78bfc686ebc0031834fd826c7/href</a></iframe><p>The robot_bringup.launch.py file serves as the top-level launch file that orchestrates both left and right arm launch processes. It declares a top-level namespace argument, includes the left and right arm launch files using IncludeLaunchDescription, and groups them with GroupAction. This design allows simultaneous launch of all necessary nodes for both arms under a unified namespace if desired. The improved note explains that this approach modularizes launch processes and simplifies scaling, even though the execution might display duplicated logging during the evaluation phase, which is normal and does not impact node functionality.</p><p><strong>Note: </strong>The functionality of left_arm.launch.py and right_arm.launch.py is identical, except for the namespace and configuration files used. Thus, in an ideal scenario, you&#39;d have a single launch file that accepts arguments for namespace and configuration file paths, which you may launch twice with different arguments or have one arm launch file that launches all the 6 nodes (3 for each arm) in one go. Note that, in a single launch file itself, we can launch the same executable multiple times with different arguments. Here, we&#39;ve kept them separate for the sake of demonstrating the concept of launching other launch files.</p><h4>Setup Files</h4><p><strong>1. </strong><strong>CMakeLists.txt</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/877ae7252229b0d1c2c21448e1725446/href">https://medium.com/media/877ae7252229b0d1c2c21448e1725446/href</a></iframe><p>The CMakeLists.txt for the robot_arms_bringup package defines build configurations specific to launching and configuration resources. It finds required dependencies like ament_cmake and robot_arms_control, and sets compiler flags. This file installs the launch and config directories to the share directory of the package, making them accessible at runtime. It also includes testing configurations if enabled, though primary focus is on deploying launch-related resources.</p><p><strong>2. </strong><strong>package.xml</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/074b47dadd4b29ca4207f1db6e59955c/href">https://medium.com/media/074b47dadd4b29ca4207f1db6e59955c/href</a></iframe><p>The package.xml for robot_arms_bringup outlines package metadata, declares build and runtime dependencies (including dependencies on robot_arms_control, launch, launch_ros, and ament_index_python), and specifies the build type. This file ensures that the bringup package correctly integrates with the ROS2 ecosystem, bringing in all necessary dependencies for launching and configuration management.</p><h4>Building the Packages</h4><pre>cd ~/ros2_ws<br>colcon build --packages-select robot_arms_control robot_arms_bringup<br>source install/setup.bash</pre><h3>Running the Packages</h3><h4>Part 1: Running the robot_arms_control Package</h4><p>You can run each node manually, passing in arguments and parameters from the command line. For example:</p><pre># Terminal 1<br>ros2 run robot_arms_control hand_node --ros-args -p &quot;finger_lengths:=[5.0, 7.5, 7.85, 7.5, 6.5]&quot; -r __ns:=/left_arm<br># Or Terminal 1<br>ros2 run robot_arms_control hand_node --ros-args --params-file /path/to/config/left_hand.yaml -r __ns:=/left_arm<br><br># Terminal 2<br>ros2 run robot_arms_control shoulder_node.py --ros-args -p &quot;shoulder.x:=0.5&quot; -p &quot;shoulder.y:=0.3&quot; -p &quot;shoulder.z:=0.7&quot; -r __ns:=/left_arm<br># Or Terminal 2<br>ros2 run robot_arms_control shoulder_node.py --ros-args --params-file /path/to/config/bringup.yaml -r __ns:=/left_arm</pre><h4>Expected Output:</h4><pre># Terminal 1<br>[INFO] [/left_arm/hand_node]: Finger lengths: [5.0, 7.5, 7.85, 7.5, 6.5]<br>[INFO] [/left_arm/hand_node]: Namespaced under /left_arm<br>[INFO] [/left_arm/hand_node]: Hand Node Initialized<br><br># Terminal 2<br>[INFO] [/left_arm/shoulder_node]: Shoulder position: (0.5, 0.3, 0.7)<br>[INFO] [/left_arm/shoulder_node]: Namespaced under /left_arm<br>[INFO] [/left_arm/shoulder_node]: Shoulder Node Initialized</pre><ul><li>The hand node logs messages about finger length and position.</li><li>The shoulder node logs updates about the shoulder position.</li><li>If arguments are passed (like --ros-args -p shoulder_x:=1.0), you’ll see them reflected in the node’s behavior.</li></ul><h4>Part 2: Running the robot_arms_bringup Package</h4><p>Use the launch files to start multiple nodes at once. You can run individual launch files or a top-level launch file.</p><pre># Launch the left arm nodes:<br>ros2 launch robot_arms_bringup left_arm.launch.py namespace:=/robot_1<br><br># Launch the right arm nodes:<br>ros2 launch robot_arms_bringup right_arm.launch.py namespace:=/robot_1<br><br># Launch the entire robot arms bringup:<br>ros2 launch robot_arms_bringup robot_bringup.launch.py</pre><p>Expected Output:</p><pre># Left Hand Launch<br>[INFO] [launch]: All log files can be found below /home/shashank/.ros/log/2025-01-12-06-42-13-167622-shashank-Legion-Pro-7-16IRX8H-3656<br>[INFO] [launch]: Default logging verbosity is set to INFO<br>[INFO] [left_arm.launch]: Launching left hand node<br>[INFO] [left_arm.launch]: Launching left elbow node<br>[INFO] [left_arm.launch]: Launching left shoulder node<br>[INFO] [hand_node-1]: process started with pid [3657]<br>[INFO] [elbow_node.py-2]: process started with pid [3659]<br>[INFO] [shoulder_node.py-3]: process started with pid [3661]<br>[INFO] [hand_node-1] [robot_1.left_arm.hand_node]: Finger lengths: [4.000000, 6.500000, 6.850000, 6.500000, 5.500000]<br>[INFO] [hand_node-1] [robot_1.left_arm.hand_node]: Namespaced under /robot_1/left_arm<br>[INFO] [hand_node-1] [robot_1.left_arm.hand_node]: Hand Node Initialized<br>[INFO] [elbow_node.py-2] [robot_1.left_arm.elbow_node]: Elbow position: (1.5, 1.5, 1.4)<br>[INFO] [elbow_node.py-2] [robot_1.left_arm.elbow_node]: Namespaced under /robot_1/left_arm<br>[INFO] [elbow_node.py-2] [robot_1.left_arm.elbow_node]: Elbow Node Initialized<br>[INFO] [shoulder_node.py-3] [robot_1.left_arm.shoulder_node]: Shoulder position: (1.5, 1.3, 1.7)<br>[INFO] [shoulder_node.py-3] [robot_1.left_arm.shoulder_node]: Namespaced under /robot_1/left_arm<br>[INFO] [shoulder_node.py-3] [robot_1.left_arm.shoulder_node]: Shoulder Node Initialized<br><br># Right Hand Launch<br>[INFO] [launch]: All log files can be found below /home/shashank/.ros/log/2025-01-12-06-43-27-623142-shashank-Legion-Pro-7-16IRX8H-3690<br>[INFO] [launch]: Default logging verbosity is set to INFO<br>[INFO] [right_arm.launch]: Launching right hand node<br>[INFO] [right_arm.launch]: Launching right elbow node<br>[INFO] [right_arm.launch]: Launching right shoulder node<br>[INFO] [hand_node-1]: process started with pid [3691]<br>[INFO] [elbow_node.py-2]: process started with pid [3693]<br>[INFO] [shoulder_node.py-3]: process started with pid [3695]<br>[INFO] [hand_node-1] [robot_1.right_arm.hand_node]: Finger lengths: [4.000000, 6.500000, 6.850000, 6.500000, 5.500000]<br>[INFO] [hand_node-1] [robot_1.right_arm.hand_node]: Namespaced under /robot_1/right_arm<br>[INFO] [hand_node-1] [robot_1.right_arm.hand_node]: Hand Node Initialized<br>[INFO] [elbow_node.py-2] [robot_1.right_arm.elbow_node]: Elbow position: (1.5, -1.5, 1.4)<br>[INFO] [elbow_node.py-2] [robot_1.right_arm.elbow_node]: Namespaced under /robot_1/right_arm<br>[INFO] [elbow_node.py-2] [robot_1.right_arm.elbow_node]: Elbow Node Initialized<br>[INFO] [shoulder_node.py-3] [robot_1.right_arm.shoulder_node]: Shoulder position: (1.5, -1.3, 1.7)<br>[INFO] [shoulder_node.py-3] [robot_1.right_arm.shoulder_node]: Namespaced under /robot_1/right_arm<br>[INFO] [shoulder_node.py-3] [robot_1.right_arm.shoulder_node]: Shoulder Node Initialized<br><br># Robot Bringup Launch<br>[INFO] [launch]: All log files can be found below /home/shashank/.ros/log/2025-01-12-06-44-30-844276-shashank-Legion-Pro-7-16IRX8H-3726<br>[INFO] [launch]: Default logging verbosity is set to INFO<br>[INFO] [left_arm.launch]: Launching left hand node<br>[INFO] [left_arm.launch]: Launching left elbow node<br>[INFO] [left_arm.launch]: Launching left shoulder node<br>[INFO] [right_arm.launch]: Launching right hand node<br>[INFO] [right_arm.launch]: Launching right elbow node<br>[INFO] [right_arm.launch]: Launching right shoulder node<br>[INFO] [left_arm.launch]: Launching left hand node<br>[INFO] [left_arm.launch]: Launching left elbow node<br>[INFO] [left_arm.launch]: Launching left shoulder node<br>[INFO] [right_arm.launch]: Launching right hand node<br>[INFO] [right_arm.launch]: Launching right elbow node<br>[INFO] [right_arm.launch]: Launching right shoulder node<br>[INFO] [hand_node-1]: process started with pid [3727]<br>[INFO] [elbow_node.py-2]: process started with pid [3729]<br>[INFO] [shoulder_node.py-3]: process started with pid [3731]<br>[INFO] [hand_node-4]: process started with pid [3733]<br>[INFO] [elbow_node.py-5]: process started with pid [3735]<br>[INFO] [shoulder_node.py-6]: process started with pid [3737]<br>[INFO] [hand_node-1] [left_arm.hand_node]: Finger lengths: [4.000000, 6.500000, 6.850000, 6.500000, 5.500000]<br>[INFO] [hand_node-1] [left_arm.hand_node]: Namespaced under /left_arm<br>[INFO] [hand_node-1] [left_arm.hand_node]: Hand Node Initialized<br>[INFO] [hand_node-4] [right_arm.hand_node]: Finger lengths: [4.000000, 6.500000, 6.850000, 6.500000, 5.500000]<br>[INFO] [hand_node-4] [right_arm.hand_node]: Namespaced under /right_arm<br>[INFO] [hand_node-4] [right_arm.hand_node]: Hand Node Initialized<br>[INFO] [shoulder_node.py-3] [left_arm.shoulder_node]: Shoulder position: (1.5, 1.3, 1.7)<br>[INFO] [shoulder_node.py-3] [left_arm.shoulder_node]: Namespaced under /left_arm<br>[INFO] [shoulder_node.py-3] [left_arm.shoulder_node]: Shoulder Node Initialized<br>[INFO] [elbow_node.py-2] [left_arm.elbow_node]: Elbow position: (1.5, 1.5, 1.4)<br>[INFO] [elbow_node.py-2] [left_arm.elbow_node]: Namespaced under /left_arm<br>[INFO] [elbow_node.py-2] [left_arm.elbow_node]: Elbow Node Initialized<br>[INFO] [shoulder_node.py-6] [right_arm.shoulder_node]: Shoulder position: (1.5, -1.3, 1.7)<br>[INFO] [elbow_node.py-5] [right_arm.elbow_node]: Elbow position: (1.5, -1.5, 1.4)<br>[INFO] [shoulder_node.py-6] [right_arm.shoulder_node]: Namespaced under /right_arm<br>[INFO] [elbow_node.py-5] [right_arm.elbow_node]: Namespaced under /right_arm<br>[INFO] [shoulder_node.py-6] [right_arm.shoulder_node]: Shoulder Node Initialized<br>[INFO] [elbow_node.py-5] [right_arm.elbow_node]: Elbow Node Initialized</pre><p><strong>Note:</strong> The double logging occurs because of how the launch system processes included launch files. When we run robot_bringup.launch.py, the following happens:</p><ol><li>The main launch file creates a GroupAction containing both left and right arm launches.</li><li>Each included launch file (left_arm.launch.py and right_arm.launch.py) goes through two phases:</li></ol><ul><li><em>First phase:</em> Launch system evaluates the launch file to build the launch description.</li><li><em>Second phase:</em> Launch system executes the actual node spawning.</li></ul><p>The double logging <strong>doesn’t affect the actual node execution</strong> — notice how each node still starts only once with a unique PID, as shown in the output.</p><h4>Passing Arguments and Parameters</h4><p>You can pass arguments to a launch file, which will then propagate them to the nodes:</p><pre>ros2 launch robot_arms_bringup robot_bringup_launch.py namespace:=/robot_ns</pre><p>Within the launch files, you might use get_package_share_directory() to locate your config/bringup.yaml or other YAMLs, ensuring that file references remain robust, even if your ROS2 workspace structure changes.</p><h4>What to Expect</h4><ul><li>Both left and right hand nodes spawn under the respective namespaces.</li><li>You’ll see debug statements in the console showing how parameters and arguments (e.g., finger lengths, elbow or shoulder positions) are applied.</li><li>If you’re remapping topics or using environment variables, you’ll see these changes in action.</li></ul><h3>Best Practices and Tips</h3><ol><li><strong>Modularize Your Nodes:</strong> Keep node responsibilities narrow. This allows for easier debugging and scaling.</li><li><strong>Use Namespaces Wisely:</strong> When dealing with multiple robot arms or similar hardware, namespaces help keep things organized and avoid topic/service name collisions.</li><li><strong>Parameter &amp; Argument Conventions:</strong> Make sure to use sensible defaults in your code. Provide YAML files for easy customization, especially for production or large-scale projects.</li><li><strong>Logging &amp; Debugging:</strong> Print or log key information to help with debugging. This is especially important when dealing with complex launch setups.</li><li><strong>Include Launch Files:</strong> Break down large launch files into smaller ones, then include them in a top-level launch. This helps in reusability and maintainability.</li><li><strong>get_package_share_directory():</strong> Use this function to reference config files or other resources. It keeps your file references valid regardless of where your package is located.</li></ol><h3>Conclusion</h3><p>Nodes and launch files are cornerstones of any robust ROS2 application. Nodes divide your software into manageable components, while launch files tie everything together, enabling consistent, repeatable, and scalable multi-node deployments. By leveraging arguments and parameters, you can dynamically configure both nodes and launch files for flexible, real-time adjustments.</p><p>If you found this article helpful, check out my previous posts on <a href="https://medium.com/@shashank-goyal-blogs/ros2-humble-gui-docker-container-a-step-by-step-guide-c541b73fe141"><strong>installing ROS2 with GUI support in Docker</strong></a>, <a href="https://shashank-goyal-blogs.medium.com/mastering-ros2-your-ultimate-beginners-guide-to-robotics-a72179db4c84"><strong>building communication</strong></a> with <a href="https://shashank-goyal-blogs.medium.com/mastering-ros2-building-robust-communication-with-custom-messages-services-and-actions-9a49b4cd8b16"><strong>custom interfaces</strong></a>, and <a href="https://shashank-goyal-blogs.medium.com/mastering-ros2-harnessing-the-power-of-ros2-parameters-for-real-time-configuration-afd4c3890fc9"><strong>harnessing the power of parameters</strong></a>. These foundations will help you assemble a polished, maintainable robotics software stack.</p><p>If you’d like to checkout the Code for the above, you can find it here on <a href="https://github.com/shashank3199/ROS-Tutorials-4"><strong>GitHub</strong></a>. Follow my <a href="https://shashank-goyal-blogs.medium.com/"><strong>Medium</strong></a> and <a href="https://github.com/shashank3199/"><strong>GitHub</strong></a> for more tutorials, and don’t forget to clap 👏 if this post helped you!</p><p>Happy coding, and may your nodes always spin without crashing!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*aUyN6YOrWzsxBQmw.png" /></figure><h4>👋 If you find this helpful, please click the clap 👏 button below a few times to show your support for the author 👇</h4><h4>🚀<a href="http://from.faun.to/r/8zxxd">Join FAUN Developer Community &amp; Get Similar Stories in your Inbox Each Week</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e8aae3fc917" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/mastering-ros2-orchestrating-your-robots-architecture-with-nodes-and-launch-files-2e8aae3fc917">Mastering ROS2: Orchestrating Your Robot’s Architecture with Nodes and Launch Files</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering ROS2: Harnessing the Power of ROS2 Parameters for Real-Time Configuration]]></title>
            <link>https://faun.pub/mastering-ros2-harnessing-the-power-of-ros2-parameters-for-real-time-configuration-afd4c3890fc9?source=rss-e85e3a6012ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/afd4c3890fc9</guid>
            <category><![CDATA[robot-operating-system]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[begginers-guide]]></category>
            <category><![CDATA[ros2]]></category>
            <category><![CDATA[robotics-development]]></category>
            <dc:creator><![CDATA[Shashank Goyal]]></dc:creator>
            <pubDate>Sat, 11 Jan 2025 04:59:08 GMT</pubDate>
            <atom:updated>2025-01-31T12:43:31.915Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZccQ71MxxSb0KL9t" /></figure><h3>Introduction</h3><p>Have you ever wondered how to manage configuration variables that need to be shared across multiple nodes in your ROS2-based robotic application? Enter ROS2 Parameters, a powerful mechanism that lets you centralize your robot’s configuration. From tuning PID controllers to specifying robot names, ROS2 Parameters offer a straightforward way to read, write, and dynamically adjust key variables at runtime.</p><p>If you’re new to ROS2 and want a reliable way to set up a development environment, check out my <a href="https://medium.com/@shashank-goyal-blogs/ros2-humble-gui-docker-container-a-step-by-step-guide-c541b73fe141"><strong>comprehensive guide on installing and configuring ROS2 with GUI support in a Docker container</strong></a>. To master the basics of ROS2 nodes, topics, services, and actions, you can refer to my other blogs: <a href="https://shashank-goyal-blogs.medium.com/mastering-ros2-your-ultimate-beginners-guide-to-robotics-a72179db4c84"><strong>Beginner’s Guide to ROS2</strong></a><strong> </strong>and<strong> </strong><a href="https://shashank-goyal-blogs.medium.com/mastering-ros2-building-robust-communication-with-custom-messages-services-and-actions-9a49b4cd8b16"><strong>Building Robust Communication with Custom Messages, Services, and Actions</strong></a><strong>.</strong></p><p>In this blog post, we’ll dive deep into ROS2 Parameters, exploring how they work, how to manipulate them via command-line tools, and how to build a mixed C++-Python ROS2 package that demonstrates their flexibility in real-world scenarios. Let’s get started!</p><h3>What Are ROS2 Parameters?</h3><p>ROS2 Parameters are global or node-specific variables that can be declared, read, and updated at runtime. Think of them as the shared configuration data that your robot needs to perform its tasks correctly. These parameters can include everything from sensor update rates and thresholds to model names and debugging flags.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2D5CS8-ugjCHhqgkVoie6Q.png" /><figcaption><em>This diagram illustrates how parameters can be defined in individual nodes, retrieved globally, and dynamically updated.</em></figcaption></figure><h3>Defining the Types of ROS2 Parameters</h3><p>In ROS2, parameters can store various data types such as integers, floats, booleans, strings, and more. You can also have arrays of these basic types. Furthermore, each parameter is accompanied by metadata (such as a descriptor) that can specify validation constraints and read/write access levels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ggzDSlwukIcsT_F5qTJPIw.png" /><figcaption><strong>Flow of different types of parameters through a ROS2 system</strong></figcaption></figure><h3>Types of ROS2 Parameters</h3><h4>1. Basic Types</h4><ul><li><strong>Integer</strong>: For integer values (e.g., int32, int64)</li><li><strong>Floating-point</strong>: For decimal values (e.g., float64)</li><li><strong>Boolean</strong>: For true/false states</li><li><strong>String</strong>: For textual data</li><li><strong>Byte/Array</strong>: For raw data or fixed-size arrays</li></ul><h4>2. Arrays</h4><ul><li><strong>Integer Array</strong>: [1, 2, 3]</li><li><strong>Float Array</strong>: [0.1, 0.2, 0.3]</li><li><strong>String Array</strong>: [&#39;front_sensor&#39;, &#39;rear_sensor&#39;]</li></ul><h4>3. Complex/Composite Types (if needed)</h4><p>Custom data structures stored in YAML (though typically, that data eventually gets mapped to standard parameter types)</p><pre>my_robot:<br>  sensors:<br>    - &#39;lidar&#39;<br>    - &#39;camera&#39;<br>  max_speed: 2.5<br>  debug_mode: true</pre><h4>Defining and Creating Custom ROS2 Parameters</h4><p>You can declare parameters in your code, or you can load them from a YAML file. For instance, you might have a custom parameter namespace such as robot_description that contains multiple nested parameters.</p><pre>robot_description:<br>  length: 1.2<br>  width: 0.8<br>  weight: 12.4</pre><h3>Command Line Interface (CLI) Tools for ROS2 Parameters</h3><p>ROS2 provides a convenient set of CLI tools to interact with parameters at runtime. Here are the most common:</p><pre># Lists all parameters for running nodes.<br>ros2 param list<br><br># Retrieves the value of a specific parameter from a node.<br>ros2 param get /node_name param_name<br><br># Sets a parameter for a node at runtime.<br>ros2 param set /node_name param_name value<br><br># Saves the node’s parameters to a YAML file.<br>ros2 param dump /node_name --file path/to/file.yaml<br><br># Loads parameters from a YAML file into a node.<br>ros2 param load /node_name path/to/file.yaml</pre><p>These commands let you inspect and modify parameters without changing your source code or restarting your nodes.</p><h3>Sample ROS2 Package: Mixed C++ &amp; Python Parameter Demonstration</h3><p>In this example, we’ll create a package that showcases multiple nodes:</p><ol><li><strong>C++ Read Node</strong>: Reads specified ROS2 parameters.</li><li><strong>Python Read Node</strong>: Reads the same ROS2 parameters.</li><li><strong>C++ Write Node</strong>: Writes new values to the parameters.</li><li><strong>Python Write Node</strong>: Writes or updates parameter values.</li><li><strong>C++ Modifier Node</strong>: Alters another node’s parameters based on some logic.</li><li><strong>Python Modifier Node</strong>: Alters another node’s parameters based on some logic in Python.</li></ol><p>Each node is independent and can be run in any combination, demonstrating how parameters remain consistent across multiple nodes and languages.</p><p>This package, named param_demo, will contain a config directory with a YAML file specifying initial parameter values. Our nodes will load these parameters either through direct code-based parameter declaration or via the command line.</p><h3>Creating the Package</h3><pre>ros2 pkg create --build-type ament_cmake param_demo</pre><h3>Package Structure</h3><pre>param_demo/<br>├── config/<br>│   └── default_params.yaml<br>├── src/<br>│   ├── cpp_read_node.cpp<br>│   ├── cpp_write_node.cpp<br>│   └── cpp_dynamic_node.cpp<br>├── param_demo/<br>│   ├── __init__.py<br>│   ├── py_read_node.py<br>│   ├── py_write_node.py<br>│   └── py_dynamic_node.py<br>├── CMakeLists.txt<br>├── package.xml<br>└── setup.py</pre><h3>Custom Configuration Files</h3><h4>config/default_params.yaml</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d09b2f33fe68b3f49917ee6bb3177b78/href">https://medium.com/media/d09b2f33fe68b3f49917ee6bb3177b78/href</a></iframe><p>/**:</p><ul><li><strong>Explanation</strong>: The top-level key /** acts as a wildcard, applying the configuration globally to all nodes in the ROS2 application. Any node running in the system can access these parameters unless overridden by node-specific configurations.</li><li><strong>Key Insight</strong>: This makes parameters accessible universally, simplifying configurations for nodes that share common settings.</li></ul><p>ros__parameters:</p><ul><li><strong>Explanation</strong>: The ros__parameters key is mandatory and indicates that all nested keys below it are ROS2 parameters. ROS2 will read and interpret only the entries under this key.</li><li><strong>Key Insight</strong>: Anything outside ros__parameters will be ignored by ROS2 (useful for including metadata or comments for human readers or non-ROS tools).</li></ul><p>my_robot:</p><ul><li><strong>Explanation</strong>: Defines a parameter namespace specific to the “my_robot” context. This namespace groups related parameters under a logical name.</li><li><strong>Key Insight</strong>: You can retrieve parameters within this namespace in your node by referencing /my_robot/&lt;parameter_name&gt; in CLI.</li></ul><p>name: &#39;RoboX_loaded&#39;</p><ul><li><strong>Explanation</strong>: Assigns the robot a name “RoboX_loaded”. This is a string parameter and can be used in nodes for identification purposes.</li><li><strong>Key Insight</strong>: Nodes can access this parameter by calling /my_robot/name in CLI.</li></ul><p>debug_mode: true</p><ul><li><strong>Explanation</strong>: Enables debug mode for the robot. This is a boolean parameter and can be used to control behaviors like logging verbosity or test mode activations.</li><li><strong>Key Insight</strong>: Use this parameter in conditional logic to toggle between normal and debug behaviors.</li></ul><p>max_speed: 1.5</p><ul><li><strong>Explanation</strong>: Specifies the maximum speed of the robot in some units (likely meters per second). This is a float parameter that can be used to limit the robot’s velocity.</li><li><strong>Key Insight</strong>: Nodes can dynamically update this parameter to modify the robot’s performance.</li></ul><p>sensor_list:</p><ul><li><strong>Explanation</strong>: Lists the sensors available on the robot. This is an array parameter, storing multiple string values.</li><li><strong>Key Insight</strong>: You can use this to dynamically load drivers or configurations for each sensor.</li></ul><p>param_sample_robot:</p><ul><li><strong>Explanation</strong>: Creates another namespace, param_sample_robot, similar to my_robot. This can be used to configure a different robot or a secondary mode of operation.</li><li><strong>Key Insight</strong>: Each namespace can have its own independent set of parameters, allowing you to manage multiple robots or modes efficiently.</li></ul><p>You can load such parameters into a node by running:</p><pre>ros2 param load /node_name config/default_params.yaml</pre><p>or by adding thenm during runtime:</p><pre>ros2 run package_name node_name --ros-args --params-file /path/to/param_file/params_file.yaml</pre><p><strong>C++ Read Node (</strong><strong>cpp_read_node.cpp)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e673a21781339a193dfe05bee2ea9e53/href">https://medium.com/media/e673a21781339a193dfe05bee2ea9e53/href</a></iframe><p><strong>Python Read Node (</strong><strong>py_read_node.py)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/269f1b90ca9b64e13148639ffb7e5727/href">https://medium.com/media/269f1b90ca9b64e13148639ffb7e5727/href</a></iframe><p><strong>Important Note:</strong> The Python implementation of py_read_node.py and py_modify_node.py is supported only in <strong>ROS2 Jazzy</strong> and later versions. The functionality for reading and modifying parameters using Python is not available in ROS2 versions prior to Jazzy.</p><p><strong>C++ Write Node (</strong><strong>cpp_write_node.cpp)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5012f2c8741debc28b23c48072d0cff8/href">https://medium.com/media/5012f2c8741debc28b23c48072d0cff8/href</a></iframe><p><strong>Python Write Node (</strong><strong>py_write_node.py)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5dc810fb35646bb99f27c32c6a650d0c/href">https://medium.com/media/5dc810fb35646bb99f27c32c6a650d0c/href</a></iframe><p><strong>C++ Modifier Node (</strong><strong>cpp_modify_node.cpp )</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f6cfbe12b171f0cabd3e74d538edef8/href">https://medium.com/media/2f6cfbe12b171f0cabd3e74d538edef8/href</a></iframe><p><strong>Python Modifier Node (</strong><strong>py_modify_node.py )</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d313dd07d3ed4a1b6831022ec09061e8/href">https://medium.com/media/d313dd07d3ed4a1b6831022ec09061e8/href</a></iframe><p><strong>Important Note:</strong> The Python implementation of py_read_node.py and py_modify_node.py is supported only in <strong>ROS2 Jazzy</strong> and later versions. The functionality for reading and modifying parameters using Python is not available in ROS2 versions prior to Jazzy.</p><h3>Setup Files</h3><h4>CMakeLists.txt</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/823b80fdff9128b0d2978abec4ba1462/href">https://medium.com/media/823b80fdff9128b0d2978abec4ba1462/href</a></iframe><h4>package.xml</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5eb2dce3ecf4373498d838e87f81cc16/href">https://medium.com/media/5eb2dce3ecf4373498d838e87f81cc16/href</a></iframe><h4>setup.py</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1e6b1246283c20b12c158cee0504730/href">https://medium.com/media/c1e6b1246283c20b12c158cee0504730/href</a></iframe><h4>Building the Package</h4><pre>cd ~/ros2_ws<br>colcon build --packages-select param_demo<br>source install/setup.bash</pre><h3>Running the Package</h3><p>Let’s explore different ways to run and interact with the parameter demo package. We’ll see how parameters flow between nodes and how to configure them using various methods.</p><h3>Case 1: Basic Node Operation</h3><p>First, let’s run our three main nodes in separate terminals to observe their interaction:</p><pre># Terminal 1: Run the writer node (CPP)<br>ros2 run param_demo cpp_write_node<br># Or<br># Terminal 1: Run the writer node (Python)<br>ros2 run param_demo py_write_node.py<br><br># Terminal 2: Run the reader node (C++)<br>ros2 run param_demo cpp_read_node<br># Or<br># Terminal 2: Run the reader node (Python)<br>ros2 run param_demo py_read_node.py<br><br># Terminal 3: Run the modifier node (CPP)<br>ros2 run param_demo cpp_modify_node<br># Or<br># Terminal 3: Run the modifier node (Python)<br>ros2 run param_demo py_modify_node</pre><p><strong>Expected Output:</strong></p><p>In the writer node terminal:</p><pre>[INFO] [parameter_writer]: Parameter Writer Node initialized<br>[INFO] [parameter_writer]: Sampled parameters:<br>[INFO] [parameter_writer]: Name: <br>[INFO] [parameter_writer]: Debug mode: false<br>[INFO] [parameter_writer]: Max speed: 0.00<br>[INFO] [parameter_writer]: Sensor list: Sensor list<br>[INFO] [parameter_writer]: ----------------------------------------<br>[INFO] [parameter_writer]: Debug mode toggled to: false<br>[INFO] [parameter_writer]: Max speed updated to: 1.00<br>[INFO] [parameter_writer]: Robot name updated to: RoboX_1<br>[INFO] [parameter_writer]: Updated sensor list: lidar<br>[INFO] [parameter_writer]: ----------------------------------------<br>[INFO] [parameter_writer]: Debug mode toggled to: true<br>[INFO] [parameter_writer]: Max speed updated to: 1.50<br>[INFO] [parameter_writer]: Robot name updated to: RoboX_2<br>[INFO] [parameter_writer]: Updated sensor list: lidar, camera<br>[INFO] [parameter_writer]: ----------------------------------------<br>[INFO] [parameter_writer]: Debug mode toggled to: false<br>[INFO] [parameter_writer]: Max speed updated to: 2.00<br>[INFO] [parameter_writer]: Robot name updated to: RoboX_3<br>[INFO] [parameter_writer]: Updated sensor list: lidar, ultrasonic<br>[INFO] [parameter_writer]: ----------------------------------------</pre><p>In the reader node terminal:</p><pre>[WARN] [parameter_reader]: Reader is inactive. Cannot update parameters.<br>[WARN] [parameter_reader]: Reader is inactive. Cannot update parameters.<br>[WARN] [parameter_reader]: Reader is inactive. Cannot update parameters.<br>[WARN] [parameter_reader]: Reader is inactive. Cannot update parameters.<br>[INFO] [parameter_reader]: Parameter &#39;my_robot.debug_mode&#39; changed to: false<br>[INFO] [parameter_reader]: Parameter &#39;my_robot.max_speed&#39; changed to: 4.000000<br>[INFO] [parameter_reader]: Parameter &#39;my_robot.name&#39; changed to: RoboX_7<br>[INFO] [parameter_reader]: Parameter &#39;my_robot.sensor_list&#39; changed to: [lidar]<br>[INFO] [parameter_reader]: Parameter &#39;my_robot.debug_mode&#39; changed to: true<br>[INFO] [parameter_reader]: Parameter &#39;my_robot.max_speed&#39; changed to: 4.500000<br>[INFO] [parameter_reader]: Parameter &#39;my_robot.name&#39; changed to: RoboX_8<br>[INFO] [parameter_reader]: Parameter &#39;my_robot.sensor_list&#39; changed to: [lidar, camera]<br>[WARN] [parameter_reader]: Reader is inactive. Cannot update parameters.<br>[WARN] [parameter_reader]: Reader is inactive. Cannot update parameters.<br>[WARN] [parameter_reader]: Reader is inactive. Cannot update parameters.<br>[WARN] [parameter_reader]: Reader is inactive. Cannot update parameters.</pre><p>In the modifier node terminal:</p><pre>[INFO] [parameter_modifier]: Parameter Modifier Node initialized<br>[INFO] [parameter_modifier]: Successfully toggled reader status to: inactive<br>[INFO] [parameter_modifier]: Successfully toggled reader status to: active<br>[INFO] [parameter_modifier]: Successfully toggled reader status to: inactive</pre><h3>Case 2: Loading Parameters from YAML</h3><p>Now, let’s start the writer node with pre-configured parameters from our YAML file:</p><pre># Terminal 1: Run writer node with YAML configuration (CPP)<br>ros2 run param_demo cpp_write_node --ros-args --params-file path_to_config/default_params.yaml<br><br># Or<br><br># Terminal 1: Run writer node with YAML configuration (Python)<br>ros2 run param_demo py_write_node --ros-args --params-file path_to_config/default_params.yaml</pre><p><strong>Expected Output:</strong></p><pre>[INFO] [parameter_writer]: Sampled parameters:<br>[INFO] [parameter_writer]: Name: RoboX_loaded_sample<br>[INFO] [parameter_writer]: Debug mode: False<br>[INFO] [parameter_writer]: Max speed: 2.5<br>[INFO] [parameter_writer]: Sensor list: lidar_loaded_sample, camera_loaded_sample, ultrasonic_loaded_sample<br>[INFO] [parameter_writer]: ----------------------------------------<br>[INFO] [parameter_writer]: Parameter Writer Node initialized<br>[INFO] [parameter_writer]: Successfully updated parameter &#39;my_robot.debug_mode&#39; to: False<br>[INFO] [parameter_writer]: Successfully updated parameter &#39;my_robot.max_speed&#39; to: 1.0<br>[INFO] [parameter_writer]: Robot name updated to: RoboX_1<br>[INFO] [parameter_writer]: Sensor list updated to: lidar<br>[INFO] [parameter_writer]: ----------------------------------------</pre><h3>Case 3: Setting Initial Reader Status</h3><p>Let’s start the reader node with an active status from the beginning:</p><pre># Terminal 1: Run reader node with active status (CPP)<br>ros2 run param_demo cpp_read_node --ros-args -p &quot;/reader_status:=active&quot;<br><br># Or<br><br># Terminal 1: Run reader node with active status (Python)<br>ros2 run param_demo py_read_node --ros-args -p &quot;/reader_status:=active&quot;</pre><p><strong>Expected Output:</strong></p><pre>[INFO] [parameter_reader]: Parameter &#39;my_robot.debug_mode&#39; changed to: false<br>[INFO] [parameter_reader]: Parameter &#39;my_robot.max_speed&#39; changed to: 1.000000<br>[INFO] [parameter_reader]: Parameter &#39;my_robot.name&#39; changed to: RoboX_1<br>[INFO] [parameter_reader]: Parameter &#39;my_robot.sensor_list&#39; changed to: [lidar]</pre><h3>Understanding the Data Flow</h3><p>As shown in the diagram below, the parameter system operates with several key components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uoZNQM3VP2WXMMcjEXmu_Q.png" /></figure><p><strong>1. Writer Node</strong>: Periodically updates parameters:</p><ul><li>Robot name (with incrementing counter)</li><li>Debug mode (toggles between true/false)</li><li>Max speed (increments from 0.5 to 5.0)</li><li>Sensor list (varies based on counter)</li></ul><p><strong>2. Reader Node</strong>:</p><ul><li>Subscribes to parameter changes</li><li>Only processes updates when its status is “active”</li><li>Logs all parameter changes it receives</li></ul><p><strong>3. Modifier Node</strong>:</p><ul><li>Toggles the reader node’s status every 5 seconds</li><li>Demonstrates remote parameter modification</li></ul><p><strong>4. Parameter Server</strong>:</p><ul><li>Maintains the current state of all parameters</li><li>Handles parameter declarations and updates</li><li>Notifies subscribed nodes of changes</li></ul><p>The diagram illustrates how these components interact, showing the flow of parameter updates and notifications through the system. The color-coded sections highlight different phases of parameter handling:</p><ul><li>Blue: Initial setup phase</li><li>Green: Normal operation and parameter access</li><li>Red: CLI interaction and dynamic updates</li></ul><p>This architecture allows for flexible configuration and real-time parameter updates across your ROS2 system, making it ideal for robotics applications that need runtime adjustability.</p><p>While each node is running, you can also open another terminal and issue parameter updates:</p><pre>ros2 param set /cpp_read_node my_robot.max_speed 2.0<br>ros2 param get /cpp_read_node my_robot.max_speed<br><br>ros2 param set /py_read_node my_robot.max_speed 2.0<br>ros2 param get /py_read_node my_robot.max_speed</pre><h3>Expected Behavior of the Package</h3><ul><li><strong>Real-Time Updates</strong>: Writing a parameter from one node (or via the CLI) should trigger any parameter callbacks in the reading nodes.</li><li><strong>Dynamic Reconfiguration</strong>: The dynamic nodes show how parameters can change based on internal logic (e.g., if debug_mode is enabled, log extra data).</li></ul><h3>Variations and Advanced Usage</h3><ol><li><strong>Node-Specific Parameters</strong></li></ol><ul><li>Instead of /**, you can specify parameters for a particular node using its exact name.</li></ul><pre>/my_specific_node:<br>    ros__parameters:<br>        robot_name: &#39;SpecificBot&#39;<br>        enable_logging: true<br>        speed_limit: 2.0</pre><ul><li><strong>Key Insight</strong>: Only the node named /my_specific_node will have access to these parameters.</li></ul><p><strong>2. Regex for Node Matching</strong></p><ul><li>ROS2 supports regex-based matching for node names, allowing you to target groups of nodes with similar names.</li></ul><pre>/robot_*:<br>    ros__parameters:<br>        logging_level: &#39;DEBUG&#39;<br>        max_payload: 5.0</pre><ul><li><strong>Key Insight</strong>: Parameters will be applied to all nodes whose names start with robot_.</li></ul><p><strong>3. Adding Non-ROS Keys</strong></p><ul><li>You can include non-ROS keys at the same level as ros__parameters, which will not be read by ROS2.</li></ul><pre>/**:<br>    ros__parameters:<br>        my_robot:<br>            name: &#39;RoboX&#39;<br>            max_speed: 1.5<br>    metadata:<br>        description: &#39;Configuration file for RoboX&#39;<br>        created_by: &#39;Shashank&#39;<br>        version: &#39;1.0&#39;</pre><ul><li><strong>Key Insight</strong>: The metadata section is ignored by ROS2 but can serve as documentation or be used by external tools.</li></ul><p><strong>4. Nested Levels of Parameters</strong></p><ul><li>Parameters can be deeply nested to reflect complex configurations.</li></ul><pre>/**:<br>    ros__parameters:<br>        robot_description:<br>            dimensions:<br>                length: 1.2<br>                width: 0.8<br>                height: 0.5<br>            weight: 50.0<br>            sensors:<br>                - type: &#39;camera&#39;<br>                  resolution: &#39;1920x1080&#39;<br>                - type: &#39;lidar&#39;<br>                  range: 30.0</pre><ul><li><strong>Key Insight</strong>: Nested levels allow you to group related data logically. Access them in your nodes using the complete path (e.g., /robot_description/dimensions/length).</li></ul><p><strong>5. Per-Node and Global Parameters</strong></p><ul><li>Combine global and node-specific parameters in the same file.</li></ul><pre>/**:<br>    ros__parameters:<br>        global_debug: true<br>/specific_node:<br>    ros__parameters:<br>        debug_mode: false</pre><ul><li><strong>Key Insight</strong>: The global_debug parameter applies to all nodes, while debug_mode applies only to /specific_node.</li></ul><h3>Addressing Nested Parameters</h3><p>To access deeply nested parameters, you must use the full path in your code. For example:</p><pre>node-&gt;declare_parameter(&quot;robot_description.dimensions.length&quot;);<br>double length = node-&gt;get_parameter(&quot;robot_description.dimensions.length&quot;).as_double();</pre><p>For YAML arrays, access them as follows:</p><pre>std::vector&lt;std::string&gt; sensor_list = node-&gt;get_parameter(&quot;sensor_list&quot;).as_string_array();</pre><ul><li>Copy code</li><li><strong>Leverage Regex for Flexibility: </strong>Use regex matching to apply parameters to a family of nodes.</li><li><strong>Use Metadata for Documentation: </strong>Include non-ROS keys for human-readable documentation or version tracking.</li><li><strong>Keep Global and Local Parameters Separate: </strong>Reserve /** for truly global parameters, and use specific node names for localized configurations.</li><li><strong>Document Parameters</strong>: List all parameters and their types in your package’s README or in a dedicated file.</li></ul><h3>Common Issues and How to Resolve Them</h3><ol><li><strong>Node Fails to Declare Parameter: </strong>In ROS2, you need to declare parameters before using them. Check your node’s code to ensure parameters are declared properly.</li><li><strong>Parameter Not Found: </strong>Verify that the node is running and named correctly. Make sure you’re using the correct namespace and parameter paths (my_robot.param_name).</li><li><strong>Incompatible Data Types: </strong>If you set an integer to a parameter expecting a float, you may encounter errors. Use the correct data types.</li><li><strong>Permissions: </strong>Some nodes may restrict parameter changes at runtime. Check the parameter descriptor or node logic if you can’t set a parameter.</li><li><strong>YAML Formatting:</strong> Ensure that the default_params.yaml or other parameter files are properly formatted with respect to the indentation and space consistency.</li></ol><h3>Best Practices</h3><ul><li><strong>Use Namespaces</strong>: Group logically related parameters under a namespace (e.g., my_robot, param_sample_robot ).</li><li><strong>Document Parameters</strong>: List all parameters and their types in your package’s README or in a dedicated file.</li><li><strong>Limit Parameter Scope</strong>: Keep parameters minimal and purposeful — avoid using them as ad-hoc global variables.</li><li><strong>Leverage YAML</strong>: Store commonly used parameter sets in YAML for easy loading via ros2 param load.</li></ul><h3>Summary</h3><p>ROS2 Parameters unlock the flexibility to manage and share essential data across your robotic system. By using CLI commands, YAML files, and dynamic reconfiguration, you can rapidly tune your robot’s behavior without recompiling or restarting nodes. With this sample param_demo package, you’ve seen how to create a system that seamlessly combines C++ and Python nodes, each capable of reading and writing parameters in real time.</p><h3>Conclusion</h3><p>In this blog, we’ve explored the concept of ROS2 Parameters in depth — from basics to real-world usage in a mixed C++-Python project. Parameters let you achieve configurable, tunable, and maintainable robot software, all while keeping your code efficient.</p><p>If you want a refresher on other core ROS2 concepts — such as topics, services, actions, and building custom interfaces — be sure to revisit my previous posts:</p><ul><li><a href="#"><strong>Installing ROS2 in a Docker Container with GUI Support</strong></a></li><li><a href="#"><strong>Mastering ROS2: Your Ultimate Beginner’s Guide to Robotics</strong></a></li><li><a href="#"><strong>Mastering ROS2: Building Robust Communication with Custom Messages, Services, and Actions</strong></a></li></ul><p>Armed with this knowledge, you’re now ready to add powerful configuration capabilities to your ROS2 applications. Happy parameterizing!</p><p><em>You can find the complete implementation </em><a href="https://github.com/shashank3199/ROS-Tutorials-3"><em>here</em></a><em>. If you found this article helpful, please follow me on </em><a href="https://shashank-goyal-blogs.medium.com/"><em>Medium</em></a><em> and </em><a href="https://github.com/shashank3199/"><em>GitHub</em></a><em>. </em>If this post was useful, please click the clap 👏 button below a few times to show your support for the author.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*aUyN6YOrWzsxBQmw.png" /></figure><h4>👋 If you find this helpful, please click the clap 👏 button below a few times to show your support for the author 👇</h4><h4>🚀<a href="http://from.faun.to/r/8zxxd">Join FAUN Developer Community &amp; Get Similar Stories in your Inbox Each Week</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afd4c3890fc9" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/mastering-ros2-harnessing-the-power-of-ros2-parameters-for-real-time-configuration-afd4c3890fc9">Mastering ROS2: Harnessing the Power of ROS2 Parameters for Real-Time Configuration</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering ROS2: Building Robust Communication with Custom Messages, Services, and Actions]]></title>
            <link>https://faun.pub/mastering-ros2-building-robust-communication-with-custom-messages-services-and-actions-9a49b4cd8b16?source=rss-e85e3a6012ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a49b4cd8b16</guid>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[ros2]]></category>
            <category><![CDATA[robotics-development]]></category>
            <category><![CDATA[robot-operating-system]]></category>
            <category><![CDATA[begginers-guide]]></category>
            <dc:creator><![CDATA[Shashank Goyal]]></dc:creator>
            <pubDate>Sat, 04 Jan 2025 04:20:10 GMT</pubDate>
            <atom:updated>2025-01-31T12:42:56.890Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*V1cP85F106qLkCOkHr6dQQ.png" /></figure><h3>Introduction</h3><p>Welcome back to our <strong>Mastering ROS2</strong> series! In this comprehensive guide, we’ll explore how to build robust communication systems in ROS2 using custom messages, services, and actions. You’ll learn how to organize these components into dedicated packages and create seamless interactions between C++ and Python nodes.</p><p>If you’re new to ROS2 or need a reliable way to set up a development environment, explore our comprehensive guide on installing and configuring <a href="https://shashank-goyal-blogs.medium.com/ros2-humble-gui-docker-container-a-step-by-step-guide-c541b73fe141"><strong>ROS2 with GUI support in a Docker container</strong></a>. Additionally, if you’re a beginner with ROS2 already set up, check out our <a href="https://medium.com/@shashank-goyal-blogs/mastering-ros2-your-ultimate-beginners-guide-to-robotics-a72179db4c84"><strong>Beginner’s Guide to ROS2</strong></a> blog to build a strong foundation before proceeding with this one.</p><h3>What are Custom Interfaces in ROS2?</h3><p>At its core, ROS2 uses interfaces to define how different parts of your robotic system communicate. Let’s visualize how these different communication patterns work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zaQ_qnIRPHuzXCjDO2BoXQ.png" /></figure><h3>These interfaces come in three main types:</h3><h4>Messages (msg)</h4><ul><li>One-way communication</li><li>Continuous data streams</li><li>Great for sensor data, robot state updates</li></ul><h4>Services (srv)</h4><ul><li>Request-response pattern</li><li>Synchronous operations</li><li>Perfect for one-time queries or commands</li></ul><h4>Actions (action)</h4><ul><li>Goal-oriented tasks</li><li>Long-running operations with feedback</li><li>Ideal for navigation, manipulation tasks</li></ul><h3>Sample ROS2 Packages</h3><h4>Sample Package 1: Custom Interface Definitions</h4><p>This package contains custom message, service, and action definitions for robot control and monitoring.</p><p><strong>Creating the Package</strong></p><pre>ros2 pkg create --build-type ament_cmake custom_interfaces --dependencies std_msgs geometry_msgs</pre><p><strong>Project Structure</strong></p><pre>custom_interfaces/<br>├── msg/<br>│   ├── RobotStatus.msg<br>│   └── SensorData.msg<br>├── srv/<br>│   └── SetJointPosition.srv<br>├── action/<br>│   └── Navigate.action<br>├── CMakeLists.txt<br>└── package.xml</pre><p><strong>Source Files</strong></p><p>1. <strong>RobotStatus Message (</strong><strong>msg/RobotStatus.msg)</strong>: Defines the robot’s current state including battery level, joint positions, and operational status.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82239b2261a3db46eb609294a2f76646/href">https://medium.com/media/82239b2261a3db46eb609294a2f76646/href</a></iframe><p>2. <strong>SensorData Message (</strong><strong>msg/SensorData.msg):</strong> Defines a generic sensor data message.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f531eb5511d9e0f50fcbe935704fc1bf/href">https://medium.com/media/f531eb5511d9e0f50fcbe935704fc1bf/href</a></iframe><p>Let’s visualize our topic structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bc4vjwRFXoDbBQqaU2yjbw.png" /></figure><p>3. <strong>SetJointPosition Service (</strong><strong>srv/SetJointPosition.srv):</strong> Defines the service interface for setting robot joint positions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6afb130af4a474597cd549bd57cd9a5/href">https://medium.com/media/d6afb130af4a474597cd549bd57cd9a5/href</a></iframe><p>Let’s visualize our service structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TrKECYMUPkbJOufgsCCC3g.png" /></figure><p>4. <strong>Navigate Action (</strong><strong>action/Navigate.action):</strong> Defines the action interface for robot navigation tasks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0de24a1ed134d82af8aec38d4e7721ae/href">https://medium.com/media/0de24a1ed134d82af8aec38d4e7721ae/href</a></iframe><p>Let’s visualize our action structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sycghTxoKjuh_7OrfcTPfA.png" /></figure><p><strong>Setup Files</strong></p><p>1. CMakeLists.txt</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a877104a38be676eb870016ef75a1442/href">https://medium.com/media/a877104a38be676eb870016ef75a1442/href</a></iframe><p>2. package.xml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e28f29f194fff43f1b9e35017269eb4/href">https://medium.com/media/2e28f29f194fff43f1b9e35017269eb4/href</a></iframe><h4>Building the Package</h4><pre>colcon build --packages-select custom_interfaces<br>source install/setup.bash</pre><p><strong>Running the Package: </strong>View the interface definitions</p><pre># View message definition<br>ros2 interface show custom_interfaces/msg/RobotStatus<br><br># View service definition<br>ros2 interface show custom_interfaces/srv/SetJointPosition<br><br># View action definition<br>ros2 interface show custom_interfaces/action/Navigate</pre><p><strong>Test publishing and subscribing to messages:</strong></p><pre># Publish a RobotStatus message<br>ros2 topic pub /robot_status custom_interfaces/msg/RobotStatus &quot;{ \<br>  header: {stamp: {sec: 0, nanosec: 0}, frame_id: &#39;base_link&#39;}, \<br>  robot_name: &#39;robot1&#39;, \<br>  battery_level: 75.5, \<br>  joint_positions: [1.0, -0.5, 0.8], \<br>  is_operational: true, \<br>  state: 0, \<br>  error_message: &#39;&#39; \<br>}&quot;<br><br># Echo the messages<br>ros2 topic echo /robot_status</pre><p><strong>Expected Output</strong></p><pre>robot_status:<br>  header:<br>    stamp:<br>      sec: 0<br>      nanosec: 0<br>    frame_id: base_link<br>  robot_name: robot1<br>  battery_level: 75.5<br>  joint_positions: [1.0, -0.5, 0.8]<br>  is_operational: true<br>  state: 0<br>  error_message: &#39;&#39;</pre><p><strong>**Test calling (sending a requesting to the Service):</strong></p><pre># Call the joint position service<br>ros2 service call /set_joint_position custom_interfaces/srv/SetJointPosition &quot;{<br>  joint_name: &#39;shoulder&#39;,<br>  position: 1.57,<br>  max_velocity: 0.5<br>}&quot;</pre><p><strong>**Test send_goal to Action Server:</strong></p><pre># Send a navigation goal<br>ros2 action send_goal /navigate custom_interfaces/action/Navigate &quot;{<br>  target_pose: {<br>    header: {<br>      stamp: {sec: 0, nanosec: 0},<br>      frame_id: &#39;map&#39;<br>    },<br>    pose: {<br>      position: {x: 1.0, y: 2.0, z: 0.0},<br>      orientation: {x: 0.0, y: 0.0, z: 0.0, w: 1.0}<br>    }<br>  },<br>  max_velocity: 0.5<br>}&quot;</pre><p><strong>**We can also monitor action feedback in real-time by adding the </strong><strong>--feedback flag:</strong></p><pre># Send goal and watch feedback<br>ros2 action send_goal /navigate custom_interfaces/action/Navigate &quot;{<br>  target_pose: {<br>    header: {<br>      stamp: {sec: 0, nanosec: 0},<br>      frame_id: &#39;map&#39;<br>    },<br>    pose: {<br>      position: {x: 1.0, y: 2.0, z: 0.0},<br>      orientation: {x: 0.0, y: 0.0, z: 0.0, w: 1.0}<br>    }<br>  },<br>  max_velocity: 0.5<br>}&quot; --feedback</pre><p><strong>**Similarly, we can also cancel an Action Goal:</strong></p><pre># Cancel a specific goal by goal ID<br>ros2 action cancel_goal /navigate &lt;goal_id&gt;<br><br># Cancel the latest goal (most recently sent)<br>ros2 action cancel_goal /navigate --latest</pre><p>To get the goal ID, we can either:</p><ol><li>Note it when we send the goal (it’s printed in the output)</li><li>Use ros2 action list_goals /navigate to see all active goals</li></ol><p>For example, the complete workflow might look like:</p><pre># Send a goal (this will print a goal ID)<br>ros2 action send_goal /navigate custom_interfaces/action/Navigate &quot;{ ... }&quot;<br><br># List active goals<br>ros2 action list_goals /navigate<br><br># Cancel a specific goal<br>ros2 action cancel_goal /navigate d4f82...   # using the goal ID<br><br># Or cancel the most recent goal<br>ros2 action cancel_goal /navigate --latest</pre><p><strong>**Important Note: </strong>We can only test these scenarios, when the respective server codes are running.</p><h4>Sample Package 2: C++ Implementation</h4><p>This package implements service and action servers/clients in C++.</p><p><strong>Creating the Package</strong></p><pre>ros2 pkg create --build-type ament_cmake cpp_robotics --dependencies rclcpp custom_interfaces</pre><p><strong>Project Structure</strong></p><pre>cpp_robotics/<br>├── src/<br>│   ├── joint_service_server.cpp<br>│   ├── joint_service_client.cpp<br>│   ├── navigation_action_server.cpp<br>│   └── navigation_action_client.cpp<br>├── CMakeLists.txt<br>└── package.xml</pre><p><strong>Joint Position Service Server (</strong><strong>src/joint_service_server.cpp)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d42df0367b01f7dfce26c1e15aeb412c/href">https://medium.com/media/d42df0367b01f7dfce26c1e15aeb412c/href</a></iframe><p><strong>Joint Position Service Client (</strong><strong>src/joint_service_client.cpp)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1f1117748458a6ff769217d60f7934d/href">https://medium.com/media/e1f1117748458a6ff769217d60f7934d/href</a></iframe><p><strong>Navigation Action Server (</strong><strong>src/navigation_action_server.cpp)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c36bc74a76388faf166b053c406dd61/href">https://medium.com/media/1c36bc74a76388faf166b053c406dd61/href</a></iframe><p><strong>Navigation Action Client (</strong><strong>src/navigation_action_client.cpp)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6ea85596ce8de0519d7aa5f7ceee74e/href">https://medium.com/media/f6ea85596ce8de0519d7aa5f7ceee74e/href</a></iframe><p><strong>Setup Files</strong></p><p>1. CMakeLists.txt</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8e5c369d98eec3d596c35059c2b36a1/href">https://medium.com/media/b8e5c369d98eec3d596c35059c2b36a1/href</a></iframe><p>2. package.xml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1e6e430eea8df94a492c1070884f34f/href">https://medium.com/media/d1e6e430eea8df94a492c1070884f34f/href</a></iframe><p><strong>Building the Package</strong></p><pre>colcon build --packages-select cpp_robotics<br>source install/setup.bash</pre><p><strong>Running the Package</strong></p><p>Run the service components:</p><pre># Terminal 1: Run the service server<br>ros2 run cpp_robotics joint_service_server<br><br># Terminal 2: Run the service client<br>ros2 run cpp_robotics joint_service_client</pre><p>Run the action components:</p><pre># Terminal 1: Run the action server<br>ros2 run cpp_robotics navigation_action_server<br><br># Terminal 2: Run the action client<br>ros2 run cpp_robotics navigation_action_client</pre><p><strong>Expected Output</strong></p><pre># Service Server Output<br>[INFO] [joint_service_server]: Received request for joint &#39;shoulder&#39;<br>[INFO] [joint_service_server]: Setting position to 1.57<br>[INFO] [joint_service_server]: Position set successfully<br><br># Action Server Output<br>[INFO] [navigation_action_server]: Goal received<br>[INFO] [navigation_action_server]: Distance remaining: 9.00 meters<br>[INFO] [navigation_action_server]: Distance remaining: 8.00 meters<br>[INFO] [navigation_action_server]: Distance remaining: 7.00 meters<br>[INFO] [navigation_action_server]: Navigation completed successfully</pre><p><strong>Checking Feedback</strong></p><pre># Terminal 3: Echo Action Feedback<br>ros2 topic echo /navigate/_action/feedback<br><br># Terminal 4: Echo Action Status<br>ros2 topic echo /navigate/_action/status</pre><h4>Sample Package 3: Python Implementation</h4><p>This package implements service and action servers/clients in Python.</p><p><strong>Creating the Package</strong></p><pre>ros2 pkg create --build-type ament_python py_robotics --dependencies rclpy custom_interfaces</pre><p><strong>Project Structure</strong></p><pre>py_robotics/<br>├── py_robotics/<br>│   ├── __init__.py<br>│   ├── joint_service_server.py<br>│   ├── joint_service_client.py<br>│   ├── navigation_action_server.py<br>│   └── navigation_action_client.py<br>├── setup.py<br>├── setup.cfg<br>└── package.xml</pre><p><strong>Joint Position Service Server (</strong><strong>py_robotics/joint_service_server.py)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9239897d05a8d831ce5e57644392d1d/href">https://medium.com/media/a9239897d05a8d831ce5e57644392d1d/href</a></iframe><p><strong>Joint Position Service Client (</strong><strong>py_robotics/joint_service_client.py)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f055dec1e6eb0aa777fbb80b752db39e/href">https://medium.com/media/f055dec1e6eb0aa777fbb80b752db39e/href</a></iframe><p><strong>Navigation Action Server (</strong><strong>py_robotics/navigation_action_server.py)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53097f8bb7e35dbcb54bed0b71b7ab43/href">https://medium.com/media/53097f8bb7e35dbcb54bed0b71b7ab43/href</a></iframe><p><strong>Navigation Action Client (</strong><strong>py_robotics/navigation_action_client.py)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e13f357b08a79fbaef694ba124070c3e/href">https://medium.com/media/e13f357b08a79fbaef694ba124070c3e/href</a></iframe><p><strong>Setup Files</strong></p><p>1. setup.py</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff28fbfecac3e8341d5cab847f766a7d/href">https://medium.com/media/ff28fbfecac3e8341d5cab847f766a7d/href</a></iframe><p>2. package.xml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4a2a26d8b6ed8782573ec1e4fcc0441/href">https://medium.com/media/a4a2a26d8b6ed8782573ec1e4fcc0441/href</a></iframe><p><strong>Building the Package</strong></p><pre>colcon build --packages-select py_robotics<br>source install/setup.bash</pre><p><strong>Running the Package</strong></p><p>Run the service components:</p><pre># Terminal 1: Run the Python service server<br>ros2 run py_robotics joint_service_server<br><br># Terminal 2: Run the Python service client<br>ros2 run py_robotics joint_service_client</pre><p>Run the action components:</p><pre># Terminal 1: Run the Python action server<br>ros2 run py_robotics navigation_action_server<br><br># Terminal 2: Run the Python action client<br>ros2 run py_robotics navigation_action_client</pre><p><strong>Expected Output</strong></p><pre># Service Component Output<br>[INFO] [py_joint_service_server]: Received request for joint &#39;shoulder&#39;<br>[INFO] [py_joint_service_server]: Joint position set successfully<br>[INFO] [py_joint_service_client]: Service response received: Position set successfully<br><br># Server Terminal Output<br>[INFO] [py_navigation_server]: Executing navigation goal...<br>[INFO] [py_navigation_server]: Distance remaining: 10.00 meters<br>[INFO] [py_navigation_server]: Distance remaining: 9.00 meters<br>[INFO] [py_navigation_server]: Distance remaining: 8.00 meters<br>[INFO] [py_navigation_server]: Distance remaining: 7.00 meters<br>[INFO] [py_navigation_server]: Distance remaining: 6.00 meters<br>[INFO] [py_navigation_server]: Navigation completed successfully<br><br># Client Terminal Output<br>[INFO] [py_navigation_client]: Goal accepted<br>[INFO] [py_navigation_client]: Distance remaining: 10.00 meters, Current velocity: 1.00 m/s, Zone: zone_0<br>[INFO] [py_navigation_client]: Distance remaining: 9.00 meters, Current velocity: 1.00 m/s, Zone: zone_1<br>[INFO] [py_navigation_client]: Distance remaining: 8.00 meters, Current velocity: 1.00 m/s, Zone: zone_2<br>[INFO] [py_navigation_client]: Distance remaining: 7.00 meters, Current velocity: 1.00 m/s, Zone: zone_3<br>[INFO] [py_navigation_client]: Distance remaining: 6.00 meters, Current velocity: 1.00 m/s, Zone: zone_4<br>[INFO] [py_navigation_client]: Navigation completed with status: Navigation completed successfully</pre><h4>Cross-Language Communication in ROS2</h4><p>This section demonstrates how to mix and match C++ and Python implementations in ROS2, showcasing the framework’s language-agnostic communication capabilities.</p><h4>Service Communication Combinations</h4><p><strong>1. C++ Server with Python Client</strong></p><p>Terminal commands:</p><pre># Terminal 1: Start C++ Service Server<br>ros2 run cpp_robotics joint_service_server<br><br># Terminal 2: Run Python Service Client<br>ros2 run py_robotics joint_service_client</pre><p>Expected Output:</p><pre>[INFO] [cpp_joint_service_server]: Received request for joint &#39;shoulder&#39;<br>[INFO] [cpp_joint_service_server]: Joint position set successfully<br>[INFO] [py_joint_service_client]: Service response received: Position set successfully</pre><p><strong>2. Python Server with C++ Client</strong></p><p>Terminal commands:</p><pre># Terminal 1: Start Python Service Server<br>ros2 run py_robotics joint_service_server<br><br># Terminal 2: Run C++ Service Client<br>ros2 run cpp_robotics joint_service_client</pre><p>Expected Output:</p><pre>[INFO] [py_joint_service_server]: Received request for joint &#39;shoulder&#39;<br>[INFO] [py_joint_service_server]: Joint position set successfully<br>[INFO] [cpp_joint_service_client]: Service response received: Position set successfully</pre><h4>Action Communication Combinations</h4><p><strong>1. C++ Action Server with Python Client</strong></p><p>Terminal commands:</p><pre># Terminal 1: Start C++ Action Server<br>ros2 run cpp_robotics navigation_action_server<br><br># Terminal 2: Run Python Action Client<br>ros2 run py_robotics navigation_action_client</pre><p>Expected Output:</p><pre># C++ Server Output:<br>[INFO] [cpp_navigation_server]: Received navigation goal<br>[INFO] [cpp_navigation_server]: Executing goal...<br>[INFO] [cpp_navigation_server]: Publishing feedback...<br><br># Python Client Output:<br>[INFO] [py_navigation_client]: Goal accepted<br>[INFO] [py_navigation_client]: Distance remaining: 9.00 meters, Current velocity: 1.00 m/s, Zone: zone_1<br>[INFO] [py_navigation_client]: Navigation completed with status: Navigation completed successfully</pre><p><strong>2. Python Action Server with C++ Client</strong></p><p>Terminal commands:</p><pre># Terminal 1: Start Python Action Server<br>ros2 run py_robotics navigation_action_server<br><br># Terminal 2: Run C++ Action Client<br>ros2 run cpp_robotics navigation_action_client</pre><p>Expected Output:</p><pre># Python Server Output:<br>[INFO] [py_navigation_server]: Executing navigation goal...<br>[INFO] [py_navigation_server]: Publishing feedback: 9.00 meters remaining<br><br># C++ Client Output:<br>[INFO] [cpp_navigation_client]: Goal accepted<br>[INFO] [cpp_navigation_client]: Distance remaining: 9.00 meters, Current velocity: 1.00 m/s, Zone: zone_1<br>[INFO] [cpp_navigation_client]: Navigation succeeded: Navigation completed successfully</pre><h4>Important Considerations</h4><p><strong>Interface Compatibility</strong></p><ul><li>All nodes use the same custom interfaces defined in the custom_interfaces package</li><li>Message formats are language-agnostic</li><li>QoS settings should match between communicating nodes</li></ul><p><strong>Error Handling</strong></p><ul><li>Both C++ and Python implementations handle errors similarly</li><li>Timeouts and connection issues are handled consistently across languages</li></ul><h4>Performance Considerations</h4><ul><li>C++ implementations might offer better performance for computationally intensive tasks</li><li>Python implementations might be easier to develop and debug</li><li>Mixed-language systems can leverage the strengths of both languages</li></ul><h4>Debugging Tips</h4><p>Monitor your ROS2 system using these commands:</p><pre># List all active nodes<br>ros2 node list<br><br># List all message topics<br>ros2 topic list --include-hidden-topics<br><br># Check message flow on a topic<br>ros2 topic echo /topic_name<br><br># List available services<br>ros2 service list<br><br># Check action server status<br>ros2 action list<br><br># Get info about an action<br>ros2 action info /navigate<br><br># View service interface<br>ros2 interface show custom_interfaces/srv/SetJointPosition<br><br># View action interface<br>ros2 interface show custom_interfaces/action/Navigate</pre><h4>Common Issues and Solutions</h4><p><strong>1. Node Not Found</strong></p><ul><li>Verify package is built: colcon build --packages-select package_name</li><li>Source setup: source install/setup.bash</li><li>Check executable permissions for Python nodes</li></ul><p><strong>2. Communication Failures</strong></p><ul><li>Verify nodes are on same ROS_DOMAIN_ID</li><li>Check interface compatibility</li><li>Ensure QoS profiles match</li></ul><p><strong>3. Action Server Timeouts</strong></p><ul><li>Increase wait time in client</li><li>Verify server is running and accepting goals</li><li>Check network connectivity</li></ul><h4>Best Practices</h4><p><strong>1. Development Workflow</strong></p><ul><li>Develop and test same-language combinations first</li><li>Add cross-language communication gradually</li><li>Use ROS2 command-line tools for debugging</li></ul><p><strong>2. System Design</strong></p><ul><li>Choose language based on component requirements</li><li>Document interface usage clearly</li><li>Consider performance requirements when selecting language</li></ul><p><strong>3. Testing</strong></p><ul><li>Test all language combinations</li><li>Verify error handling across languages</li><li>Monitor system performance with mixed implementations</li></ul><h3>Summary</h3><p>In this comprehensive guide, we’ve explored the robust communication capabilities of ROS2, focusing on how to create and utilize custom messages, services, and actions. We’ve seen how to:</p><ul><li>Create custom interfaces in a dedicated package</li><li>Implement service and action patterns in both C++ and Python</li><li>Leverage ROS2’s language-agnostic communication</li><li>Mix and match C++ and Python implementations seamlessly</li></ul><p>The sample packages we’ve built demonstrate ROS2’s flexibility in handling different communication patterns:</p><ol><li><strong>Custom Interfaces Package</strong></li></ol><ul><li>Foundation for type-safe communication</li><li>Clear message, service, and action definitions</li><li>Reusable interface components</li></ul><p><strong>2. C++ Implementation</strong></p><ul><li>High-performance node examples</li><li>Robust error handling</li><li>Memory-efficient design patterns</li></ul><p><strong>3. Python Implementation</strong></p><ul><li>Rapid development capabilities</li><li>Clear, readable implementations</li><li>Easy debugging and testing</li></ul><p><strong>4. Cross-Language Communication</strong></p><ul><li>Language-agnostic message passing</li><li>Seamless C++/Python interoperability</li><li>Consistent behavior across languages</li></ul><h4>Conclusion</h4><p>The world of ROS2 is constantly evolving, with new tools, packages, and capabilities being added regularly. By mastering these fundamental communication patterns, you’ve laid a strong foundation for building sophisticated robotic applications.</p><p>Remember that effective robotic systems often combine multiple communication patterns, and the key is choosing the right pattern for each specific use case. Whether you’re building a simple mobile robot or a complex industrial automation system, the principles and patterns we’ve covered will serve as essential tools in your robotics development journey.</p><p><em>You can find the complete implementation </em><a href="https://github.com/shashank3199/ROS-Tutorials-2"><em>here</em></a><em>. If you found this article helpful, please follow me on </em><a href="https://shashank-goyal-blogs.medium.com/"><em>Medium</em></a><em> and </em><a href="https://github.com/shashank3199/"><em>GitHub</em></a><em>. </em>If this post was useful, please click the clap 👏 button below a few times to show your support for the author.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*aUyN6YOrWzsxBQmw.png" /></figure><h4>👋 If you find this helpful, please click the clap 👏 button below a few times to show your support for the author 👇</h4><h4>🚀<a href="http://from.faun.to/r/8zxxd">Join FAUN Developer Community &amp; Get Similar Stories in your Inbox Each Week</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a49b4cd8b16" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/mastering-ros2-building-robust-communication-with-custom-messages-services-and-actions-9a49b4cd8b16">Mastering ROS2: Building Robust Communication with Custom Messages, Services, and Actions</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering ROS2: Your Ultimate Beginner’s Guide to Robotics]]></title>
            <link>https://faun.pub/mastering-ros2-your-ultimate-beginners-guide-to-robotics-a72179db4c84?source=rss-e85e3a6012ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/a72179db4c84</guid>
            <category><![CDATA[ros2]]></category>
            <category><![CDATA[robotics-development]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[robot-operating-system]]></category>
            <category><![CDATA[begginers-guide]]></category>
            <dc:creator><![CDATA[Shashank Goyal]]></dc:creator>
            <pubDate>Sun, 29 Dec 2024 07:25:07 GMT</pubDate>
            <atom:updated>2025-01-31T12:42:49.419Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*4z57EVrhEmwdu2Km49sMzw.png" /></figure><h3>Introduction</h3><p>Have you ever marveled at how robots seamlessly coordinate their parts — from sensors to motors, vision systems to movement controllers? That’s where ROS2 comes into play. Despite its name, ROS2 isn’t an operating system. Instead, think of it as the maestro conducting a complex robotic orchestra, ensuring every component works in harmony.</p><p>Before we dive into the nuts and bolts of ROS2, if you’re looking for a guide on installing and setting up ROS2 in a Docker container with GUI support, check out this <a href="https://medium.com/@shashank-goyal-blogs/ros2-humble-gui-docker-container-a-step-by-step-guide-c541b73fe141">step-by-step guide</a>.</p><h3>What is ROS2?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*oSAug8DbsKkdKTcuKAjDCg.png" /><figcaption>ROS2: Humble Hawksbill</figcaption></figure><p>At its heart, ROS2 (Robot Operating System 2) is a middleware framework designed to streamline communication between different parts of a robotic system. Just like your computer’s operating system manages resources and facilitates communication between programs, ROS2 oversees the flow of information and resources in robotic applications. However, ROS2 operates at a higher level, offering specialized tools and libraries tailored specifically for robotics.</p><h3>More Than Just a Message Broker</h3><p>While ROS2 shares similarities with message brokers like RabbitMQ or Kafka — facilitating communication between different parts of a system — it goes way beyond simple message passing. ROS2 provides a rich ecosystem of tools and libraries specifically crafted for robotics, including:</p><ul><li><strong>Hardware Abstraction Layers:</strong> Makes it easier to interface with various hardware components through standardized interfaces.</li><li><strong>Device Drivers:</strong> Simplifies communication with a wide range of sensors and actuators.</li><li><strong>Robotics Libraries:</strong> Offers ready-to-use functionalities for navigation, manipulation, perception, and more.</li><li><strong>Visualization and Simulation Tools:</strong> Tools like RViz for visualization and Gazebo for simulation help you see and test your robots in action.</li><li><strong>Package Management:</strong> Organizes your code into reusable packages, managing dependencies and versions seamlessly.</li></ul><h3>The Architecture of ROS2 Packages</h3><p>One of the foundational concepts in ROS2 is its package structure. Imagine a ROS2 package as a self-contained unit of functionality — much like a module in a well-organized software system. Let’s take a look at what a typical ROS2 package looks like:</p><pre>my_robot_package/<br>├── config/                         # Configuration files<br>│   ├── controller.yaml             # Controller parameters<br>│   ├── sensor_params.yaml          # Sensor configurations<br>│   └── robot_params.yaml           # General robot parameters<br>├── meshes/                         # 3D model files<br>│   ├── robot_arm.stl               # STL format mesh<br>│   ├── robot_base.pqr.dae          # DAE format mesh<br>│   └── sensor_mount.obj            # OBJ format mesh<br>├── urdf/                           # Robot description files<br>│   ├── robot.urdf.xacro            # Main URDF file using xacro<br>│   ├── robot.component.xacro       # Component-specific URDF<br>│   ├── robot.ros2_control.xacro    # ROS2 control URDF<br>│   └── robot.urdf.xml              # Expanded URDF file<br>├── include/                        # C++ header files<br>│   └── my_robot_package/<br>│       ├── controller.hpp          # Controller class header<br>│       └── sensor.hpp              # Sensor class header<br>├── launch/                         # Launch files<br>│   ├── start_robot.py              # Launch file to start robot nodes<br>│   └── simulation.launch.py        # Launch file for simulation<br>├── msg/                            # Custom message definitions<br>│   ├── RobotStatus.msg             # Custom message for robot status<br>│   └── SensorData.msg              # Custom message for sensor data<br>├── srv/                            # Service definitions<br>│   ├── ControlCommand.srv          # Service for control commands<br>│   └── GetSensorInfo.srv           # Service to get sensor information<br>├── action/                         # Action definitions<br>│   ├── Navigate.action             # Action for navigation<br>│   └── Manipulate.action           # Action for manipulation tasks<br>├── src/                            # Source code<br>│   ├── controller_node.cpp         # C++ controller node<br>│   └── sensor_node.cpp             # C++ sensor node<br>├── my_robot_package/               # Python module<br>│   ├── __init__.py                 # Initializes the Python package<br>│   ├── robot_controller.py         # Python controller script<br>│   └── sensor_manager.py           # Python sensor management script<br>├── CMakeLists.txt                  # Build system configuration<br>├── package.xml                     # Package metadata and dependencies<br>├── setup.py                        # Python setup script<br>└── setup.cfg                       # Python configuration file</pre><h3>Directory Breakdown</h3><p>Let’s dive into each directory’s purpose and contents:</p><ul><li><strong>config/:</strong> This is where you store all your configuration files. These YAML files contain parameters that can be loaded at runtime:<br>-<em> Controller parameters:</em> PID gains, control loops settings<br>- <em>Sensor configurations:</em> Update rates, thresholds, calibration data<br>-<em> Robot parameters:</em> Physical dimensions, limits, default behaviors</li><li><strong>meshes/:</strong> Houses 3D models used for visualization in RViz or simulation in Gazebo:<br>- Supports multiple formats: STL (common for 3D printing), DAE (Collada, with texture support), OBJ (with material properties)<br>- Used by URDF files to define the robot’s visual appearance</li><li><strong>urdf/:</strong> Contains the robot&#39;s structural definition files:<br>- <em>Main URDF file:</em> Describes the robot’s kinematic and dynamic properties<br>- <em>Component files:</em> Modular descriptions of robot parts<br>- <em>ROS2 control file:</em> Defines interfaces for hardware control<br>- Uses Xacro for template-based URDF generation, making files more maintainable</li><li><strong>include/:</strong> C++ header files organized by package:<br>- Follows C++ best practices for header organization<br>- Contains class declarations, template definitions<br>- Usually paired with implementation files in src/</li><li><strong>launch/:</strong> Python-based launch files that:<br>- Orchestrate node startup sequences<br>- Configure node parameters<br>- Set up robot state publishers<br>- Launch simulation environments when needed</li><li><strong>msg/, </strong><strong>srv/, </strong><strong>action/:</strong> Define custom communication interfaces:<br><em>- Messages:</em> For continuous data streams (sensor readings, state updates)<br><em>- Services:</em> For request-response interactions (queries, commands)<br><em>- Actions:</em> For long-running tasks with feedback (navigation, manipulation)</li><li><strong>src/:</strong> Source code for C++ nodes:<br>- Implementation of node functionality<br>- Hardware drivers<br>- Algorithms and control logic</li><li><strong>my_robot_package/:</strong> Python module containing:<br>- Node implementations in Python<br>- Utility functions and helper classes<br>- Python-based tools and scripts</li></ul><h3>The Communication Model</h3><p>ROS2’s communication framework revolves around three main concepts: <strong>Topics</strong>, <strong>Services</strong>, and <strong>Actions</strong>. Let’s break each of these down.</p><h4>Topics: The Publisher-Subscriber Pattern</h4><p>Think of topics as broadcast channels. Publishers send messages to a topic, and any number of subscribers can listen to that topic and receive the messages. This is perfect for continuous data streams, like sensor readings or control commands.</p><h4>How Topics Work</h4><ol><li><strong>Publishers</strong> send messages to a <strong>topic queue</strong>.</li><li>Messages are stored based on <strong>Quality of Service (QoS)</strong> settings.</li><li><strong>Subscribers</strong> receive messages from the queue.</li><li>Multiple subscribers can receive the same message simultaneously.</li></ol><p>Here’s a simple visualization:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XvcAjfmkekc90JVvB8WDvA.png" /></figure><h3>Services: The Request-Response Pattern</h3><p>Services are great for tasks that require a one-time interaction, like querying data or sending a specific command. It follows a synchronous request-response model where a client sends a request and waits for a response from the server.</p><h4>How Services Work</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bg7YVL3hNrpFvL3m7ng2Kg.png" /></figure><h3>Actions: Long-Running Tasks with Feedback</h3><p>Actions are perfect for operations that take time and need ongoing feedback, like navigating to a location or manipulating an object. They blend the features of topics and services, allowing for goal setting, feedback during execution, and final results.</p><h4>How Actions Work</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-XipdqDxJa1lkXPvmkoLOg.png" /></figure><h3>Custom Message Types</h3><p>ROS2 allows you to create your own message types tailored to your robot’s specific needs. This flexibility ensures that your nodes can communicate effectively using data structures that make sense for your application.</p><h4>Message Definition (msg/RobotStatus.msg)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8cecdd559957b81bd18ff56d8b467e7/href">https://medium.com/media/b8cecdd559957b81bd18ff56d8b467e7/href</a></iframe><p><em>What’s Inside:</em></p><ul><li><strong>Header:</strong> Keeps track of when and where the message was created.</li><li><strong>robot_name:</strong> The name of your robot.</li><li><strong>battery_level:</strong> Current battery status.</li><li><strong>joint_positions:</strong> Positions of the robot’s joints.</li><li><strong>is_operational:</strong> Whether the robot is functioning properly.</li><li><strong>state:</strong> Current state of the robot (Idle, Moving, or Error).</li></ul><h4>Service Definition (srv/SetJointPosition.srv)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbd8efbf0db4e91e9cd1dc3f47f22a59/href">https://medium.com/media/fbd8efbf0db4e91e9cd1dc3f47f22a59/href</a></iframe><p><em>What’s Inside:</em></p><ul><li><strong>Request:<br>- joint_name:</strong> Which joint to move.<br><strong>- position:</strong> Desired position.<br><strong>- max_velocity:</strong> Maximum speed for the movement.</li><li><strong>Response:<br>- success:</strong> Whether the operation was successful.<br>- <strong>message:</strong> Additional info or error messages.<br>- <strong>actual_position:</strong> The final position achieved.</li></ul><h4>Action Definition (action/Navigate.action)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea87d837a78245f5cea9f6bae84dcc73/href">https://medium.com/media/ea87d837a78245f5cea9f6bae84dcc73/href</a></iframe><p><em>What’s Inside:</em></p><ul><li><strong>Goal:<br>- target_pose:</strong> Where you want the robot to go.<br>- <strong>max_velocity:</strong> How fast the robot should move.</li><li><strong>Result:<br>- success:</strong> Whether navigation was successful.<br>- <strong>message:</strong> Additional info or error messages.<br>- <strong>total_distance_traveled:</strong> How far the robot moved.<br>- <strong>final_pose:</strong> The final position and orientation.</li><li><strong>Feedback:<br>- distance_remaining:</strong> How much more the robot needs to travel.<br>- <strong>current_velocity:</strong> Current speed.<br>- <strong>current_zone:</strong> The area the robot is navigating through.</li></ul><p>After defining these custom message types, you’ll need to update your CMakeLists.txt (for C++) and setup.py (for Python) to generate the message interfaces.</p><h4>CMakeLists.txt Additions</h4><pre>find_package(rosidl_default_generators REQUIRED)<br><br>rosidl_generate_interfaces(${PROJECT_NAME}<br>  &quot;msg/RobotStatus.msg&quot;<br>  &quot;srv/SetJointPosition.srv&quot;<br>  &quot;action/Navigate.action&quot;<br>  DEPENDENCIES geometry_msgs std_msgs<br>)</pre><p><em>Explanation:</em></p><ul><li><strong>find_package:</strong> Finds the necessary ROS2 packages for generating message interfaces.</li><li><strong>rosidl_generate_interfaces:</strong> Tells ROS2 which message, service, and action files to process and their dependencies.</li></ul><h4>package.xml Additions</h4><pre>&lt;depend&gt;geometry_msgs&lt;/depend&gt;<br>&lt;depend&gt;std_msgs&lt;/depend&gt;<br>&lt;buildtool_depend&gt;rosidl_default_generators&lt;/buildtool_depend&gt;<br>&lt;exec_depend&gt;rosidl_default_runtime&lt;/exec_depend&gt;<br>&lt;member_of_group&gt;rosidl_interface_packages&lt;/member_of_group&gt;</pre><p><em>Explanation:</em></p><ul><li><strong>Dependencies:</strong> Specifies which packages your messages depend on.</li><li><strong>Build Tool Dependency:</strong> Required for generating message interfaces during build.</li><li><strong>Execution Dependency:</strong> Needed at runtime.</li><li><strong>Member of Group:</strong> Categorizes the package appropriately within ROS2.</li></ul><h3>Basic Communication Syntax</h3><p>Let’s look at some basic examples of how to set up publishers, subscribers, services, and actions in both Python and C++. These snippets will give you a taste of how ROS2 handles communication.</p><h4>Python</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0468cbc871170a7dc1b79ccd3675f4f1/href">https://medium.com/media/0468cbc871170a7dc1b79ccd3675f4f1/href</a></iframe><p><em>Quick Breakdown:</em></p><ul><li><strong>Publisher:</strong> Sends messages of a specific type to a topic.</li><li><strong>Subscriber:</strong> Listens to a topic and processes incoming messages with a callback function.</li><li><strong>Service:</strong> Handles requests and sends back responses.</li><li><strong>Client:</strong> Sends requests to a service.</li><li><strong>Action Server:</strong> Manages long-running tasks, providing feedback.</li><li><strong>Action Client:</strong> Initiates tasks and receives feedback and results.</li></ul><h4>C++</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e93e780e3a6d0c917abd2465ae794393/href">https://medium.com/media/e93e780e3a6d0c917abd2465ae794393/href</a></iframe><p><em>Quick Breakdown:</em></p><ul><li><strong>Publisher:</strong> Initializes a publisher for a specific message type on a topic.</li><li><strong>Subscriber:</strong> Subscribes to a topic and binds a callback method to handle incoming messages.</li><li><strong>Service:</strong> Creates a service server that binds a callback to process requests.</li><li><strong>Client:</strong> Initializes a client to communicate with a service.</li><li><strong>Action Server:</strong> Sets up an action server to handle long-running tasks.</li><li><strong>Action Client:</strong> Creates a client to send goals to an action server.</li></ul><h3>Sample ROS2 Packages</h3><p>To make things clearer, let’s walk through some sample ROS2 packages. Each sample showcases different combinations of Python and C++ nodes, highlighting ROS2’s flexibility in supporting multiple programming languages. You can find the below code at <a href="https://github.com/shashank3199/ROS-Tutorials-1">GitHub</a>.</p><h4>Sample Package 1: Python Publisher and C++ Subscriber</h4><p>This package demonstrates how Python and C++ nodes can work together within the same ROS2 package, offering a hybrid approach to robotics development.</p><p><strong>Creating Package</strong></p><pre>ros2 pkg create --build-type ament_cmake mixed_pub_sub</pre><p><strong>Project Structure</strong></p><pre>mixed_pub_sub/<br>├── src/                     <br>│   └── twist_subscriber.cpp          # C++ subscriber node<br>├── mixed_pub_sub/<br>│   ├── __init__.py                   # Allows ROS2 to recognize build system<br>│   └── twist_publisher.py            # Python publisher node<br>├── CMakeLists.txt                    # Build system configuration<br>├── package.xml                       # Package metadata and dependencies<br>└── setup.py                          # Python setup script</pre><p><strong>Python Publisher (</strong><strong>twist_publisher.py)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8232a57b1bb8a8bdf035a6e5f52050be/href">https://medium.com/media/8232a57b1bb8a8bdf035a6e5f52050be/href</a></iframe><p><em>What’s Happening:</em></p><ul><li><strong>TwistPublisher Class:</strong> Creates a publisher that sends TwistStamped messages to the cmd_vel topic every 0.1 seconds.</li><li><strong>Logging:</strong> Each time a message is published, it logs a message for easy monitoring.</li></ul><p><strong>C++ Subscriber (</strong><strong>twist_subscriber.cpp)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0344eec65f7f597c4181137eba731090/href">https://medium.com/media/0344eec65f7f597c4181137eba731090/href</a></iframe><p><em>What’s Happening:</em></p><ul><li><strong>TwistSubscriber Class:</strong> Listens to the cmd_vel topic and logs any incoming TwistStamped messages.</li></ul><p><strong>Setup Files</strong></p><ol><li>setup.py</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ff36beddcd0911e58664a5716b0ac58/href">https://medium.com/media/0ff36beddcd0911e58664a5716b0ac58/href</a></iframe><ul><li><strong>Entry Points:</strong> Defines twist_publisher as a ROS2 node that can be launched using the ROS2 command.</li></ul><p>2. CMakeLists.txt</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f51339ef76df8e6643a79cf0505e6495/href">https://medium.com/media/f51339ef76df8e6643a79cf0505e6495/href</a></iframe><p><em>What’s Happening:</em></p><ul><li><strong>Executable Definitions:</strong> Defines and links the C++ subscriber.</li><li><strong>Installation Rules:</strong> Specifies where to install both the Python publisher and C++ subscriber executables.</li></ul><p>3. package.xml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe4865b094b69d12a08b3862e526762f/href">https://medium.com/media/fe4865b094b69d12a08b3862e526762f/href</a></iframe><p><em>What’s Happening:</em></p><ul><li><strong>Dependencies:</strong> Lists all the necessary build and runtime dependencies for the package.</li></ul><p><strong>Building the Package: </strong>Once the code for the package is completed and ready. Change directory to the ROS2 workspace and run colcon build command.</p><p><strong>Running the Package: </strong>Once you’ve built and sourced your ROS2 workspace, launching these sample packages is straightforward. Open separate terminals for each node to see them interact in real-time.</p><pre># Terminal 1: Run the Python Publisher<br>ros2 run mixed_pub_sub twist_publisher<br><br># Terminal 2: Run the C++ Subscriber<br>ros2 run mixed_pub_sub twist_subscriber</pre><p><em>What to Expect:</em></p><ul><li><strong>Terminal 1:</strong> The Python publisher starts sending TwistStamped messages to the cmd_vel topic every 0.1 seconds.</li><li><strong>Terminal 2:</strong> The C++ subscriber listens to the cmd_vel topic and logs each received message.</li></ul><h4>Sample Package 2: C++ Publisher and Python Subscriber</h4><p>This package flips the previous setup, with the publisher in C++ and the subscriber in Python. It highlights ROS2’s seamless interoperability between different programming languages.</p><p><strong>Creating Package</strong></p><pre>ros2 pkg create --build-type ament_cmake mixed_cpp_py_pkg</pre><p><strong>Project Structure</strong></p><pre>mixed_cpp_py_pkg/<br>├── src/                     <br>│   └── twist_publisher.cpp          # C++ publisher node<br>├── mixed_cpp_py_pkg/        <br>│   ├── __init__.py                  # Allows ROS2 to recognize build system<br>│   └── twist_subscriber.py          # Python subscriber node<br>├── CMakeLists.txt                   # Build system configuration<br>├── package.xml                      # Package metadata and dependencies<br>└── setup.py                         # Python setup script</pre><p><strong>C++ Publisher (</strong><strong>twist_publisher.cpp)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48fc5ae5cb36dfc9525f18d8689ece88/href">https://medium.com/media/48fc5ae5cb36dfc9525f18d8689ece88/href</a></iframe><p><em>What’s Happening:</em></p><ul><li><strong>TwistPublisher Class:</strong> Sends TwistStamped messages to the cmd_vel topic every 0.1 seconds.</li></ul><p><strong>Python Subscriber (</strong><strong>twist_subscriber.py)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb790b9bf6a095299df3072d2dcf3ab6/href">https://medium.com/media/cb790b9bf6a095299df3072d2dcf3ab6/href</a></iframe><p><em>What’s Happening:</em></p><ul><li><strong>TwistSubscriber Class:</strong> Listens to the cmd_vel topic and logs incoming TwistStamped messages.</li></ul><p><strong>Setup Files</strong></p><ol><li>setup.py</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e66f185c3a61f28f1323a54f6f39816/href">https://medium.com/media/6e66f185c3a61f28f1323a54f6f39816/href</a></iframe><p><em>What’s Happening:</em></p><ul><li><strong>Entry Points:</strong> Defines twist_subscriber as a ROS2 node that can be launched using the ROS2 command.</li></ul><p>2. CMakeLists.txt</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96cb6560726ebae11e8c36030dd12ed2/href">https://medium.com/media/96cb6560726ebae11e8c36030dd12ed2/href</a></iframe><p><em>What’s Happening:</em></p><ul><li><strong>Executable Definitions:</strong> Defines and links the C++ publisher.</li><li><strong>Installation Rules:</strong> Specifies where to install both the Python subscriber and C++ publisher executables.</li></ul><p>3. package.xml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/353615dbb6115df092035e85f589d24e/href">https://medium.com/media/353615dbb6115df092035e85f589d24e/href</a></iframe><p><em>What’s Happening:</em></p><ul><li><strong>Dependencies:</strong> Lists all the necessary build and runtime dependencies for the package.</li></ul><p><strong>Building the Package: </strong>Once the code for the package is completed and ready. Change directory to the ROS2 workspace and run colcon build command.</p><p><strong>Running the Package: </strong>Once you’ve built and sourced your ROS2 workspace, launching these sample packages is straightforward. Open separate terminals for each node to see them interact in real-time.</p><pre># Terminal 1: Run the C++ Publisher<br>ros2 run mixed_cpp_py_pkg twist_publisher<br><br># Terminal 2: Run the Python Subscriber<br>ros2 run mixed_cpp_py_pkg twist_subscriber</pre><p><em>What to Expect:</em></p><ul><li><strong>Terminal 1:</strong> The C++ publisher emits TwistStamped messages to the cmd_vel topic every 0.1 seconds.</li><li><strong>Terminal 2:</strong> The Python subscriber listens to the cmd_vel topic and logs each incoming message.</li></ul><h4>Sample Package 3: Pure C++ Publisher and Subscriber</h4><p>This package is entirely in C++, with both the publisher and subscriber written in C++. It’s ideal for scenarios where performance is crucial.</p><p><strong>Creating Package</strong></p><pre>ros2 pkg create --build-type ament_cmake cpp_pub_sub_pkg</pre><p><strong>Project Structure</strong></p><pre>cpp_pub_sub_pkg/<br>├── src/                     <br>│   ├── twist_publisher.cpp    # C++ publisher node<br>│   └── twist_subscriber.cpp   # C++ subscriber node<br>├── CMakeLists.txt             # Build system configuration<br>└── package.xml                # Package metadata and dependencies</pre><p><strong>1. C++ Publisher (</strong><strong>twist_publisher.cpp): </strong>Remains exactly the same as the previous packages.</p><p><strong>2. C++ Subscriber (</strong><strong>twist_subscriber.cpp): </strong>Remains exactly the same as the previous packages.</p><p><strong>3. </strong><strong>CMakeLists.txt</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3dce33a91cba874f226c651153dc1ae7/href">https://medium.com/media/3dce33a91cba874f226c651153dc1ae7/href</a></iframe><p><em>What’s Happening:</em></p><ul><li><strong>Executable Definitions:</strong> Defines and links both C++ publisher and subscriber.</li><li><strong>Installation Rules:</strong> Specifies where to install both executables.</li></ul><p>4. <strong>package.xml</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3233c0fb38c4721b4a215b215ddbb824/href">https://medium.com/media/3233c0fb38c4721b4a215b215ddbb824/href</a></iframe><p><em>What’s Happening:</em></p><ul><li><strong>Dependencies:</strong> Lists all the necessary build and runtime dependencies for the package.</li></ul><p><strong>Building the Package: </strong>Once the code for the package is completed and ready. Change directory to the ROS2 workspace and run colcon build command.</p><p><strong>Running the Package: </strong>Once you’ve built and sourced your ROS2 workspace, launching these sample packages is straightforward. Open separate terminals for each node to see them interact in real-time.</p><pre># Terminal 1: Run the C++ Publisher<br>ros2 run cpp_pub_sub_pkg cpp_twist_publisher<br><br># Terminal 2: Run the C++ Subscriber<br>ros2 run cpp_pub_sub_pkg cpp_twist_subscriber</pre><p><em>What to Expect:</em></p><ul><li><strong>Terminal 1:</strong> The C++ publisher sends out TwistStamped messages to the cmd_vel topic.</li><li><strong>Terminal 2:</strong> The C++ subscriber receives and logs these messages.</li></ul><h4>Sample Package 4: Pure Python Publisher and Subscriber</h4><p>This package is entirely in Python, making it perfect for those who prefer Python’s simplicity and rapid development capabilities.</p><p><strong>Creating Package</strong></p><pre>ros2 pkg create --build-type ament_python py_pub_sub_pkg</pre><p><strong>Project Structure</strong></p><pre>py_pub_sub_pkg/<br>├── py_pub_sub_pkg/                     <br>│   ├── __init__.py           # Allows ROS2 to recognize build system<br>│   ├── twist_publisher.py    # Python publisher node<br>│   └── twist_subscriber.py   # Python subscriber node<br>├── package.xml               # Package metadata and dependencies<br>├── setup.cfg                 # Build system configuration<br>└── setup.py                  # Python setup script</pre><p><strong>1. Python Publisher (</strong><strong>twist_publisher.py): </strong>Remains exactly the same as the previous packages.</p><p><strong>2. Python Subscriber (</strong><strong>twist_subscriber.py): </strong>Remains exactly the same as the previous packages.</p><h4>Setup Files</h4><p>3. setup.py</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a10aa52d491d132a65616a0a6bfdc3b6/href">https://medium.com/media/a10aa52d491d132a65616a0a6bfdc3b6/href</a></iframe><p>4. setup.cnf</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c59221cb9e061afe0457b2bd8271048f/href">https://medium.com/media/c59221cb9e061afe0457b2bd8271048f/href</a></iframe><p>5. package.xml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32f976fa8226205684fc91c5d7b8efb2/href">https://medium.com/media/32f976fa8226205684fc91c5d7b8efb2/href</a></iframe><p><strong>Building the Package: </strong>Once the code for the package is completed and ready. Change directory to the ROS2 workspace and run colcon build command.</p><p><strong>Running the Package: </strong>Once you’ve built and sourced your ROS2 workspace, launching these sample packages is straightforward. Open separate terminals for each node to see them interact in real-time.</p><pre># Terminal 1: Run the Python Publisher<br>ros2 run py_pub_sub_pkg py_twist_publisher<br><br># Terminal 2: Run the Python Subscriber<br>ros2 run py_pub_sub_pkg py_twist_subscriber</pre><p><em>What to Expect:</em></p><ul><li><strong>Terminal 1:</strong> The Python publisher starts sending TwistStamped messages to the cmd_vel topic.</li><li><strong>Terminal 2:</strong> The Python subscriber listens and logs each message it receives.</li></ul><h3>Best Practices and Tips</h3><p>Building robust and maintainable ROS2 applications is all about following best practices and making the most of ROS2’s features. Here are some tips to keep in mind:</p><p><strong>1. Node Design</strong></p><ul><li><strong>Single Responsibility Principle:</strong> Keep each node focused on a single task. This makes your system modular and easier to manage.</li><li><strong>Meaningful Naming:</strong> Use clear and descriptive names for your nodes and topics to make your system more understandable.</li><li><strong>Graceful Error Handling:</strong> Implement error handling to allow nodes to recover from unexpected issues without crashing.</li></ul><p><strong>2. Package Organization</strong></p><ul><li><strong>Stick to Standard Structures:</strong> Adhering to ROS2’s standard package structure ensures compatibility and makes your packages easier to navigate.</li><li><strong>Group Related Functionality:</strong> Organize related code and resources within the same package or logical subdirectories.</li><li><strong>Document Everything:</strong> Clear documentation helps you and others understand how your packages work and what dependencies they have.</li></ul><p><strong>3. Communication Patterns</strong></p><ul><li><strong>Use Topics for Continuous Streams:</strong> Perfect for sensor data or ongoing control commands.</li><li><strong>Leverage Services for One-Time Requests:</strong> Ideal for querying data or triggering specific actions.</li><li><strong>Employ Actions for Long-Running Tasks:</strong> Great for operations that need feedback, like navigation or object manipulation.</li></ul><p><strong>4. Configuration Management</strong></p><ul><li><strong>Utilize YAML Files:</strong> Manage parameters using YAML files to easily adjust settings without touching the code.</li></ul><p><strong>5. Performance Optimization</strong></p><ul><li><strong>Design Efficient Messages:</strong> Keep your custom message types lightweight to reduce communication overhead.</li><li><strong>Tune QoS Settings:</strong> Adjust Quality of Service parameters to balance reliability and performance based on your application’s needs.</li></ul><p><strong>6. Engage with the Community</strong></p><ul><li><a href="https://ros.org/"><strong>Explore Official Documentation</strong></a><strong>:</strong> Stay updated with ROS2’s latest features and best practices.</li><li><strong>Participate in Forums:</strong> Join ROS2 community forums and mailing lists to seek help and share your knowledge.</li><li><strong>Contribute Back:</strong> Consider contributing to ROS2 packages and tools to help the community grow and improve.</li></ul><h3>Conclusion</h3><p>ROS2 is a powerhouse framework that simplifies the complexities of building robotic applications. By grasping its core concepts and adhering to best practices, you can develop robust, efficient, and maintainable robot software. Whether you’re crafting a simple mobile robot or diving into complex industrial automation, ROS2’s modular architecture and extensive toolset make it an excellent choice for your robotics projects.</p><p>But don’t stop here! ROS2 is packed with advanced features waiting to be explored:</p><ul><li><strong>Parameter Handling:</strong> Dynamically manage configurations across your nodes.</li><li><strong>Transformations (tf2):</strong> Easily handle coordinate frame transformations for sensor data and robot states.</li><li><strong>Navigation Capabilities:</strong> Utilize ROS2’s navigation stack for autonomous movement and obstacle avoidance.</li><li><strong>Manipulation Libraries:</strong> Implement intricate manipulation tasks with ROS2’s manipulation tools.</li><li><strong>Simulation Integration:</strong> Test and refine your robot’s behaviors in virtual environments like Gazebo before real-world deployment.</li></ul><p>As you continue your journey with ROS2, take advantage of these features and tap into the vibrant community resources available. Happy building, and may your robots perform flawlessly!</p><p><em>You can find the complete implementation </em><a href="https://github.com/shashank3199/ROS-Tutorials-1"><em>here</em></a><em>. If you found this article helpful, please follow me on </em><a href="https://shashank-goyal-blogs.medium.com/"><em>Medium</em></a><em> and </em><a href="https://github.com/shashank3199/"><em>GitHub</em></a><em>. </em>If this post was useful, please click the clap 👏 button below a few times to show your support for the author.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*aUyN6YOrWzsxBQmw.png" /></figure><h4>👋 If you find this helpful, please click the clap 👏 button below a few times to show your support for the author 👇</h4><h4>🚀<a href="http://from.faun.to/r/8zxxd">Join FAUN Developer Community &amp; Get Similar Stories in your Inbox Each Week</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a72179db4c84" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/mastering-ros2-your-ultimate-beginners-guide-to-robotics-a72179db4c84">Mastering ROS2: Your Ultimate Beginner’s Guide to Robotics</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the Beauty of Euler’s Identity]]></title>
            <link>https://shashank-goyal-blogs.medium.com/exploring-the-beauty-of-eulers-identity-7a42805520dd?source=rss-e85e3a6012ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a42805520dd</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[stem]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[complex-number]]></category>
            <dc:creator><![CDATA[Shashank Goyal]]></dc:creator>
            <pubDate>Thu, 26 Dec 2024 06:44:13 GMT</pubDate>
            <atom:updated>2024-12-26T06:44:13.385Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z8YA9iXKhY47YK-h" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/0*vHwF_e-BXBzIYLB_.png" /></figure><p>Euler’s Identity, is one of the most beautiful equations in mathematics, connecting fundamental constants of mathematics and showcasing the elegance of mathematical relationships. In this blog, we’ll explore its derivation step by step.</p><h3>Understanding Pi</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*zvZ770nn2kzjdSH7VFp1pA.png" /></figure><p>Pi (π) is a well-known constant in geometry, representing the ratio of a circle’s circumference to its diameter, approximately equal to 3.14. Beyond geometry, π plays a critical role in measuring angles. There are two main units for measuring angles: degrees and radians.</p><p>In degrees, a full circle is 360°. In radians, however, a full circle is measured as 2π radians. For example, an angle of 90° is equivalent to π/2 radians.</p><p>In calculus and advanced mathematics, angles are typically measured in radians, as they simplify calculations. Notably, when dealing with radians, we often omit the unit “rad” for convenience; if an angle is written without a unit, it is assumed to be in radians.</p><p>Radians are particularly useful because when a circle’s radius is 1, the length of an arc is numerically equal to the angle it subtends, provided the angle is measured in radians. This natural relationship makes radians a preferred unit in many mathematical contexts.</p><h3>Understanding the Imaginary Unit <em>i</em></h3><p>The imaginary unit <em>i</em>, also known as iota, is a fundamental concept in mathematics that represents the square root of negative one. While this might sound strange at first — after all, no real number squared equals negative one - <em>i</em> is a powerful tool for extending the number system beyond the real numbers into what we call the complex numbers.</p><h4>What is i?</h4><p>Mathematically, <em>i</em> is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/75/0*sLVie2POTPmufuDK.png" /></figure><p>This definition allows us to work with square roots of negative numbers, which are otherwise undefined in the real number system. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/0*6LAX_xeNmQ3IGkDH.png" /></figure><h4>Why Do We Need i?</h4><p>The introduction of <em>i</em> solves real mathematical problems. In equations like x² + 1 = 0, the solutions cannot be real numbers. Using <em>i</em>, we can express the solutions as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/58/0*2RUPeM6k8vvPvzSa.png" /></figure><h4>Properties of i</h4><p>One of the fascinating aspects of <em>i</em> is how it behaves when raised to powers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/64/0*XG3qgMqAapDrgUAO.png" /></figure><h4>Applications of i</h4><p>While <em>i</em> might seem abstract, it has many practical applications:</p><ul><li>In electrical engineering, complex numbers are used to analyze alternating current (AC) circuits.</li><li>In quantum mechanics, imaginary numbers are integral to the mathematics describing wave functions and quantum states.</li><li>In signal processing, techniques like the Fourier transform rely on complex numbers to analyze frequency components.</li><li>In control systems, imaginary numbers help in designing stable and efficient systems.</li></ul><h4>Beyond Math: A Tool for Thinking</h4><p>Imaginary numbers challenge our intuition but open up a richer way to describe and solve problems. Much like how negative numbers expanded our understanding of subtraction, <em>i</em> expands our ability to work with equations and phenomena that extend beyond the real world.</p><p>By embracing <em>i</em>, we unlock the door to the complex plane - a mathematical landscape filled with elegance and utility.</p><h3>Unveiling Differentiation: The Art of Change</h3><h4>What Is Differentiation?</h4><p>Differentiation is a fundamental concept in calculus that helps us understand how things change. It allows us to measure the rate at which one quantity changes with respect to another. For instance, imagine you’re driving a car. The <strong>distance</strong> you cover changes with time, and the speedometer tells you your <strong>velocity</strong>, which is essentially the rate of change of your distance.</p><p>In simpler terms, differentiation answers questions like:</p><ul><li>How fast is something changing at a specific moment?</li><li>What happens to one variable as another changes?</li></ul><p>Let’s take a classic example:</p><ul><li>If s(t) represents the distance traveled as a function of time t, then the velocity is the rate of change of s(t) with respect to t is the derivative of distance with respect to time. This can be written as</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/80/0*BF8zTU0qdyL7iIIt.png" /></figure><h4>The Limit Formula for Differentiation</h4><p>At its core, differentiation is defined using the concept of limits. The derivative of a function f(x) at a point x is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/0*5fCnWfZop3VYXr-h.png" /><figcaption>This formula measures the slope of the tangent line to the curve of f(x) at the point x</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zflQnw6ptfFw_vL6" /></figure><h4>Example: Differentiating an Algebraic Expression</h4><p>Let’s differentiate f(x) = x² using the limit formula:</p><ol><li>Substitute f(x+h) and f(x) into the formula:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/0*8jWGVl9tT4DERGWr.png" /></figure><ol><li>Expand (x + h)² and simplify:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/0*c2ivQwl5q3_lJ7-B.png" /></figure><ol><li>Factor out h:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/167/0*qXemveq4idABH6vs.png" /></figure><ol><li>Evaluate the limit as h→0:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/89/0*2BDSZ4vx9STV1yTc.png" /></figure><p>Thus, the derivative of x² is 2x.</p><h4>General Formula for Differentiation</h4><p>For a general function f(x)=c⋅x^n, where c and n are constants, the derivative is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/0*5jpkPmY5VW4X8oFM.png" /></figure><p>This is a foundational rule in calculus and simplifies the differentiation of polynomial functions.</p><h4>Differentiating Sine and Cosine Functions</h4><p>To derive the derivative of sin⁡(x), we use the limit definition. Start with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/0*NQTGhHt6KT4ahHHO.png" /></figure><p>Using the trigonometric identity, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/0*-6bvRy88ZHgue7CK.png" /></figure><p>Group terms and factor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*-7UQ4OTuWZpkN5AXMaCc7Q.png" /></figure><p>From known limits:</p><ul><li>sin⁡(h)/h → 1 as h→0,</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_v0sF7PJh5BqoILJ" /></figure><ul><li>(cos⁡(h)−1)/h → 0 as h → 0,</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*neHHukAcjUVdQbbJ" /></figure><p>We can conclude:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/153/0*Cm_x2lwcRv0cuJZ6.png" /></figure><p>Similarly, for cos⁡(x):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/0*mDOBsWq0TV6c2znT.png" /></figure><h4>Differentiating a^x and Defining Euler’s Number</h4><p>To differentiate f(x) = a^x, start with the limit definition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/0*75zqfJ7tK_i0iEig.png" /></figure><p>Simplify:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/0*4tFidRIRUt0X7E4M.png" /></figure><p>Factor out a^x:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/0*B1yf5saQFloGa0I6.png" /></figure><p>The value of the lim⁡ h → 0 (a^h−1)/h depends on a.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P22wZ94lHoDn3chG" /></figure><p>By analyzing the above plot, we can see that a specific base e (Euler’s number ~ 2.718), this limit equals 1. Thus, when a = e:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/84/0*lbmvK3jvvOIgUgds.png" /></figure><h4>What Is Euler’s Number?</h4><p>Euler’s number, denoted e, is a mathematical constant approximately equal to 2.718. It is the base of the natural logarithm and has the unique property that the function e^x is its own derivative. This property makes e fundamental in exponential growth, decay, and many natural processes.</p><h3>Unlocking the Power of the Taylor Series</h3><h4>What Is a Taylor Series?</h4><p>The Taylor series is a mathematical tool that allows us to approximate complex functions using infinite sums of simpler terms based on their derivatives. By expanding a function into its Taylor series, we can represent it as a polynomial, making it easier to analyze and compute. This approach is widely used in physics, engineering, computer science, and numerical methods.</p><p>The idea originates from the work of the mathematician Brook Taylor, who first described this series in the 18th century. It forms the foundation for approximating functions near a specific point, often zero, which is known as a Maclaurin series.</p><h4>The Idea Behind a Taylor Series Expansion</h4><p>Let’s represent a function f(x) as an infinite sum of terms of the form a + bx + cx² + dx³ + …, where the coefficients a, b, c, … are determined using derivatives of the function at a specific point.</p><h4>Example 1: Taylor Series for Sine</h4><p>Start by writing the function sin⁡(x)as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*0dwC324kFqMjG8ek2QdqLg.png" /></figure><ol><li><strong>Find the value of aa:</strong><br> Set x = 0:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/85/1*-O4ld9P54uhPSnw8L-mMfg.png" /></figure><p>Since sin(0) = 0, we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/45/0*LBwX2W1FabGuotcg.png" /></figure><ol><li><strong>Find the value of b:</strong><br> Take the derivative of sin⁡(x) and evaluate it at x = 0:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/131/0*Q8c05GJU7wGm9xfR.png" /></figure><p>At x = 0:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*CjHBqf5pgQHf9KspbJPH7Q.png" /></figure><p>Thus, b = 1.</p><ol><li><strong>Find the value of c:</strong><br> Take the second derivative and evaluate at x = 0:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/152/0*HKjqpN996yzKMRgK.png" /></figure><p>At x = 0:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/0*yBunU3-Q-0Vs5qd5.png" /></figure><p>Thus, c = 0.</p><ol><li><strong>Find the value of d:</strong><br> Take the third derivative and evaluate at x = 0:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/0*dps8sf3vw5VEOAi7.png" /></figure><p>At x = 0:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/0*XAlZbDA5MchwEnbe.png" /></figure><p>Thus, d = -1/3!</p><p>Repeating this process, the general Taylor series for sine is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/0*XCHcy5uZ3cDBHs_Y.png" /></figure><p><strong>Note: </strong>Here, we assume that x is in radians not in degrees.</p><h4>Example 2: Taylor Series for Cosine</h4><p>Start by writing cos⁡(x) as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/0*qyEhidtMApgxv1mk.png" /></figure><ol><li><strong>Find the value of aa:</strong><br> Set x = 0:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/87/0*JjyHFqv_tWS9gdQK.png" /></figure><p>Since cos(0) = 1, we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/45/0*Dk8FqgBDal8jwghM.png" /></figure><ol><li><strong>Find the value of b:</strong><br> Take the derivative and evaluate at x = 0:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/0*gAzDcibJhzfpZCt8.png" /></figure><p>At x = 0:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/0*GgoC8HdUNFEsx_5e.png" /></figure><p>Thus, b = 0.</p><ol><li><strong>Find the value of cc:</strong><br> Take the second derivative and evaluate at x = 0:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/156/0*S9xjEnS-8mkY5LcT.png" /></figure><p>At x = 0:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/0*VQR9UWDHHe4B_MeD.png" /></figure><p>Thus, c = -1/2!</p><p>Repeating this process, the general Taylor series for cosine is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/0*W8BpBRnkiZNugbg2.png" /></figure><p><strong>Note: </strong>Here, we assume that x is in radians not in degrees.</p><h4>Example 3: Taylor Series for Exponential Function</h4><p>Start by writing e^x as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/0*wfk1fAhGtVAgotep.png" /></figure><ol><li><strong>Find the value of aa:</strong><br> Set x = 0:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/53/0*t7zsQXa54HSWW0KR.png" /></figure><p>Since e⁰ = 1, we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/45/0*6bjyny3BE-ACekt7.png" /></figure><ol><li><strong>Find the value of b:</strong><br> Take the derivative and evaluate at x = 0:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/84/0*ZX5NPOaJCwneWpeO.png" /></figure><p>At x = 0:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/51/0*KFD4EisvNo6tMjYD.png" /></figure><p>Thus, b = 1.</p><ol><li><strong>Find the value of c:</strong><br> Take the second derivative and evaluate at x = 0:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/91/0*4aqnNCihUnkgiCY9.png" /></figure><p>At x = 0:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/51/0*dUiaAMSGq1VBHLm2.png" /></figure><p>Thus, c = 1/2!</p><p>Repeating this process, the general Taylor series for e^x is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/0*spVdXG0gNpjUXfLy.png" /></figure><p>The Taylor series is an incredibly powerful tool for approximating functions by polynomials. By using derivatives at a specific point, we can create these series for functions like sine, cosine, and the exponential function. These series are foundational in many fields of science and mathematics, making complex functions accessible and computable.</p><h3>Merging the Marvels: Connecting e^x, sin(x), and cos(x)</h3><h4>Revisiting the Taylor Series for the Three Functions</h4><p>Let’s start by writing down the Taylor series expansions for e^x, sin(x), and cos(x):</p><ol><li>Taylor series for the exponential function:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/0*aKX2-Mrh4J94BSyY.png" /></figure><ol><li>Taylor series for sine:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/0*PHb0jTQcSIl5knjB.png" /></figure><ol><li>Taylor series for cosine:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/0*dulVa5oQFLyNDzN3.png" /></figure><p>At first glance, you might notice some similarities between these series, particularly their use of alternating powers and factorial terms. But there are important differences.</p><h4>Understanding the Key Differences</h4><p>In the sine series, only the odd powers of x appear, and their coefficients alternate between positive and negative values. For instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/0*sNf2SsUUgV-l8rjD.png" /></figure><p>In the cosine series, only the even powers of xx appear, and their coefficients alternate as well. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/0*10ZkZag6AUcUGwmQ.png" /></figure><p>In contrast, the exponential series includes all powers of x without any alternation of signs.</p><p>This suggests that sine and cosine are each partial representations of the exponential series, capturing specific powers of xx. But how can we merge these two trigonometric functions into one unified form?</p><h4>Replacing x with ix: A Key Insight</h4><p>Let’s replace x with <em>i</em>x (where <em>i</em> is the imaginary unit) in the Taylor series for cosine and sine. For cosine, replacing x with <em>i</em>x gives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/0*FXzI42TX_EAhSWtC.png" /></figure><p>Since i² = -1, this simplifies to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/0*iUyaYCmu4S782lFr.png" /></figure><p>Notice that the alternating signs in the cosine series are now resolved. For sine, replacing x with <em>i</em>x gives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/0*8nbbe_eNIl-E48Rj.png" /></figure><p>Simplifying, this becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/0*ASq8QlgG1x-wfvkD.png" /></figure><p>Here, while the alternating signs are also resolved, the terms still include the factor <em>i</em>, which is not ideal for merging with cosine.</p><h4>Fixing the Issue by Multiplying sin⁡(ix) by i</h4><p>To resolve the issue with sin⁡(ix), we multiply it by <em>i</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/0*C9BXPUVN2ApxRgUm.png" /></figure><p>This simplifies to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/0*NFTAhc9Zjg98hj9N.png" /></figure><p>Now, we observe that i⋅sin⁡(ix) perfectly complements cos⁡(ix), as it captures the odd powers of x.</p><h3>Substituting x with ix in the Exponential Series</h3><p>Before merging the sine and cosine series, let’s first explore what happens when we substitute x with <em>i</em>x directly into the Taylor series expansion for the exponential function. The Taylor series for e^x is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/0*DmasoyN8H0DCJUOe.png" /></figure><p>Now, replace x with <em>i</em>x:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/0*CyZc_SRGycwt4ouV.png" /></figure><p>Simplify each term using i² = -1, i³ = -i, i⁴ = 1, and so on:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*Y9A_6bH7K9RqYcYn.png" /></figure><p>Grouping the terms, we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/0*z_Vr0aYXC-63L7Mj.png" /></figure><p>Notice something fascinating: the real part of this series matches the Taylor series for cosine, and the imaginary part matches the Taylor series for sine.</p><p>The real part is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/0*YGkKQQTM2R8EVQKE.png" /></figure><p>The imaginary part is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/0*KnR70nOOlJTtQ7dw.png" /></figure><p>Thus, substituting x with <em>i</em>x in the exponential series naturally separates into cosine and sine components.</p><h4>Merging the Two Series into One Unified Expression</h4><p>Finally, we combine cos⁡(ix) and i⋅sin⁡(ix) :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/0*Hjdn9hFKRA6i-_Bj.png" /></figure><p>This matches the Taylor series for the exponential function when x is replaced with <em>i</em>x. This beautiful relationship connects exponential, sine, and cosine functions into one elegant formula, known as Euler’s formula.</p><h4>The Significance of Euler’s Formula</h4><p>Euler’s formula is a cornerstone of mathematics, linking trigonometry and exponential functions in a profound way. It demonstrates how imaginary numbers are not just abstract concepts but essential components of the mathematical universe, enabling us to describe complex oscillatory behavior in fields like physics, engineering, and signal processing.</p><h3>The Beauty of Euler’s Identity</h3><h4>Deriving Euler’s Identity</h4><p>Euler’s identity is often celebrated as one of the most beautiful equations in mathematics. It is derived directly from Euler’s formula by substituting x = π:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/0*6urxdMWsQEwSctrm.png" /></figure><p>From trigonometry:</p><ul><li>cos⁡(π) = −1</li><li>sin⁡(π) = 0</li></ul><p>Thus:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/73/0*sKt1WausidkFkI6G.png" /></figure><p>Rearranging this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/92/0*uhH3FUTg1lff7gja.png" /></figure><p>This is Euler’s identity, a succinct equation that combines five of the most fundamental constants in mathematics: e, <em>i</em>, π, 1, and 0. It is a testament to the deep interconnection between seemingly unrelated branches of mathematics, such as algebra, geometry, and analysis.</p><h4>Historical Significance of Euler’s Identity</h4><p>Euler’s identity has played a pivotal role in mathematical discoveries and applications across various fields. Here are a few key examples:</p><ol><li><strong>Complex Analysis</strong>: Euler’s formula is the foundation for understanding complex exponential functions, which are used extensively in solving differential equations and studying analytic functions.</li><li><strong>Fourier Transform</strong>: The Fourier transform relies on Euler’s formula to represent sinusoidal signals as combinations of complex exponentials. This is a cornerstone in signal processing, telecommunications, and image compression.</li><li><strong>Quantum Mechanics</strong>: The Schrödinger equation and the concept of wave functions use Euler’s formula to describe quantum states and oscillatory behaviors in the microscopic world.</li><li><strong>Electrical Engineering</strong>: In alternating current (AC) circuit analysis, phasors are expressed as complex exponentials, simplifying calculations of voltage and current.</li><li><strong>Number Theory</strong>: Euler’s identity is closely tied to the study of modular arithmetic and the properties of prime numbers.</li></ol><h4>Other Applications of Euler’s Formula</h4><p>Beyond its historical significance, Euler’s formula and identity find applications in many practical and theoretical domains:</p><ol><li><strong>Rotations in Geometry</strong>: Complex exponentials are used to describe rotations in two-dimensional space, forming the basis for complex plane geometry.</li><li><strong>Fractals and Chaos Theory</strong>: Euler’s formula appears in iterative algorithms that generate fractals and study chaotic systems.</li><li><strong>Computer Graphics</strong>: Rotations and transformations in 3D space often use Euler’s formula for efficient computation.</li><li><strong>Wave Phenomena</strong>: Euler’s formula is crucial in studying wave interference, resonance, and harmonic motion.</li><li><strong>Control Systems</strong>: In control theory, transfer functions use Euler’s formula to describe system dynamics and stability.</li></ol><h4>Conclusion</h4><p>Euler’s identity is more than just an equation — it is a bridge between vastly different realms of mathematics and science. Its simplicity and elegance have inspired generations of mathematicians, scientists, and engineers, proving that profound truths often lie in the most compact expressions. Whether describing the quantum world, analyzing waves, or processing signals, Euler’s formula continues to be a beacon of mathematical beauty and utility.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a42805520dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI learns to Play Tetris Game: Building the Intelligence]]></title>
            <link>https://shashank-goyal-blogs.medium.com/ai-learns-to-play-tetris-game-building-the-intelligence-b6e1a7109ef6?source=rss-e85e3a6012ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6e1a7109ef6</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[neuroevolution]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tetris]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Shashank Goyal]]></dc:creator>
            <pubDate>Thu, 26 Dec 2024 03:41:21 GMT</pubDate>
            <atom:updated>2024-12-26T04:24:37.081Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*RVZL5SxFH8PNlsgEGjjYqg.gif" /></figure><p>This article is a continuation of the AI-based intelligence program that learns to play Tetris. In this article, we are going to focus on developing the core intelligence behind the AI Model. Please note that the general logic and solution from this project can be applied to other games and learning-based tasks as well.</p><p>The approach that we will be taking uses the Python <strong>“NEAT” </strong>module which stands for NeuroEvolution of Augmenting Topologies. In simpler terms, it is used to evolve artificial neural networks using Genetic Algorithms. If you want to understand the concept behind this in more detail, I recommend reading the <a href="https://nn.cs.utexas.edu/downloads/papers/stanley.cec02.pdf">Initial NEAT Paper</a> by Kenneth O. Stanley and Risto Miikkulainen. Additionally, you can also check out other papers that explore this concept and related topics <a href="http://www.cs.ucf.edu/~kstanley/#publications">here</a>.</p><p>This project has been blogged in two parts, you can find the previous part: AI learns to Play Tetris Game: Building the GUI — which describes the development of the GUI that will be used in the project, <a href="https://faun.pub/ai-learns-to-play-tetris-game-building-the-gui-38346e5984c8">here</a>.</p><p><strong>Part II — Building the Intelligence</strong></p><p>Before moving forward, if you are not comfortable with Python, Numpy, or PyGame, I recommend the following Youtube playlist and video -</p><ul><li><a href="https://www.youtube.com/playlist?list=PLi01XoE8jYohWFPpC17Z-wWhPOSuh8Er-">Python Programming Tutorials Playlist</a> by <a href="https://www.youtube.com/c/Socratica">Socratica</a>.</li><li><a href="https://youtu.be/QUT1VHiLmmI">Python Numpy Tutorial</a> by <a href="https://www.youtube.com/channel/UC8butISFwT-Wl7EV0hUK0BQ">freecodecamp.org</a></li><li><a href="https://youtu.be/FfWpgLFMI7w">Pygame Tutorial for Beginners</a> by <a href="https://www.youtube.com/channel/UC8butISFwT-Wl7EV0hUK0BQ">freecodecamp.org</a></li></ul><p>If you want to learn about genetic algorithms which will help understand the underlying concept behind NEAT, you can read my blogs on Genetic Algorithm <a href="https://medium.com/faun/genetic-algorithms-to-solve-the-zero-one-knapsack-problem-d38856beaa35">here</a>.</p><p>Additionally, you can check out the <a href="https://youtube.com/playlist?list=PLzMcBGfZo4-lwGZWXz5Qgta_YNX3_vLS2">“AI Plays Flappy Bird”</a> playlist by Tech with Tim, which also deploys the same technique used by this implementation. So without further ado, let’s start with the code ….</p><h4><strong>Tetris Params Class —</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fb86c68b17d6719fb8b7e1001889127/href">https://medium.com/media/9fb86c68b17d6719fb8b7e1001889127/href</a></iframe><p>The TetrisParams class is used to calculate the parameters that will be used for the evaluating state of the playing field. The metrics used to quantify the fitness of a playing field scenario are the following -</p><ul><li><strong>Column Heights and Bumpiness:</strong> The get_peaks method calculates the height of each column in the Tetris grid, essential for understanding the landscape the AI is working with. Bumpiness, measured by get_bumpiness, quantifying the irregularity between column heights, influences the AI’s decision to place pieces in a way that minimizes height variations.</li><li><strong>Hole Detection:</strong> Holes are spaces in the grid that are blocked from above and can significantly impact the game’s progress. The methods get_holes and get_total_holes compute the number and distribution of these gaps. Fewer holes mean a cleaner grid, which is preferable for achieving higher scores.</li><li><strong>Transition Metrics:</strong> Transitions are changes from filled to empty spaces or vice versa within the grid. Both get_row_transitions and get_col_transitions methods assess the smoothness of the grid’s filled areas. Smoother lines without abrupt transitions are better for completing rows and scoring.</li><li><strong>Well Analysis:</strong> Wells are deep vertical spaces that can trap pieces, analyzed using get_wells and get_max_wells. The AI aims to avoid creating deep wells as they are harder to fill and can lead to game-ending scenarios.</li><li><strong>Scoring Potential:</strong> Finally, get_num_lines_cleared looks at the immediate scoring potential by identifying completely filled rows ready to be cleared. This metric directly contributes to the game score, guiding the AI to place pieces strategically to maximize point gains.</li></ul><p>Each of these metrics feeds into a function that collectively determines the state’s “fitness” from an AI perspective. By optimizing these, the AI learns not just to play Tetris but to excel at it, leveraging genetic algorithms to evolve strategies that score higher with each game.</p><p>This advanced metric system is crucial for training the AI to evaluate and react to changing game conditions, ensuring that each move maximizes potential benefits while minimizing risks like creating holes or deep wells. Through continuous learning and adaptation, the AI becomes capable of handling Tetris challenges with increasing proficiency. These parameters can be explained using an example by Duc Anh Bui in his blog post. Please refer <a href="https://towardsdatascience.com/beating-the-world-record-in-tetris-gb-with-genetics-algorithm-6c0b2f5ace9b#:~:text=Using%20the%20matrix%20above%2C%20we%20can%20define%20a%20number%20of%20features%20as%20seen%20in%20%5B2%5D%3A">here</a> for the example.</p><p><strong>Translating Tetris Blocks into Numpy Arrays -</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/402f96433d7907533b6245c07b3057b7/href">https://medium.com/media/402f96433d7907533b6245c07b3057b7/href</a></iframe><p>In AI development for games like Tetris, it’s crucial to represent game elements in a way that algorithms can efficiently process. The get_numpy_shape function is an essential part of this process, translating Tetris block shapes into numpy arrays which facilitate the computation of game logic. How It Works -</p><ul><li><strong>Input Representation:</strong> The function takes a formatted_shape list that includes coordinates for each block of a Tetris piece. These coordinates mark where blocks are positioned relative to a grid.</li><li><strong>Matrix Creation:</strong> It calculates the necessary size of a numpy matrix based on the maximum extent of the coordinates. This matrix starts filled with zeros, representing an empty grid.</li><li><strong>Mapping Blocks to Matrix:</strong> The function iterates over the list of block coordinates, setting the corresponding matrix cells to 1, which signifies that a block occupies that position.</li></ul><p><strong>Example:</strong> Consider a Tetris T-shape; this function would map its three-dimensional layout into a two-dimensional array, where each ‘1’ indicates the presence of a block and ‘0’ represents empty space.</p><p>This matrix is not just a visual representation but a functional one that allows the AI’s underlying algorithms to quickly assess and manipulate the game state, leading to more effective decision-making processes in gameplay.</p><h4>Generating Rotations for Tetrominoes -</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25a1548a0d6b8c88e5cc54bbb4b180d4/href">https://medium.com/media/25a1548a0d6b8c88e5cc54bbb4b180d4/href</a></iframe><p>The AI relies on exploring all possible orientations of a given Tetris piece to make optimal decisions. This is accomplished through the get_piece_rotations function, which generates all potential rotations for a Tetromino and represents each rotation as a numpy array.</p><h4>How it Works:</h4><ol><li><strong>Iterating Rotations:</strong><br>For each rotation of a Tetromino shape, the function calculates its numpy representation using the get_numpy_shape function.</li><li><strong>Storing Orientations:</strong><br>Each numpy array is appended to a list of possible rotations. The orientation index is updated using modular arithmetic to ensure circular rotation logic.</li><li><strong>Output:</strong><br>The function returns a list of numpy arrays, each representing a distinct rotation of the Tetromino.</li></ol><h4>Significance in Gameplay:</h4><p>By precomputing all valid rotations, the AI can evaluate each possible placement scenario efficiently. This ensures that the agent considers not only the current orientation of the piece but also its potential impact after rotation.</p><h4>Evaluating Gameplay Scenarios -</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fe371be889370eafac311571476a520/href">https://medium.com/media/8fe371be889370eafac311571476a520/href</a></iframe><p>Once Tetromino rotations are generated, the AI must evaluate potential placements to decide the most strategic move. This is handled by the generate_piece_possibilities function.</p><h4>Key Steps:</h4><ol><li><strong>Matrix Copying:</strong><br>A copy of the current game grid (init_matrix) is used for simulating each possible placement.</li><li><strong>Placement Simulation:</strong><br>For each rotation and column position, the function drops the Tetromino until it either lands on the bottom or collides with another piece.</li><li><strong>Metric Evaluation:</strong><br>The resulting grid is evaluated using the TetrisParams class. Metrics like row transitions, holes, and scoring potential are calculated to determine the grid&#39;s fitness.</li><li><strong>Handling Next Piece:</strong><br>If the function is called with next_piece_rotations, it recursively evaluates the impact of the current piece on the fitness of the next piece&#39;s placement.</li><li><strong>Output:</strong><br>The function returns a list of possible moves, each described by:</li></ol><ul><li>Rotation index</li><li>Column position</li><li>Fitness of the current piece</li><li>Maximum future fitness achievable with the next piece</li></ul><h4>Optimization Goal:</h4><p>By scoring each potential placement, the AI identifies the move that maximizes both immediate and future benefits, ensuring robust decision-making in dynamic gameplay scenarios.</p><h4>Sorting and Selecting the Best Move -</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd017fa1daa4f63aec1286828777d4ba/href">https://medium.com/media/cd017fa1daa4f63aec1286828777d4ba/href</a></iframe><p>The AI leverages the try_possible_moves function to finalize the best move by sorting potential placements. Here&#39;s how this process unfolds:</p><ol><li><strong>Input Preparation:</strong><br>The function takes the current game grid and generates numpy representations for the current and next pieces.</li><li><strong>Sorting Criteria:</strong><br>Possible moves are sorted based on:<br>• Total fitness (sum of current and next piece fitness)<br>• Minimal horizontal shifts<br>• Minimal rotations<br>This ensures the AI prioritizes moves that yield high scores with minimal movement, simulating a human-like strategy.</li><li><strong>Output:<br></strong>The sorted list of moves enables the AI to select the most advantageous placement for the current piece.</li></ol><h4>Strategic Advantage:</h4><p>By considering future implications and minimizing unnecessary moves, this approach enables the AI to adapt to dynamic game states effectively.</p><h4>Training the AI with NEAT -</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82fecc2e97900b1941fa9edbc61eac35/href">https://medium.com/media/82fecc2e97900b1941fa9edbc61eac35/href</a></iframe><p>The <strong>main_game</strong> function is the core of the training process, where the AI learns to play Tetris using <strong>NEAT (NeuroEvolution of Augmenting Topologies)</strong>. This function evaluates the fitness of each neural network (genome), simulates gameplay, and guides the evolutionary process. Here’s how it works:</p><h4>1. Function Overview</h4><p>The <strong>main_game</strong> function accepts:</p><ul><li><strong>genomes</strong>: A list of tuples, where each tuple contains a genome ID and the corresponding genome.</li><li><strong>config</strong>: A configuration object containing NEAT parameters such as mutation rates, population size, and activation functions.</li></ul><p>The primary goal of this function is to evaluate each genome’s fitness by simulating Tetris gameplay and guide the NEAT algorithm to evolve better-performing networks.</p><h4>2. Initialization</h4><ul><li><strong>Generation Tracking</strong>:<br>The global variable gen_index is incremented to track the current generation of the AI.</li><li><strong>Genome-Specific Data Structures</strong>:<br>Three lists are initialized:<br>• <strong>gen</strong>: Stores the genomes being evaluated.<br>• <strong>tetrises</strong>: Holds a Tetris game instance for each genome.<br>• <strong>models</strong>: Contains neural networks created from the genomes using the NEAT FeedForwardNetwork class.</li><li><strong>Genome Setup</strong>:<br>For each genome:<br>• A corresponding Tetris game instance is created.<br>• The genome’s fitness is initialized to 0.</li></ul><h4>3. Gameplay Simulation</h4><ul><li><strong>Iterative Gameplay</strong>:<br>The function runs until all genomes have been evaluated, i.e., until every Tetris game instance ends.</li><li><strong>Move Evaluation and Execution</strong>:<br>For each game instance:<br>• The <strong>try_possible_moves</strong> function evaluates all possible moves for the current piece. This function returns a sorted list of moves based on their fitness.<br>• The best move (rotation, position, and fitness) is selected, and the following steps are executed:<br>1. Rotate the piece until it matches the desired orientation.<br>2. Move the piece left or right to align it with the target column.<br>3. Drop the piece to its lowest possible position.</li><li><strong>Game Over Handling</strong>:<br>If no valid moves are left, the game ends for that genome.</li></ul><h4>4. Fitness Evaluation</h4><ul><li><strong>Scoring as Fitness</strong>:<br>The score achieved during gameplay is assigned as the genome’s fitness value.</li><li><strong>Updating the Best Model</strong>:<br>If a genome achieves a higher score than the current max_fitness:<br>• The max_fitness is updated.<br>• The genome is saved as the best-performing model using the pickle module.</li></ul><h4>5. Genome Removal</h4><p>When a Tetris game ends:</p><ul><li>The corresponding genome, Tetris instance, and neural network are removed from their respective lists.</li><li>A debug message logs the genome’s ID, its fitness, and the remaining number of genomes in the current generation.</li></ul><h4>6. Evolutionary Advantage</h4><p>This iterative process:</p><ol><li><strong>Rewards High Performance</strong>:<br>Genomes with higher fitness are more likely to pass their traits to the next generation.</li><li><strong>Refines Neural Networks</strong>:<br>Each generation adapts and improves, reducing errors and enhancing decision-making capabilities.</li><li><strong>Encourages Innovation</strong>:<br>NEAT introduces mutations and crossovers to explore new strategies, ensuring the AI evolves dynamically over time.</li></ol><h4>7. Real-Time Learning</h4><p>By simulating gameplay for each genome and evaluating fitness based on actual performance, this training loop ensures:</p><ul><li>The AI learns strategies specific to Tetris.</li><li>The evolutionary process continuously pushes the AI toward optimal gameplay.</li></ul><p>In essence, the <strong>main_game</strong> function serves as the driving force behind training, enabling the AI to evolve and excel at Tetris through iterative learning and adaptation.</p><h3>Running the Genetic Algorithm</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/781953bb65acfb383276251057298a97/href">https://medium.com/media/781953bb65acfb383276251057298a97/href</a></iframe><p>The <strong>run</strong> method serves as the entry point for the NEAT-based training process, orchestrating the evolutionary learning loop. This function handles the initialization of the NEAT population, loading from checkpoints, and managing the reporting and checkpointing mechanisms during the evolution process.</p><h4>1. Configuration Initialization</h4><p>The method begins by extracting details from the provided config_file:<br><strong>neat.config.Config</strong>: Loads configuration parameters for genome structures, reproduction mechanisms, species set definitions, and stagnation policies.<br>This step ensures that the NEAT algorithm follows the specified evolutionary rules.</p><h4>2. Handling Checkpoints</h4><p>Checkpoints are used to save the progress of the evolution process, allowing it to resume from the last saved state in case of interruptions:</p><ul><li><strong>Directory Check</strong>:<br>• If the checkpoints/ directory is empty, a new population is created using neat.Population(config).<br>• If checkpoints exist, the function identifies the most recent one by sorting checkpoint files numerically.</li><li><strong>Restoring State</strong>:<br>• The latest checkpoint is loaded using neat.Checkpointer.restore_checkpoint.<br>• A message is printed to confirm the loaded checkpoint, ensuring the user knows the starting point of the resumed training process.</li></ul><h4>3. Reporting and Statistics</h4><p>To monitor the training process, NEAT provides built-in reporters:</p><ul><li><strong>neat.StdOutReporter</strong>: Outputs key statistics such as the best genome&#39;s fitness and population diversity during each generation.</li><li><strong>neat.StatisticsReporter</strong>: Tracks and aggregates fitness data across generations, enabling analysis of performance trends.</li><li><strong>neat.Checkpointer</strong>: Automatically saves the state of the evolution process at specified intervals:<br>• <strong>generation_interval</strong>: Saves progress every generation.<br>• <strong>time_interval_seconds</strong>: Saves progress every 1200 seconds (20 minutes).</li></ul><h4>4. Running the Evolution</h4><p>The <strong>pop.run()</strong> method executes the training loop by repeatedly calling the main_game function:</p><ul><li>The argument 20 specifies the number of generations to evolve.</li><li>In each generation, genomes are evaluated, and the population is updated based on their fitness.</li></ul><h4>5. Saving the Best Genome</h4><p>Once the evolution process completes:</p><ul><li>The best-performing genome, referred to as the “winner,” is displayed using print(&#39;\n\nBest genome: {!s}&#39;.format(winner)).</li><li>This genome is serialized and saved to a file named winner.pickle using the pickle module. This allows future testing or usage of the trained model.</li></ul><h3>Significance of Checkpoints</h3><p>Checkpoints play a vital role in long-running evolutionary processes:</p><ul><li><strong>Resilience</strong>: Protects against interruptions, ensuring no progress is lost during extended training sessions.</li><li><strong>Experimentation</strong>: Allows users to resume or analyze training from specific points without restarting from scratch.</li><li><strong>Efficiency</strong>: Saves computation time, especially when fine-tuning hyperparameters or conducting multiple runs.</li></ul><p>The <strong>run</strong> function is the backbone of the NEAT training pipeline, ensuring seamless management of the evolutionary process. It integrates population initialization, checkpointing, progress reporting, and result saving into a streamlined workflow, allowing the AI to iteratively learn and optimize its gameplay strategies in Tetris.</p><h4>Loading Configuration and Running Training -</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1ed172d2d7c59487e8726e19f5dd05d/href">https://medium.com/media/b1ed172d2d7c59487e8726e19f5dd05d/href</a></iframe><p>This block ensures the script executes the training process only when run directly, not when imported as a module. It sets up the path to the NEAT configuration file and calls the run method to start the genetic algorithm-based training.</p><h4>Summary of Configuration Parameters</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff0125ce35c2315b9f03c48343343a92/href">https://medium.com/media/ff0125ce35c2315b9f03c48343343a92/href</a></iframe><p>Each parameter in the NEAT configuration governs a specific aspect of the evolutionary process, from network initialization and mutation to species preservation and reproduction. Together, they ensure a balanced approach to evolving neural networks capable of solving complex tasks like Tetris.</p><h4>[NEAT]</h4><ul><li><strong>fitness_criterion</strong>: Determines how fitness is evaluated. The max option selects the genome with the highest fitness as the representative for a species.</li><li><strong>fitness_threshold</strong>: The minimum fitness value a genome must achieve for the evolution process to terminate successfully.</li><li><strong>pop_size</strong>: The number of genomes in the population, which determines the diversity and computational cost of the evolution.</li><li><strong>reset_on_extinction</strong>: If True, the population resets when all species go extinct. If False, the evolution halts on extinction.</li></ul><h4>[DefaultGenome]</h4><h4>Node Activation Options</h4><ul><li><strong>activation_default</strong>: The default activation function for nodes, such as identity (no transformation), relu, or sigmoid.</li><li><strong>activation_mutate_rate</strong>: The probability of mutating a node’s activation function.</li><li><strong>activation_options</strong>: A list of activation functions available for mutation.</li></ul><h4>Node Aggregation Options</h4><ul><li><strong>aggregation_default</strong>: The default aggregation function, such as sum or product, which combines inputs at a node.</li><li><strong>aggregation_mutate_rate</strong>: The probability of mutating the aggregation function.</li><li><strong>aggregation_options</strong>: A list of aggregation functions available for mutation.</li></ul><h4>Node Bias Options</h4><ul><li><strong>bias_init_mean</strong>: The initial mean value for node biases, influencing node outputs before weights are applied.</li><li><strong>bias_init_stdev</strong>: The standard deviation for initializing biases, controlling variance.</li><li><strong>bias_init_type</strong>: The distribution type for initializing biases, such as uniform or gaussian.</li><li><strong>bias_max_value</strong>: The maximum allowable bias value.</li><li><strong>bias_min_value</strong>: The minimum allowable bias value.</li><li><strong>bias_mutate_power</strong>: The step size for bias mutations.</li><li><strong>bias_mutate_rate</strong>: The probability of a bias mutating during evolution.</li><li><strong>bias_replace_rate</strong>: The probability of replacing a bias with a new random value.</li></ul><h4>Genome Compatibility Options</h4><ul><li><strong>compatibility_disjoint_coefficient</strong>: Weight for disjoint genes when calculating genome compatibility (genes present in one genome but not the other).</li><li><strong>compatibility_weight_coefficient</strong>: Weight for the average weight differences of matching genes when calculating compatibility.</li></ul><h4>Connection Add/Remove Rates</h4><ul><li><strong>conn_add_prob</strong>: The probability of adding a new connection between two unconnected nodes.</li><li><strong>conn_delete_prob</strong>: The probability of removing an existing connection.</li></ul><h4>Connection Enable Options</h4><ul><li><strong>enabled_default</strong>: Whether new connections are enabled by default.</li><li><strong>enabled_mutate_rate</strong>: The probability of toggling a connection between enabled and disabled.</li><li><strong>feed_forward</strong>: If True, enforces feedforward networks with no recurrent connections.</li><li><strong>initial_connection</strong>: Determines how nodes are initially connected, e.g., full_direct (fully connected).</li></ul><h4>Node Add/Remove Rates</h4><ul><li><strong>node_add_prob</strong>: The probability of adding a new node by splitting an existing connection.</li><li><strong>node_delete_prob</strong>: The probability of removing a node and its associated connections.</li></ul><h4>Network Parameters</h4><ul><li><strong>num_hidden</strong>: The initial number of hidden nodes in the genome.</li><li><strong>num_inputs</strong>: The number of input nodes in the genome.</li><li><strong>num_outputs</strong>: The number of output nodes in the genome.</li></ul><h4>Node Response Options</h4><ul><li><strong>response_init_mean</strong>: The initial mean value for node responses, which modulate inputs to nodes.</li><li><strong>response_init_stdev</strong>: The standard deviation for initializing node responses.</li><li><strong>response_max_value</strong>: The maximum allowable response value.</li><li><strong>response_min_value</strong>: The minimum allowable response value.</li><li><strong>response_mutate_power</strong>: The step size for mutating node responses.</li><li><strong>response_mutate_rate</strong>: The probability of a response mutating.</li><li><strong>response_replace_rate</strong>: The probability of replacing a response with a new random value.</li></ul><h4>Connection Weight Options</h4><ul><li><strong>weight_init_mean</strong>: The initial mean value for connection weights.</li><li><strong>weight_init_stdev</strong>: The standard deviation for initializing weights.</li><li><strong>weight_max_value</strong>: The maximum allowable weight.</li><li><strong>weight_min_value</strong>: The minimum allowable weight.</li><li><strong>weight_mutate_power</strong>: The step size for mutating connection weights.</li><li><strong>weight_mutate_rate</strong>: The probability of a weight mutating.</li><li><strong>weight_replace_rate</strong>: The probability of replacing a weight with a new random value.</li></ul><h4>[DefaultSpeciesSet]</h4><ul><li><strong>compatibility_threshold</strong>: The maximum compatibility distance for genomes to be grouped into the same species. A lower threshold leads to more species and vice versa.</li></ul><h4>[DefaultStagnation]</h4><ul><li><strong>species_fitness_func</strong>: Defines how the fitness of a species is determined, such as max or mean.</li><li><strong>max_stagnation</strong>: The number of generations a species can persist without improving before being removed.</li><li><strong>species_elitism</strong>: The number of top-performing species guaranteed to survive each generation.</li></ul><h4>[DefaultReproduction]</h4><ul><li><strong>elitism</strong>: The number of top-performing genomes guaranteed to survive in each species.</li><li><strong>survival_threshold</strong>: The proportion of genomes in each species allowed to reproduce, based on fitness.</li><li><strong>min_species_size</strong>: The minimum number of genomes required for a species to exist.</li></ul><h4>Testing the Trained Model -</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1b5c2504bdfeee9e0aec7cd69cbbb32/href">https://medium.com/media/e1b5c2504bdfeee9e0aec7cd69cbbb32/href</a></iframe><p>This script tests the <strong>trained Tetris AI</strong> using the best-performing genome saved during the training process. It loads the trained model, simulates gameplay, and visualizes the AI’s decision-making.</p><h4>1. Imports and Initialization</h4><ul><li><strong>Standard Libraries</strong>:<br>• os and pickle handle file management for loading the trained model.<br>•time.sleep adds delays for visualizing each AI action clearly.</li><li><strong>NEAT Library</strong>: Handles loading the genome and creating the neural network from it.</li><li><strong>PyGame</strong>: Used for rendering the Tetris game interface.</li><li><strong>Game-Specific Modules</strong>:<br>• Tetris: The primary game logic class.<br>• try_possible_moves: Utility function to evaluate all potential moves and select the most optimal one.</li></ul><p>The script also initializes the PyGame environment, sets the window’s title and icon, and prepares for visual feedback.</p><h4>2. Loading the Trained Genome</h4><ul><li><strong>Model Loading</strong>:<br>• The saved genome (winner.pickle) from the training phase is loaded using pickle.load.<br>• This genome represents the best-performing neural network that emerged from the evolutionary process.</li><li><strong>Configuration Setup</strong>: The NEAT configuration file (config.txt) is read, enabling the genome to be recreated with the same parameters used during training.</li><li><strong>Neural Network Creation</strong>: The neural network is instantiated using neat.nn.FeedForwardNetwork.create, allowing it to make decisions during gameplay.</li></ul><h4>3. Gameplay Simulation</h4><p>The main function simulates Tetris gameplay with the trained AI:</p><ul><li><strong>Game Instance</strong>: A new Tetris instance is created, serving as the playing field.</li><li><strong>Game Loop</strong>: Continues until the game ends or the user closes the window.</li><li><strong>Event Handling</strong>: Monitors PyGame events, allowing the user to terminate the simulation by closing the window or pressing the escape key.</li></ul><h4>4. Decision-Making</h4><ul><li><strong>Evaluating Moves</strong>: The AI evaluates possible moves for the current piece using the try_possible_moves function. This function considers:<br>1. Rotations<br>2. Horizontal shifts<br>3. Fitness of each placement</li><li><strong>Optimal Move Execution</strong>: The AI executes the best move:<br>• <strong>Rotation</strong>: Rotates the piece until it matches the optimal orientation.<br>• <strong>Horizontal Movement</strong>: Shifts the piece left or right to align with the target column.<br>• <strong>Drop</strong>: Moves the piece to its lowest possible position in the column.</li></ul><h4>5. Visualization</h4><ul><li><strong>Sleep Delays</strong>: Short delays using sleep(0.1) are added after each action (rotation, shift, drop) to make the AI’s gameplay visually comprehensible.</li><li><strong>Rendering</strong>: The game screen updates in real-time, showing the AI’s decisions as it plays.</li></ul><h4>6. Game Termination</h4><ul><li>If the AI determines there are no valid moves left, the game ends:</li><li>The PyGame display is closed.</li><li>The script terminates gracefully.</li></ul><h4>Significance</h4><p>This script allows users to observe the trained AI in action:</p><ul><li>Demonstrates the AI’s ability to make strategic decisions based on its training.</li><li>Provides insights into the AI’s gameplay mechanics through visual feedback.</li><li>Validates the effectiveness of the evolutionary training process.</li></ul><p>This end-to-end testing ensures that the trained AI performs as expected and highlights its decision-making capabilities in a dynamic environment like Tetris.</p><h3>Conclusion</h3><p>The journey of building an AI that learns to play Tetris demonstrates the power and versatility of NeuroEvolution of Augmenting Topologies (NEAT). By combining evolutionary algorithms with neural networks, we have crafted an intelligent agent capable of adapting to dynamic game environments and making human-like strategic decisions.</p><p>From creating a robust GUI to designing the AI’s intelligence using metrics like fitness evaluation, Tetromino rotations, and gameplay scenario analysis, every step highlights the potential of AI to solve complex problems creatively. The NEAT algorithm’s evolutionary principles — mutation, crossover, and species differentiation — enable continuous learning and optimization, showcasing how AI can improve iteratively over generations.</p><p>This project not only achieves an AI that excels at Tetris but also serves as a template for tackling other learning-based tasks. Whether you’re a researcher exploring AI concepts or a developer building gaming applications, the principles and methods outlined here provide a foundation for innovation. The integration of visualization, decision-making, and real-time testing ensures a holistic understanding of AI’s capabilities in gameplay.</p><p>As we conclude this blog, the success of this AI-based Tetris player underscores the boundless opportunities in combining creativity with cutting-edge algorithms. The methodologies used here pave the way for future exploration, inspiring new applications in AI gaming, robotics, and beyond.</p><p><em>You can find the complete python implementation </em><a href="https://github.com/shashank3199/Tetrominoes-NEAT_AI"><em>here</em></a><em>. If you found this article helpful, please follow me on </em><a href="https://shashank-goyal-blogs.medium.com/"><em>Medium</em></a><em> and </em><a href="https://github.com/shashank3199/"><em>GitHub</em></a><em> and star the Project Repository.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6e1a7109ef6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ROS2 Humble GUI-Docker Container: A Step-by-Step Guide]]></title>
            <link>https://faun.pub/ros2-humble-gui-docker-container-a-step-by-step-guide-c541b73fe141?source=rss-e85e3a6012ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/c541b73fe141</guid>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[ros2]]></category>
            <category><![CDATA[dockergui]]></category>
            <category><![CDATA[simulation]]></category>
            <dc:creator><![CDATA[Shashank Goyal]]></dc:creator>
            <pubDate>Sat, 19 Oct 2024 15:26:27 GMT</pubDate>
            <atom:updated>2025-01-31T12:42:23.361Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*96vMlmM4lFEzTPV4" /></figure><p>Developing with <a href="https://docs.ros.org/en/humble/index.html">ROS2 (Robot Operating System 2)</a> can often be simplified by using Docker to create an isolated and reproducible environment. By using <a href="https://docs.docker.com/engine/install/">Docker</a>, you can avoid version conflicts, ensure consistency across machines, and facilitate easy collaboration. With Docker, the development and deployment processes become much more streamlined, especially when working with complex robotic software like ROS2, which requires precise versioning and specific dependencies. In this blog post, we will go through the process of creating a custom ROS2 Docker container step-by-step, using a set of files that define the entire setup.</p><p>ROS2 is a powerful framework for developing robotic systems, but it comes with numerous dependencies and a steep setup curve. This complexity makes Docker an excellent choice for managing ROS2 environments. Using Docker ensures that everyone on your development team is running the same configuration, which reduces debugging time and avoids unexpected behaviors that can arise due to environment discrepancies. By the end of this guide, you will have a robust and repeatable ROS2 development environment that you can easily share and reuse.</p><h3>Prerequisites</h3><p>Before we dive into the setup, make sure you have Docker installed on your system. You can follow the installation guide on Docker’s official website for your respective OS. For Ubuntu users, follow these steps to install Docker:</p><ol><li><strong>Update existing package list</strong>: Run the following command to update your system’s package list:</li></ol><pre>sudo apt update</pre><p><strong>2. Install prerequisites</strong>: Install the necessary prerequisites to allow apt to use a repository over HTTPS:</p><pre>sudo apt install -y apt-transport-https ca-certificates curl software-properties-common</pre><p>3. <strong>Add Docker’s official GPG key:</strong> Run the command below to add Docker’s official GPG key:</p><pre>curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg — dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg</pre><p>4. <strong>Set up the stable repository:</strong> Add the Docker apt repository to your sources list:</p><pre>echo “deb [arch=$(dpkg — print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable” | sudo tee /etc/apt/sources.list.d/docker.list &gt; /dev/null</pre><p>5. <strong>Update package list again:</strong> Run the update command again to include the Docker repository:</p><pre>sudo apt update</pre><p>6. <strong>Install Docker:</strong> Install Docker using the following command:</p><pre>sudo apt install -y docker-ce</pre><p>If you want to use Docker without needing sudo privileges, you can follow these steps after installing Docker:</p><p>1. <strong>Create Docker Group:</strong> Create a Docker group to manage access. Run:</p><pre>sudo groupadd docker</pre><p>3. <strong>Add User to Docker Group:</strong> Add your user to the Docker group to avoid using `sudo` with Docker commands. Replace `&lt;username&gt;` with your actual username:</p><pre>sudo usermod -aG docker &lt;username&gt;</pre><p>4. <strong>Restart:</strong> Log out and back in, or restart your system to apply the group changes.</p><p>5. <strong>Test Docker:</strong> Verify that you can run Docker commands without `sudo` by running:</p><pre>docker run hello-world</pre><p>It’s also recommended to have some familiarity with basic Docker commands, as this will make it easier to follow along. Having a fundamental understanding of ROS2 concepts will also be helpful but is not strictly necessary.</p><h3>Breakdown of Docker Configuration Files</h3><p>To create a custom ROS2 Docker container, we will use the following files, each serving a specific purpose in the Docker-based development environment setup:</p><ul><li><strong>Dockerfile</strong>: Defines the Docker image, including the base image, installed packages, and environment configurations.</li><li><strong>entrypoint.sh</strong>: Sets up the environment inside the container when it starts, ensuring ROS2 is ready for use.</li><li><strong>docker_build.sh</strong>: A script that automates the Docker image build process.</li><li><strong>docker_run.sh</strong>: A script to run the Docker container with the appropriate settings.</li><li><strong>.bashrc</strong>: Customizes the bash environment inside the container, making it user-friendly for development.</li></ul><p>Each of these files plays a crucial role in building and managing your ROS2 Docker environment. Let’s go through each one in detail.</p><h3>Dockerfile</h3><p>The Dockerfile is the blueprint for our Docker image. It defines the base image, installs the necessary dependencies, and configures the environment. Below is a breakdown of the main components of the Dockerfile:</p><ol><li><strong>Base Image:</strong> We start by using the official ROS2 Humble base imageosrf/ros:humble-desktop-full. This base image includes all the essential ROS2 components for development and is a great starting point for our custom container. By using this base image, we can ensure compatibility with other ROS2 tools and libraries, making it easier to integrate various ROS2 packages and extensions. This also saves time since the base image already includes many of the necessary ROS2 dependencies.</li><li><strong>Set Default Username:</strong> We use an argument to allow customization of the username for the non-root user. By setting this argument, you can easily customize the non-root user name when building the Docker image. This feature is particularly useful when multiple developers are working on the same project, allowing each developer to create a container with their preferred username. It also helps when deploying the container on different systems, as you can match the container user to the local system user for better integration. The user also has superuser privileges via sudo without requiring a password, making it easier to manage system-level tasks during development.</li><li><strong>Install Additional Tools:</strong> The Dockerfile installs some basic development tools like git, wget, curl, and python3-pip are installed. These tools are useful for developing and managing ROS2 packages, as well as accessing repositories and installing additional dependencies. git is essential for version control, allowing you to clone and manage code repositories. wget and curl are useful for downloading files and interacting with web APIs. python3-pip is used to install Python packages, which are often needed for ROS2 development. software-properties-common helps manage software repositories, making it easier to add new sources for package installation. Finally, ros-dev-tools provides additional utilities that enhance the ROS2 development experience.</li><li><strong>Install Python Packages</strong> Python packages are installed using pip to support ROS2 development: These packages are essential for building ROS2 workspaces using colcon. setuptools is a package development tool that simplifies the process of packaging and distributing Python code. colcon is the build tool used for ROS2, and colcon-common-extensions adds useful features and plugins to colcon, making it easier to build and manage complex workspaces. By installing these packages, we ensure that our container is fully equipped to handle ROS2 package builds, allowing developers to easily compile and run their ROS2 nodes.</li><li><strong>Install ROS2 Packages</strong> The Dockerfile includes installation of key ROS2 packages, such as ros-humble-desktop, ros-humble-moveit*, and others: These packages are essential for robotic development, providing control tools, simulation capabilities, and visualization tools. ros-humble-desktop includes the core ROS2 components along with visualization tools like Rviz, which are crucial for developing and debugging robotic systems. ros-humble-control* and ros-humble-moveit* provide advanced capabilities for controlling robotic arms and other hardware, enabling motion planning and manipulation tasks. ignition-fortress is a powerful simulation tool that allows developers to create realistic environments for testing their robotic applications. By installing these packages, we create a versatile environment capable of handling a wide range of robotic development tasks.</li><li><strong>Create Non-Root User</strong> For security purposes, the Docker container should not run as the root user. Therefore, we create a non-root user: This non-root user will be used for all operations inside the container, reducing potential security risks. Running as a non-root user prevents accidental system modifications and minimizes the impact of any security vulnerabilities that might be exploited within the container. By using the useradd command, we create a new user with a home directory and bash as the default shell. We also add an entry in the sudoers file to allow the user to execute commands with superuser privileges without requiring a password. This is particularly useful for development tasks that require elevated privileges, such as installing new software or modifying system settings.</li><li><strong>Setup User Environment</strong> We copy a custom .bashrc file into the container to customize the shell environment: This .bashrc file sets up useful aliases and sources the necessary ROS2 setup files to make the development experience smoother. The .bashrc file is executed whenever a new terminal session is started, allowing us to define environment variables, aliases, and functions that enhance productivity. For example, we can add aliases for commonly used commands like colcon build or ros2 launch, reducing the amount of typing required. We also source the ROS2 setup files, ensuring that all necessary environment variables are set up correctly for ROS2 development. By customizing the .bashrc file, we create a more efficient and user-friendly development environment.</li><li><strong>Entrypoint Script</strong> We use an entrypoint script to ensure the ROS2 environment is properly initialized every time the container starts: The entrypoint.sh script will source the ROS2 setup files and execute any provided command, making it easy to start developing immediately after launching the container. The ENTRYPOINT instruction in the Dockerfile specifies the script that will be executed whenever the container starts. This ensures that the ROS2 environment is always properly set up, regardless of how the container is run. The CMD instruction provides a default command (bash) to be executed if no other command is specified. By using an entrypoint script, we can guarantee that the container is always in a ready-to-use state, allowing developers to focus on writing and testing their code without worrying about environment setup.</li></ol><h4>Full Dockerfile</h4><pre>FROM osrf/ros:humble-desktop-full<br><br># Set environment variables<br>ENV DEBIAN_FRONTEND=noninteractive<br>ENV TZ=UTC<br><br># Install dependencies and tools<br>RUN apt-get update &amp;&amp; apt-get install -y \<br>    git wget curl python3-pip software-properties-common ros-dev-tools \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*<br><br># Install Python packages<br>RUN pip3 install --no-cache-dir setuptools==58.2.0 colcon-common-extensions<br><br># Add Gazebo repository<br>RUN wget https://packages.osrfoundation.org/gazebo.gpg -O /usr/share/keyrings/pkgs-osrf-archive-keyring.gpg \<br>    &amp;&amp; echo &quot;deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/pkgs-osrf-archive-keyring.gpg] http://packages.osrfoundation.org/gazebo/ubuntu-stable $(lsb_release -cs) main&quot; | tee /etc/apt/sources.list.d/gazebo-stable.list &gt; /dev/null<br><br># Install ROS2 packages<br>RUN apt-get update &amp;&amp; apt-get install -y \<br>    ros-humble-desktop \<br>    ros-humble-control* \<br>    ros-humble-ros2-control* \<br>    ros-humble-moveit* \<br>    ros-humble-ros-ign* \<br>    ros-humble-joint-state-publisher-gui \<br>    ros-humble-kinematics-interface-kdl \<br>    ros-humble-rqt-joint-trajectory-controller \<br>    ~nros-humble-rqt* \<br>    ignition-fortress \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*<br><br>RUN apt-get update &amp;&amp; apt-get upgrade -y<br><br># Create a non-root user<br>RUN useradd -m -s /bin/bash &lt;username&gt; &amp;&amp; \<br>echo &quot;&lt;username&gt; ALL=(ALL) NOPASSWD:ALL&quot; &gt; /etc/sudoers.d/&lt;username&gt;<br><br># Set up the user&#39;s environment<br>COPY ./.bashrc /home/&lt;username&gt;/.bashrc<br>RUN chown &lt;username&gt;:&lt;username&gt; /home/&lt;username&gt;/.bashrc<br><br># Set the working directory<br>WORKDIR /home/&lt;username&gt;<br><br># Switch to the non-root user<br>USER &lt;username&gt;<br><br>RUN rosdep update<br><br># Entrypoint<br>COPY ./entrypoint.sh /entrypoint.sh<br>RUN sudo chmod 755 /entrypoint.sh<br>ENTRYPOINT [&quot;/entrypoint.sh&quot;]<br>CMD [&quot;bash&quot;]</pre><p><strong>Note: Replace the </strong>&lt;username&gt;<strong> in the above script with the username you wish for the user in the docker container shell.</strong></p><h3>Entrypoint Script</h3><p>The entrypoint.sh script plays a crucial role in ensuring that the ROS2 environment is properly set up each time the Docker container starts. Below is the breakdown of its functionality:</p><h4>Explanation</h4><ul><li><strong>Source ROS Installation</strong>: The script begins by sourcing the base ROS2 setup file, which is located at /opt/ros/humble/setup.bash. This step is essential as it ensures that all the ROS2 environment variables are properly configured. This includes adding ROS2 binaries to the system path and setting up any other environment requirements.</li><li><strong>Source the Workspace</strong>: The script then checks if there is an existing workspace located at /home/&lt;username&gt;/&lt;ros2_workspace_directory&gt;/install/setup.bash and sources it. This step allows the workspace&#39;s setup file to be loaded, making any compiled packages in the workspace available for use in the current environment. By checking the file&#39;s existence, the script ensures that it only sources the workspace if it has been built, preventing errors during container initialization.</li><li><strong>Execute Passed Command</strong>: Finally, the script executes any command passed to it (exec &quot;$@&quot;). This is an important feature that allows the container to behave flexibly depending on what is provided during its run time. For example, you could start a shell, run a script, or launch a specific ROS2 node. By using exec, it replaces the shell with the given command, which helps with better signal handling, especially in Docker.</li></ul><p>The entrypoint.sh script ensures that every time the Docker container starts, it is ready to work with ROS2, either by launching a node, testing, or running any development script. This makes the development process more efficient, as it minimizes the time spent on setup.</p><h4><strong>Full entrypoint.sh</strong></h4><pre>#!/bin/bash<br><br># Source ROS installation<br>source /opt/ros/humble/setup.bash<br><br># Directory path to the ROS2 Workspace<br>ROS_WS=&quot;ros2_workspace&quot;<br><br># Source the workspace if it exists<br>if [ -f &quot;/home/$USER/$ROS_WS/install/setup.bash&quot; ]; then<br>    source &quot;/home/$USER/$ROS_WS/install/setup.bash&quot;<br>fi<br><br># Execute the command passed to the script<br>exec &quot;$@&quot;</pre><p><strong>Note: Replace the </strong>ROS_WS<strong> in the above script with the path to the ROS2 Workspace Directory.</strong></p><h3>Docker Build Script</h3><p>The docker_build.sh script automates the process of building the Docker image for the ROS2 environment. This script simplifies the image creation process by encapsulating all the necessary build commands, ensuring that developers can quickly generate a consistent image without manually executing multiple commands.</p><h4>Explanation</h4><ul><li><strong>Set the Image Name</strong>: The script defines a variable IMAGE_NAME to specify the name of the Docker image being built. This makes it easy to modify the image name if needed.</li><li><strong>Build the Docker Image</strong>: The docker build command is used to create the Docker image using the Dockerfile in the current directory. The -t flag tags the image with the specified name.</li><li><strong>Output Success Message</strong>: After building the image, the script outputs a success message to indicate that the build process has completed.</li></ul><p>This script makes the image-building process straightforward and reproducible, ensuring that all team members can generate the same development environment with ease.</p><h4>Full Docker Build Script</h4><pre>#!/usr/bin/bash<br><br># Set Contianer Name<br>CONTAINER_NAME=&quot;&lt;CUSTOM_ROS2_CONTAINER&gt;&quot;<br><br>echo &quot;Building ROS2-Humble Container&quot;<br>docker build --rm -t $CONTAINER_NAME:latest .<br><br>echo &quot;Docker Build Completed&quot;</pre><p><strong>Note: Replace the </strong>&lt;CUSTOM_ROS2_CONTAINER&gt;<strong> in the above script with the name of your ROS2 Container.</strong></p><h3>Docker Run Script</h3><p>The docker_run.sh script is used to run the Docker container with the correct settings. This script ensures that the container is executed with the appropriate configuration and makes it easy to start development without manually specifying Docker options each time.</p><pre>#!/usr/bin/env bash<br><br>BASH_HISTORY_FILE=${PWD%/*}/.bash_history<br>BASH_RC_FILE=${PWD%/*}/docker/.bashrc<br><br>CONTAINER_NAME=&lt;CUSTOM_CONTAINER_NAME&gt;<br>DOCKER_USER=&quot;&lt;USERNAME&gt;&quot;<br><br>docker_count=$(docker ps -a | grep CONTAINER_NAME | wc -l)<br>((docker_count=docker_count+1))<br><br>XAUTH=/tmp/.docker.xauth_$docker_count<br>sleep 0.1<br>touch $XAUTH<br>xauth nlist $DISPLAY | sed -e &#39;s/^..../ffff/&#39; | xauth -f $XAUTH nmerge -<br><br># Create a string with all --device options for each device in /dev/<br>device_options=&quot;&quot;<br>for device in /dev/*; do<br>    if [ -e &quot;$device&quot; ]; then<br>        device_options+=&quot;--device=$device &quot;<br>    fi<br>done<br><br>docker run -it --rm \<br>    --name CONTAINER_NAME-$docker_count \<br>    --user $(id -u):$(id -g) \<br>    --volume=&quot;${PWD%/*}:/home/$DOCKER_USER&quot; \<br>    --volume=&quot;$BASH_HISTORY_FILE:/home/$DOCKER_USER/.bash_history&quot; \<br>    --volume=&quot;$BASH_RC_FILE:/home/$DOCKER_USER/.bashrc&quot; \<br>    --volume=&quot;/tmp/.X11-unix:/tmp/.X11-unix:rw&quot; \<br>    --volume=&quot;$XAUTH:$XAUTH&quot; \<br>    --env=&quot;XAUTHORITY=$XAUTH&quot; \<br>    --env=&quot;DISPLAY&quot; \<br>    --env=&quot;QT_X11_NO_MITSHM=1&quot; \<br>    --workdir=&quot;/home/$DOCKER_USER&quot; \<br>    $device_options \<br>    --net=host \<br>    --privileged \<br>    CONTAINER_NAME:latest<br><br>echo &quot;Docker container exited.&quot;</pre><h4>Script Breakdown:</h4><ol><li><strong>Bash History and .bashrc Paths</strong>:</li></ol><ul><li>BASH_HISTORY_FILE=${PWD%/*}/.bash_history: This line sets the path to the .bash_history file, which will be mounted inside the container. It helps in preserving the bash history across container runs.</li><li>BASH_RC_FILE=${PWD%/*}/docker/.bashrc: This sets the path to the .bashrc file that will be used in the container. Customizing the bash environment inside the container improves usability.</li></ul><p>2. <strong>Dynamic Container Naming:</strong></p><ul><li>docker_count=$(docker ps -a | grep CONTAINER_NAME | wc -l): This command counts the number of existing CONTAINER_NAME containers. It ensures that each new container has a unique name.</li><li>((docker_count=docker_count+1)): The count is incremented by one to assign a new number to the container name for each new instance.</li><li>This dynamic naming helps avoid naming conflicts when launching multiple containers.</li></ul><p>3. <strong>X11 Authentication Setup</strong>:</p><ul><li>XAUTH=/tmp/.docker.xauth_$docker_count: A unique Xauthority file is created for each container to handle X11 forwarding.</li><li>xauth nlist $DISPLAY | sed -e &#39;s/^..../ffff/&#39; | xauth -f $XAUTH nmerge -: This command fetches the X11 authentication token from the host’s display and prepares it for use inside the Docker container. It allows graphical applications inside the container to access the display server on the host.</li></ul><p>4. <strong>Device Mounting</strong>:</p><ul><li>The loop for device in /dev/* collects all devices from the /dev/ directory and constructs a string of --device options. This ensures that all connected devices (e.g., sensors, cameras, etc.) are accessible inside the Docker container.</li><li>device_options+=&quot;--device=$device &quot;: This line adds each device found under /dev/ to the device options passed to the docker run command. It’s useful for hardware access, such as when interfacing with robotic components or USB devices.</li></ul><p>5. <strong>Running the Docker Container</strong>: The docker run command is structured with several flags and options:</p><ul><li>-it: This flag allows the container to run in interactive mode with a terminal attached.</li><li>--rm: This flag ensures the container is removed once it exits, keeping your Docker environment clean.</li><li>--name CONTAINER_NAME-$docker_count: The container is named dynamically, ensuring no name conflicts when launching multiple containers.</li><li>--user $(id -u):$(id -g): This ensures that the container runs as the current user, preventing permission issues when accessing files created inside the container.</li><li>--volume=&quot;${PWD%/*}:/home/$DOCKER_USER&quot;: Mounts the parent directory of the current working directory into the container at /home/$DOCKER_USER, allowing you to access files from your local environment inside the container.</li><li>--volume=&quot;$BASH_HISTORY_FILE:/home/$DOCKER_USER/.bash_history&quot;: Preserves the bash history between container sessions by mounting the host machine’s .bash_history file into the container.</li><li>--volume=&quot;$BASH_RC_FILE:/home/$DOCKER_USER/.bashrc&quot;: Mounts the .bashrc file from the host machine into the container, ensuring that any custom shell configurations are applied when using the container.</li><li>--volume=&quot;/tmp/.X11-unix:/tmp/.X11-unix:rw&quot;: This mounts the X11 socket into the container, allowing GUI applications to interface with the host&#39;s display.</li><li>--volume=&quot;$XAUTH:$XAUTH&quot; and --env=&quot;XAUTHORITY=$XAUTH&quot;: These lines ensure the container can authenticate with the host’s X server, enabling graphical applications to display on the host.</li><li>--env=&quot;DISPLAY&quot; and --env=&quot;QT_X11_NO_MITSHM=1&quot;: These environment variables set up the display environment, ensuring that graphical applications can be run from within the container.</li><li>--workdir=&quot;/home/$DOCKER_USER&quot;: This sets the working directory inside the container to /home/$DOCKER_USER, where mounted files and environment variables are located.</li><li>$device_options: The collected --device options are passed here to allow the container to access all hardware devices available in /dev/.</li><li>--net=host: This option makes the container use the host’s network stack, which is necessary for ROS2 networking and communication, especially in multi-machine setups.</li><li>--privileged: This flag grants the container extended privileges, enabling access to hardware devices such as USB ports, which is crucial for robotic systems.</li><li><strong>Image to Run</strong>: CONTAINER_NAME:latest: This specifies the Docker image to run. In this case, it&#39;s the ndi-needle image with the latest tag.</li><li><strong>Exit Message</strong>: echo &quot;Docker container exited.&quot;: After the container finishes its run, this message is printed to indicate that the container has exited.</li></ul><p>This custom docker_run.sh script allows you to easily start a ROS2 development environment with access to graphical applications and hardware devices. The script handles various important tasks:</p><ul><li><strong>Dynamic container naming</strong>: To avoid conflicts and allow multiple container instances.</li><li><strong>Graphical application support</strong>: By forwarding X11 credentials and mounting the necessary sockets, GUI applications like rviz or gazebo can run inside the container and display on the host machine.</li><li><strong>Hardware device access</strong>: The script automatically discovers and mounts hardware devices, making it easy to interface with robots, sensors, and other peripherals.</li><li><strong>User-friendly</strong>: The mounted .bashrc and .bash_history files ensure that your shell environment inside the container is familiar and customizable.</li></ul><p>This script streamlines the process of launching a fully-featured ROS2 container with all necessary configurations, perfect for robotic development and testing environments.</p><h3>Custom BASHRC Script</h3><p>The provided .bashrc file plays an essential role in customizing the ROS2 development environment inside the Docker container. It sets up the necessary ROS2 configurations, enables useful aliases, and ensures a more efficient shell experience. The custom .bashrc file enhances the ROS2 development workflow by:</p><ul><li><strong>Sourcing ROS2 environments automatically</strong>: Both the main ROS2 environment and your specific workspace are set up every time a terminal is opened, eliminating repetitive manual commands.</li><li><strong>Improving usability</strong>: The custom prompt makes it easier to distinguish between Docker and host environments. Color support and handy aliases for ls and grep commands make the terminal output more readable.</li><li><strong>Streamlining ROS2 development</strong>: The provided ROS2 aliases simplify common tasks like building, running nodes, launching simulations, and interacting with topics, nodes, and parameters.</li><li><strong>Effortless navigation</strong>: Automatically navigating to the ROS2 workspace on session start reduces friction when switching between tasks, ensuring that you are ready to build, test, or launch nodes without extra steps.</li></ul><pre># .bashrc<br><br># Source ROS setup files<br>source /opt/ros/humble/setup.bash<br><br># Path to the Default ROS2 Workspace<br>ROS2_WS=&quot;&lt;DEFAULT_ROS2_WORKSPACE_PATH&gt;&quot;<br><br>if [ -f &quot;/home/$USER/$ROS2_WS/install/setup.bash&quot; ]; then<br>    source &quot;/home/$USER/$ROS2_WS/install/setup.bash&quot;<br>fi<br># Set the prompt<br>PS1=&#39;\[\033[01;32m\]\u@docker:\[\033[01;34m\]\w\[\033[00m\]\$ &#39;<br><br># Enable color support for ls and add handy aliases<br>if [ -x /usr/bin/dircolors ]; then<br>    test -r ~/.dircolors &amp;&amp; eval &quot;$(dircolors -b ~/.dircolors)&quot; || eval &quot;$(dircolors -b)&quot;<br>    alias ls=&#39;ls --color=auto&#39;<br>    alias grep=&#39;grep --color=auto&#39;<br>    alias fgrep=&#39;fgrep --color=auto&#39;<br>    alias egrep=&#39;egrep --color=auto&#39;<br>fi<br><br># Some more ls aliases<br>alias ll=&#39;ls -alF&#39;<br>alias la=&#39;ls -A&#39;<br>alias l=&#39;ls -CF&#39;<br><br># ROS2 aliases<br>alias cb=&#39;colcon build &amp;&amp; source install/setup.bash&#39;<br>alias cbp=&#39;colcon build --symlink-install --packages-select&#39;<br>alias cbt=&#39;colcon build --symlink-install --packages-select --cmake-args -DCMAKE_BUILD_TYPE=RelWithDebInfo&#39;<br>alias run=&#39;ros2 run&#39;<br>alias launch=&#39;ros2 launch&#39;<br>alias topic=&#39;ros2 topic&#39;<br>alias node=&#39;ros2 node&#39;<br>alias param=&#39;ros2 param&#39;<br><br># CD to the workspace<br>cd /home/$USER/$ROS2_WS</pre><h4>Script Breakdown:</h4><h4><strong>1. Sourcing ROS2 Setup Files</strong>:</h4><ul><li>source /opt/ros/humble/setup.bash: This command sources the ROS2 setup file for the Humble release, initializing the ROS2 environment by setting the necessary environment variables.</li><li>The next if block checks for the existence of the workspace’s setup file (/home/$USER/$ROS2_WS/install/setup.bash). If it exists, it is sourced, making the ROS2 packages in the workspace available. This ensures that every time a new terminal is opened, the workspace is automatically ready for development without requiring manual setup.</li></ul><p><strong>2. Custom Prompt</strong>:<br>PS1=&#39;\[\033[01;32m\]\u@docker:\[\033[01;34m\]\w\[\033[00m\]\$ &#39;: This line customizes the command prompt to display the username, the current working directory, and the identifier @docker in different colors. This visual change makes it clear when you&#39;re working inside the Docker container, reducing confusion between host and container environments.</p><p><strong>3. Color Support and Aliases for </strong><strong>ls</strong>: This block enables color support for commands like ls, grep, and their variants (fgrep, egrep). This makes output easier to read, particularly when dealing with long lists of files or search results. The additional aliases for ls provide shortcuts for common listing tasks :</p><ul><li>ll: Lists all files in long format, including hidden files (-alF).</li><li>la: Lists all hidden files (-A).</li><li>l: Lists files in columns (-CF).</li></ul><p><strong>4. ROS2 Aliases</strong>: This section provides shortcuts for common ROS2 commands to streamline development:</p><ul><li>cb: Runs colcon build and then sources the generated setup.bash file, making the build results available in the environment.</li><li>cbp: Builds specific ROS2 packages by name using --packages-select.</li><li>cbt: Builds selected packages with additional CMake arguments for RelWithDebInfo (optimized with debugging information).</li><li>run: A shortcut for running ROS2 nodes (ros2 run).</li><li>launch: A shortcut for launching ROS2 launch files (ros2 launch).</li><li>topic, node, param: Shortcuts for inspecting and managing ROS2 topics, nodes, and parameters, respectively. This reduces the need for typing the full command names.</li></ul><p><strong>5. Automatic Workspace Navigation</strong>: cd /home/$USER/$ROS2_WS: This command automatically navigates to the ROS2 workspace ($ROS2_WS) when a new terminal session is started. This ensures that you’re always in the correct directory to start development without manually navigating to it each time.</p><p>This configuration optimizes the development experience inside the Docker container, ensuring a faster and smoother workflow when working with ROS2 applications.</p><h3>General Architecture of the Project Workspace</h3><p>This project workspace is organized to support ROS2 development using Docker, ensuring that all necessary files and scripts are contained within a structured hierarchy. Below is an elaboration of the key components and how each part fits into the overall workflow.</p><pre>ROS-FOLDER<br>├── docker<br>│   ├── docker_build.sh<br>│   ├── Dockerfile<br>│   ├── docker_run.sh<br>│   ├── entrypoint.sh<br>│   └── .bashrc<br>├── .bashrc<br>├── .bash_history<br>└── ros_workspace<br>    ├── build<br>    ├── install<br>    │   ├── setup.bash<br>    │   ├── setup.ps1<br>    │   ├── setup.sh<br>    │   └── setup.zsh<br>    ├── log<br>    └── src<br>        ├── pkg_1<br>        └── pkg_2</pre><h4>1. ROS-FOLDER:</h4><p>The top-level directory serves as the root of your project workspace. It contains two main sections:</p><ul><li><strong>docker/</strong>: A folder for Docker-related files and scripts that set up and manage the ROS2 container.</li><li><strong>ros_workspace/</strong>: A standard ROS2 workspace that includes source code, build files, installation scripts, and logs.</li></ul><h4>2. docker/:</h4><p>This folder contains all the files required for setting up, building, and running your Docker-based ROS2 environment.</p><ul><li><strong>docker_build.sh</strong>: This script automates the process of building the Docker image for the ROS2 development environment. Running this script ensures that the Docker container is created with all necessary dependencies, libraries, and tools.</li><li><strong>Dockerfile</strong>: Defines the Docker image that encapsulates your ROS2 environment. It specifies the base image, installs ROS2 and additional tools, sets up environment variables, and configures the system to create a development environment that is isolated from the host system.</li><li><strong>docker_run.sh</strong>: A script that automates launching the Docker container. It handles mounting volumes (such as your workspace and configuration files), passing device access, setting up environment variables, and allowing GUI applications to run inside the container. This script dynamically names containers and manages hardware access, making it easier to run your ROS2 nodes and work with the environment.</li><li><strong>entrypoint.sh</strong>: This script is executed whenever the container starts, ensuring that the ROS2 environment is properly initialized by sourcing the necessary setup files. It also allows for passing commands dynamically to be executed when the container starts.</li><li><strong>.bashrc</strong>: A container-specific .bashrc file, which configures the shell environment for the container. It sources ROS2 setup files, defines useful aliases, and customizes the command prompt to make development inside the container more efficient.</li></ul><h4>3. .bashrc (outside docker folder):</h4><p>This is the .bashrc file located in the root of the ROS-FOLDER, and it is separate from the .bashrc used within the container. This file likely contains shell customizations for the user on the host system. When the Docker container is run, the relevant .bashrc from the docker/ folder is used inside the container instead.</p><h4>4. .bash_history:</h4><p>This file contains the command history for your shell sessions. It is shared between the host and the container, allowing you to retain your command history across different Docker sessions, which improves productivity by letting you easily re-run commands without needing to type them again.</p><h4>5. ros_workspace/:</h4><p>This directory is your ROS2 workspace, where the actual development and execution of ROS2 nodes happen. It follows the standard ROS2 workspace structure:</p><ul><li><strong>build/</strong>: This folder contains the compiled binary files after running the colcon build command. It includes all build artifacts needed to run your ROS2 packages.</li><li><strong>install/</strong>: After building your ROS2 workspace, the install/ directory contains the final installation of the packages, including the necessary setup files for various shells. These setup files are automatically generated when you build the ROS2 workspace and are used to ensure that all ROS2-related environment variables are correctly set up when running ROS2 nodes or packages.</li><li><strong>log/</strong>: This folder stores the logs from running and building the ROS2 packages. It is useful for debugging purposes, as it provides detailed information on what occurred during build or execution, helping you identify any errors or issues.</li><li><strong>src/</strong>: The src directory is where your ROS2 packages (or nodes) are stored. This is where you write your ROS2 code.</li></ul><h4>Overall Structure Benefits:</h4><p>This workspace structure is designed to separate concerns:</p><ul><li><strong>Docker management</strong> is handled in the docker/ folder, ensuring a consistent ROS2 environment across different machines.</li><li><strong>ROS2 workspace</strong> development follows the standard ROS2 workspace structure, enabling smooth development, build, and execution processes.</li></ul><p>By adhering to this structure, you ensure that both Docker and ROS2 are properly configured and can easily interact, providing a clean and modular development workflow. This organization helps in maintaining scalability and manageability, especially when dealing with larger ROS2 projects with multiple packages and dependencies.</p><h3>Overall Summary</h3><p>This blog provides a comprehensive guide for setting up a ROS2 Humble environment using Docker, emphasizing the importance of containerization in robotics development. Docker offers a reproducible and isolated development environment, avoiding common issues such as dependency conflicts and version mismatches. This guide walks through the process of configuring and launching a custom ROS2 Docker container, highlighting key components such as the Dockerfile, docker_build.sh, docker_run.sh, entrypoint.sh, and .bashrc, all of which streamline the setup and development process.</p><p>Key takeaways include:</p><ul><li><strong>Docker as a Tool for Consistency</strong>: Docker ensures that your ROS2 environment is identical across all machines, facilitating team collaboration and reducing the risk of environment discrepancies.</li><li><strong>ROS2 in Docker</strong>: By containerizing ROS2, you can manage complex dependencies more easily, ensuring your development process is isolated from the host machine while retaining access to necessary hardware devices and graphical interfaces through X11 forwarding.</li><li><strong>Customizable Environment</strong>: The use of custom .bashrc files and ROS2 workspace configuration ensures that the development environment is tailored for both ease of use and efficiency, with handy aliases and automatic sourcing of setup files.</li><li><strong>Effortless Automation</strong>: The provided scripts, including docker_build.sh and docker_run.sh, automate tedious setup processes, making it easy to build and run the Docker container with minimal effort. The scripts dynamically configure container names, access devices, and set up necessary volumes and environment variables.</li><li><strong>Standard ROS2 Workspace Structure</strong>: A well-organized workspace structure, adhering to ROS2 standards, ensures that the development process is clean, maintainable, and scalable. This layout allows seamless compilation and execution of ROS2 nodes.</li></ul><p>Overall, this guide demonstrates how to effectively leverage Docker for ROS2 development, providing a repeatable, secure, and efficient setup for robotic system development and testing.</p><p><em>If you found this article helpful, please follow me on </em><a href="https://shashank-goyal-blogs.medium.com/"><em>Medium</em></a><em>. </em>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author.</p><p>Now that you’ve set up ROS2 using Docker, it’s time to dive deeper! Learn how to build ROS2 packages, understand its core concepts, and create your first robotics application. Check out my next guide: <a href="https://shashank-goyal-blogs.medium.com/mastering-ros2-your-ultimate-beginners-guide-to-robotics-a72179db4c84">Mastering ROS2: Your Ultimate Beginner’s Guide to Robotics</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*aUyN6YOrWzsxBQmw.png" /></figure><h4>👋 If you find this helpful, please click the clap 👏 button below a few times to show your support for the author 👇</h4><h4>🚀<a href="http://from.faun.to/r/8zxxd">Join FAUN Developer Community &amp; Get Similar Stories in your Inbox Each Week</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c541b73fe141" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/ros2-humble-gui-docker-container-a-step-by-step-guide-c541b73fe141">ROS2 Humble GUI-Docker Container: A Step-by-Step Guide</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Brain-Computer Interfaces]]></title>
            <link>https://shashank-goyal-blogs.medium.com/introduction-to-brain-computer-interfaces-171f4e725bb4?source=rss-e85e3a6012ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/171f4e725bb4</guid>
            <category><![CDATA[humancomputer-interaction]]></category>
            <category><![CDATA[neuroscience]]></category>
            <category><![CDATA[cognitive-science]]></category>
            <category><![CDATA[neurotechnology]]></category>
            <category><![CDATA[brain-computer-interface]]></category>
            <dc:creator><![CDATA[Shashank Goyal]]></dc:creator>
            <pubDate>Tue, 17 Sep 2024 06:04:41 GMT</pubDate>
            <atom:updated>2024-09-17T06:04:41.894Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_cRHE0zNlXjKt1z3" /></figure><p><strong>Introduction:</strong> Welcome to the exciting and rapidly evolving field of Brain-Computer Interfaces (BCIs)! This blog will serve as the gateway to understanding how BCIs function, a brief historical background, and a lot of applications that make this technology so transformative. We will cover the fundamental components of BCI systems and explore the types of brain signals that can be harnessed to communicate with machines.</p><p><strong>What is a Brain-Computer Interface (BCI)?</strong> A Brain-Computer Interface is a direct communication pathway between the brain and an external device. By bypassing the body’s normal neuromuscular pathways, BCIs allow individuals to control devices using only their thoughts. This technology has profound implications for people with disabilities, enabling them to regain control over their environment through thought alone.</p><p><strong>Components of a BCI System:</strong> BCI systems are composed of several key components -</p><ul><li><strong>Signal Acquisition:</strong> The first step in a BCI system is the acquisition of brain signals. This is typically done using electrodes that capture electrical activity from the brain, such as EEG (Electroencephalography).</li><li><strong>Signal Processing:</strong> Once the brain signals are acquired, they must be processed to remove noise and extract relevant features. This involves filtering the data, identifying signal patterns, and isolating the components that correspond to specific thoughts or intentions.</li><li><strong>Feature Extraction and Classification:</strong> After processing, the next step is to extract meaningful features from the signals. These features are then classified to determine the user’s intent. Machine learning algorithms play a crucial role in this step, learning from training data to improve classification accuracy.</li><li><strong>Output Device:</strong> Finally, the classified signals are translated into commands that control an external device, such as a computer cursor, robotic arm, or wheelchair.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XGfow453Bzso0n13NP-B0w.png" /><figcaption>Figure by <a href="https://www.jhuapl.edu/about/people/brock-wester">Dr. Brock Wester</a></figcaption></figure><p><strong>Types of Brain Signals Used in BCIs:</strong> The most commonly used brain signals in BCIs include -</p><ul><li><strong>EEG (Electroencephalography):</strong> EEG measures electrical activity in the brain through electrodes placed on the scalp. It is widely used due to its non-invasive nature, although it has limitations in terms of spatial resolution and signal clarity.</li><li><strong>ECoG (Electrocorticography):</strong> ECoG involves placing electrodes directly on the surface of the brain. It provides better signal quality than EEG but is more invasive.</li><li><strong>fNIRS (Functional Near-Infrared Spectroscopy):</strong> fNIRS measures changes in blood oxygenation, offering better spatial resolution than EEG but with slower signal acquisition.</li><li><strong>Intracortical Implants:</strong> These electrodes are implanted directly into the brain tissue, providing the highest quality signals but with significant risks.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*VuyhWprIPu8raA8I_OCJaQ.png" /><figcaption>Figure by <a href="https://www.jhuapl.edu/about/people/brock-wester">Dr. Brock Wester</a></figcaption></figure><p><strong>History of BCIs:</strong> The journey of BCIs began in 1924 with Hans Berger’s discovery of EEG. This marked the first time electrical activity from the brain was recorded. Over the decades, the field has evolved from basic EEG experiments to sophisticated BCI systems capable of controlling complex devices. Significant milestones include the development of the first BCIs for communication by paralyzed patients in the 1970s and 1980s, leading up to the modern era of BCIs, which are now being explored for a wide range of applications.</p><p><strong>Applications of BCIs:</strong> BCIs have numerous applications across various fields -</p><ul><li><strong>Medical Rehabilitation:</strong> BCIs are used to assist individuals with disabilities, allowing them to control prosthetic limbs, wheelchairs, or computer interfaces using their thoughts.</li><li><strong>Neuroergonomics:</strong> Enhancing the interaction between humans and machines, BCIs can be used in workplaces to improve efficiency and safety.</li><li><strong>Gaming and Entertainment:</strong> BCIs are being integrated into video games, creating immersive experiences where players can control gameplay using their minds.</li><li><strong>Neurofeedback:</strong> BCIs are also employed in neurofeedback therapies to help patients improve their mental health by training their brain activity.</li></ul><p><strong>Conclusion:</strong> Brain-computer interfaces represent a groundbreaking technology that has the potential to change lives. From restoring mobility to enhancing human-machine interaction, BCIs are paving the way for new possibilities in both medical and non-medical fields. In the next blog, we will delve deeper into the different types of BCIs, focusing on non-invasive and invasive modalities.</p><p><strong>Next Blog:</strong> <a href="https://shashank-goyal-blogs.medium.com/diving-deeper-into-bci-technologies-non-invasive-vs-invasive-modalities-4cd55f74ab12">Diving Deeper into BCI Technologies: Non-Invasive vs. Invasive Modalities</a></p><p><strong>Thank You:</strong> I have learned this information from my course <strong>EN.585.783: Introduction to Brain-Computer Interface at Johns Hopkins University</strong>. A big thanks to my instructors for making this journey enlightening!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=171f4e725bb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diving Deeper into BCI Technologies: Non-Invasive vs. Invasive Modalities]]></title>
            <link>https://shashank-goyal-blogs.medium.com/diving-deeper-into-bci-technologies-non-invasive-vs-invasive-modalities-4cd55f74ab12?source=rss-e85e3a6012ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cd55f74ab12</guid>
            <category><![CDATA[medical-devices]]></category>
            <category><![CDATA[non-invasive-technology]]></category>
            <category><![CDATA[invasive-brain-interfaces]]></category>
            <category><![CDATA[eeg]]></category>
            <category><![CDATA[neurotechnology]]></category>
            <dc:creator><![CDATA[Shashank Goyal]]></dc:creator>
            <pubDate>Tue, 17 Sep 2024 06:02:04 GMT</pubDate>
            <atom:updated>2024-09-17T06:02:04.367Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aNhmh13EKK7Vr5Rr" /></figure><p><strong>Introduction:</strong> After exploring the basics of Brain-Computer Interfaces in our previous blog, it’s time to take a closer look at the different types of BCIs. Specifically, we’ll be comparing non-invasive and invasive approaches, discussing their respective advantages, limitations, and use cases.</p><p><strong>Understanding Non-Invasive BCIs:</strong> Non-invasive BCIs are designed to capture brain signals without the need for surgical procedures. These systems are popular because they are safer and easier to deploy compared to invasive methods. The most common non-invasive technique is EEG (Electroencephalography), which involves placing electrodes on the scalp to measure brain activity.</p><ul><li><strong>EEG (Electroencephalography):</strong> EEG is the foundation of non-invasive BCIs. It measures the brain’s electrical activity through electrodes on the scalp. While EEG is non-invasive and relatively inexpensive, it is prone to noise and has limited spatial resolution. Despite these limitations, EEG is widely used in research and clinical applications due to its accessibility and ease of use.</li><li><strong>fNIRS (Functional Near-Infrared Spectroscopy):</strong> fNIRS is another non-invasive technique that measures brain activity by detecting changes in blood oxygenation. This method offers better spatial resolution than EEG but is slower in capturing brain signals. fNIRS is particularly useful in monitoring cortical activity during cognitive tasks.</li><li><strong>Magnetoencephalography (MEG):</strong> MEG measures magnetic fields produced by neural activity. While it provides excellent temporal resolution and is less susceptible to noise than EEG, it requires large, expensive equipment and is not as widely available.</li></ul><p><strong>Exploring Invasive BCIs:</strong> Invasive BCIs, on the other hand, involve implanting electrodes directly into the brain. These systems offer much clearer and more precise signals than non-invasive BCIs but come with significant risks, such as infection or damage to brain tissue.</p><ul><li><strong>ECoG (Electrocorticography):</strong> ECoG involves placing electrodes directly on the surface of the brain, beneath the skull. This technique provides better signal quality and spatial resolution compared to EEG, making it suitable for clinical applications, particularly in epilepsy treatment. However, it is more invasive, requiring surgical intervention.</li><li><strong>Intracortical Implants:</strong> These implants involve inserting electrodes directly into the brain tissue. They provide the highest signal quality and spatial resolution, making them ideal for controlling advanced prosthetic devices or restoring motor function in paralyzed individuals. However, the risks associated with intracortical implants are significant, including potential brain damage and long-term biocompatibility issues.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CFRjr8B6q6O3Bl9olHva0A.png" /><figcaption>Wolpaw et al., IEEE Trans Neural Sys Rehab Eng, 2006</figcaption></figure><p><strong>Comparative Analysis: Non-Invasive vs. Invasive BCIs:</strong></p><ul><li><strong>Signal Quality:</strong> Invasive BCIs offer superior signal quality and spatial resolution due to the direct access to brain tissue. Non-invasive methods, while safer, tend to have lower signal clarity.</li><li><strong>Safety and Risk:</strong> Non-invasive BCIs are much safer, as they do not involve surgery. In contrast, invasive BCIs carry risks such as infection, brain tissue damage, and the potential for adverse immune responses.</li><li><strong>Applications:</strong> Non-invasive BCIs are suitable for everyday applications, such as gaming, neurofeedback, and basic communication devices. Invasive BCIs are more appropriate for clinical applications where high precision is necessary, such as advanced neuroprosthetics or deep brain stimulation.</li></ul><p><strong>Conclusion:</strong> Both non-invasive and invasive BCIs have their unique advantages and challenges. While non-invasive BCIs are more accessible and pose fewer risks, invasive BCIs offer superior performance for more demanding applications. As technology progresses, hybrid approaches that combine the benefits of both methods may emerge, offering high-quality signals with minimal risk.</p><p><strong>Next Blog:</strong> <a href="https://shashank-goyal-blogs.medium.com/the-technical-backbone-of-bcis-signal-processing-and-machine-learning-27afd8d669b6">The Technical Backbone of BCIs: Signal Processing and Machine Learning</a></p><p><strong>External References (Reading Recommendation):</strong></p><ul><li>Lebedev, M. A., &amp; Nicolelis, M. A. L. (2006). “Brain-machine interfaces: past, present and future.” <em>Trends in Neurosciences</em>, 29(9), 536–546.</li><li>Schalk, G., &amp; Leuthardt, E. C. (2011). “Brain-computer interfaces using electrocorticographic signals.” <em>IEEE Reviews in Biomedical Engineering</em>, 4, 140–154.</li></ul><p><strong>Thank You:</strong> I have learned this information from my course <strong>EN.585.783 Introduction to Brain-Computer Interface at Johns Hopkins University</strong>. A big thanks to my instructors for making this journey enlightening!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cd55f74ab12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Technical Backbone of BCIs: Signal Processing and Machine Learning]]></title>
            <link>https://shashank-goyal-blogs.medium.com/the-technical-backbone-of-bcis-signal-processing-and-machine-learning-27afd8d669b6?source=rss-e85e3a6012ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/27afd8d669b6</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai-healthcare-revolution]]></category>
            <category><![CDATA[eeg-analysis]]></category>
            <category><![CDATA[signal-processing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Shashank Goyal]]></dc:creator>
            <pubDate>Tue, 17 Sep 2024 05:59:12 GMT</pubDate>
            <atom:updated>2024-09-17T05:59:12.248Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mpc3rUqk3PYs6mFV" /></figure><p><strong>Introduction:</strong> In the world of Brain-Computer Interfaces (BCIs), the journey from raw brain signals to meaningful commands is a complex process that relies heavily on signal processing and machine learning. In this blog, we’ll dive into the technical aspects of BCIs, exploring how brain signals are processed, how features are extracted, and how machine learning algorithms are applied to decode user intentions.</p><p><strong>Signal Processing: Cleaning and Preparing Brain Signals:</strong> The first step in BCI signal processing is to clean and prepare the raw brain signals for further analysis. This involves several key steps -</p><ul><li><strong>Artifact Removal:</strong> Raw EEG signals often contain artifacts from muscle movements, eye blinks, and electrical noise. These artifacts must be removed to ensure that the signals reflect genuine brain activity. Common techniques include Independent Component Analysis (ICA) and filtering methods to isolate and remove these unwanted components.</li><li><strong>Filtering:</strong> The raw EEG signals are filtered to remove high-frequency noise and to isolate the frequency bands of interest, such as alpha (8–12 Hz), beta (13–30 Hz), and gamma (30–100 Hz) rhythms. Filtering helps to focus the analysis on the most relevant parts of the brain signals.</li><li><strong>Signal Segmentation:</strong> Once the signals are clean, they are segmented into epochs or time windows that correspond to specific events or stimuli. This segmentation is crucial for aligning the brain signals with external events, such as a user’s intent to move a cursor or select an item.</li></ul><p><strong>Feature Extraction (Identifying Meaningful Patterns):</strong> After the signals are cleaned and segmented, the next step is to extract meaningful features that can be used to decode user intentions. This involves analyzing the signal in both the time and frequency domains -</p><ul><li><strong>Time-Domain Analysis:</strong> This involves examining the signal’s amplitude and latency over time. This can reveal important information about the brain’s response to stimuli, such as the timing of an event-related potential (ERP).</li><li><strong>Frequency-Domain Analysis:</strong> This involves analyzing the signal’s power across different frequency bands. For example, an increase in alpha power might indicate a relaxed state, while an increase in beta power might indicate concentration or alertness. Techniques like the Fourier Transform or Wavelet Transform are commonly used for this purpose.</li><li><strong>Spatial Filtering:</strong> This involves identifying the specific regions of the brain that are most relevant to the task at hand. Spatial filtering techniques, such as Common Spatial Patterns (CSP), can enhance the signal from the most informative electrodes while suppressing noise from less relevant regions.</li></ul><p><strong>Machine Learning (Decoding Brain Signals):</strong> Once the features are extracted, machine learning algorithms are employed to decode these signals and translate them into commands:</p><ul><li><strong>Classification Algorithms:</strong> Classification algorithms, such as Support Vector Machines (SVM) and Linear Discriminant Analysis (LDA), are used to categorize the brain signals into different classes, such as a left-hand movement vs. a right-hand movement. These algorithms are trained on labeled data, where the correct output is known, allowing them to learn the relationship between the brain signals and the intended actions.</li><li><strong>Regression Algorithms:</strong> For tasks that require continuous control, such as moving a cursor in two-dimensional space, regression algorithms are used to map the brain signals to continuous output variables. This enables smooth and precise control of external devices.</li><li><strong>Deep Learning:</strong> In recent years, deep learning techniques, such as Convolutional Neural Networks (CNNs), Long Short-Term Memory (LSTMs), etc. have been applied to BCI tasks. These models can automatically learn complex features from raw data, potentially improving the accuracy and generalization of BCI systems.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*9Mk5Bvb03w4XCvTeeyjqCw.png" /><figcaption><a href="https://doi.org/10.1002/hbm.23730">Schirrmeister et al., 2017</a></figcaption></figure><p><strong>Challenges and Future Directions:</strong> While signal processing and machine learning have significantly advanced BCI technology, several challenges remain: -</p><ul><li><strong>Data Variability:</strong> Brain signals can vary widely between individuals and even within the same individual over time. This variability poses a challenge for creating robust and generalizable models.</li><li><strong>Real-Time Processing:</strong> BCIs require real-time processing of brain signals, which can be computationally intensive. Ensuring that the system operates with minimal latency is critical for applications such as prosthetic control or real-time communication.</li><li><strong>Overfitting:</strong> Machine learning models can easily overfit to the training data, leading to poor performance on new data. Cross-validation and careful model selection are essential to mitigate this issue.</li></ul><p><strong>Conclusion:</strong> Signal processing and machine learning are at the heart of Brain-Computer Interface technology. By transforming raw brain signals into actionable commands, these techniques enable various applications, from controlling prosthetics to enhancing human-computer interaction. As technology continues to evolve, we can expect even more sophisticated BCI systems that are faster, more accurate, and capable of learning from minimal data.</p><p><strong>Next Blog:</strong> <a href="https://shashank-goyal-blogs.medium.com/advanced-bci-applications-from-neurostimulation-to-ethical-considerations-08e456fe4fdc">Advanced BCI Applications: From Neurostimulation to Ethical Considerations</a></p><p><strong>External References (Reading Recommendation):</strong></p><ul><li>Bishop, C. M. (2006). <em>Pattern Recognition and Machine Learning</em>. Springer.</li><li>Schalk, G., &amp; Leuthardt, E. C. (2011). “Brain-computer interfaces using electrocorticographic signals.” <em>IEEE Reviews in Biomedical Engineering</em>, 4, 140–154.</li></ul><p><strong>Thank You:</strong> I have learned this information from my course <strong>EN.585.783 Introduction to Brain-Computer Interface at Johns Hopkins University</strong>. A big thanks to my instructors for making this journey enlightening!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27afd8d669b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>