5% off all items, 10% off clearance with code FESTIVE

Free Shipping for orders over ₹999

support@thinkrobotics.com | +91 93183 94903

ROS2 Tutorial for Beginners: Your Complete Guide to Robot Operating System 2

ROS2 Tutorial for Beginners: Your Complete Guide to Robot Operating System 2


Robot Operating System 2 represents the next generation of the world's most popular framework for building robot software. Unlike its predecessor, ROS2 was designed from the ground up to address the limitations that emerged as robotics moved from research labs into commercial products. Whether you're building an autonomous mobile robot, a robotic arm, or a drone, ROS2 provides the tools and libraries you need to develop robust, scalable systems.

Learning ROS2 opens doors to countless robotics opportunities. Companies developing everything from warehouse automation to surgical robots rely on ROS2 as their software foundation. The framework handles the complex communication between sensors, actuators, and processing units that make up modern robotic systems, allowing developers to focus on their specific application logic rather than reinventing fundamental infrastructure.

This tutorial guides beginners through ROS2 fundamentals, starting with core concepts and progressing to hands-on examples that demonstrate real-world usage patterns. By the end, you'll understand how ROS2 nodes communicate, how to create your own nodes, and how to leverage the vast ecosystem of existing packages to accelerate your robotics projects.

What is ROS2 and Why Should You Learn It?

ROS2 is not an operating system despite its name. Instead, it's a middleware framework that provides communication infrastructure, development tools, and libraries designed explicitly for robot software. ROS2 handles messaging between different parts of your robot system, manages hardware drivers, and provides pre-built algorithms for everyday robotics tasks such as navigation, manipulation, and perception.

The transition from ROS1 to ROS2 addressed fundamental architectural limitations. ROS1 relied on a central controller node, creating a single point of failure and making distributed systems more difficult. ROS2 eliminates this requirement through its Data Distribution Service middleware, enabling truly distributed architectures where components can discover each other dynamically. This design makes ROS2 suitable for commercial products where reliability and real-time performance matter.

ROS2 brings several key advantages for modern robotics development. Real-time capabilities allow controlling hardware with deterministic timing requirements. Native support for multiple operating systems including Linux, Windows, and macOS, broadens development options. Built-in security features enable encrypted communication and authentication, essential for commercial deployments. The DDS middleware provides quality-of-service controls that weren't possible in ROS1.

The ROS2 ecosystem includes thousands of packages covering sensors, actuators, planning algorithms, perception tools, and simulation environments. Rather than implementing everything from scratch, robotics developers assemble these building blocks to create complete systems. This community-driven development accelerates progress across the entire robotics field, as improvements benefit everyone who uses the framework.

Installing ROS2 and Setting Up Your Environment

Getting started with ROS2 requires installing the framework on your development machine. ROS2 supports several Linux distributions, with Ubuntu receiving the most extensive testing and community support. The recommended approach uses Ubuntu 22.04 LTS with ROS2 Humble Hawksbill, the current long-term support release that receives updates through 2027.

Installation on Ubuntu is straightforward. First, set up the ROS2 apt repository by adding the package sources and importing the necessary GPG keys. Then install the desktop-full package, which includes all core tools, libraries, and visualization applications needed for development.

bash

sudo apt update && sudo apt install curl gnupg lsb-release

sudo curl -sSL https://raw.githubusercontent.com/ros/rosdistro/master/ros.key -o /usr/share/keyrings/ros-archive-keyring.gpg

echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/ros-archive-keyring.gpg] http://packages.ros.org/ros2/ubuntu $(source /etc/os-release && echo $UBUNTU_CODENAME) main" | sudo tee /etc/apt/sources.list.d/ros2.list > /dev/null

sudo apt update

sudo apt install ros-humble-desktop

After installation, configure your shell environment to recognize ROS2 commands. Source the setup script in every new terminal, or add it to your shell configuration file for automatic loading.

bash

source /opt/ros/humble/setup.bash

echo "source /opt/ros/humble/setup.bash" >> ~/.bashrc

Verify your installation by running the turtlesim demo. If you see a window with a turtle in the center, your ROS2 installation succeeded.

bash

ros2 run turtlesim turtlesim_node

Creating a ROS2 workspace provides an organized location for your custom packages and code. Workspaces use the colcon build system, which replaced catkin from ROS1.

bash

mkdir -p ~/ros2_ws/src

cd ~/ros2_ws

colcon build

source install/setup.bash

Think Robotics offers comprehensive robotics courses and tutorials covering ROS2 setup across different platforms and hardware configurations.

Understanding ROS2 Nodes, Topics, and Messages

ROS2 architecture revolves around nodes, which are individual processes that perform specific computational tasks. A complete robot system typically consists of many nodes working together, each handling a distinct responsibility. One node might process camera images, another might plan motion trajectories, and another might send commands to motors. This modular design allows teams to develop and test components independently.

Nodes communicate by publishing and subscribing to topics. A topic represents a named channel for a specific type of data. Publishers send messages to topics, and subscribers receive them. This publish-subscribe pattern decouples nodes from each other since publishers don't need to know which nodes are listening, and subscribers don't care which nodes are sending data.

Messages define the data structures that flow through topics. ROS2 includes standard message types for common robotics data, such as sensor readings, geometric poses, and images. The geometry_msgs/Twist message describes linear and angular velocity commands used to control mobile robots. Developers can also create custom message types when standard messages don't fit their needs.

Understanding the relationship between nodes, topics, and messages is fundamental to ROS2 development. Think of topics as radio stations broadcasting specific content. Nodes can tune in to receive broadcasts that interest them, and nodes can transmit on channels where others are listening.

Discovering what's running in a ROS2 system uses command-line tools. The ros2 node list command shows all active nodes, while ros2 topic list displays available topics.

bash

ros2 node list

ros2 topic list

ros2 topic info /turtle1/cmd_vel

ros2 topic echo /turtle1/pose

Creating Your First ROS2 Publisher and Subscriber

Building your first ROS2 nodes demonstrates how to create software that integrates into the ROS2 ecosystem. This example creates a publisher node that sends messages and a subscriber node that receives them.

Start by creating a new Python package in your workspace. ROS2 packages group related code and declare dependencies on other packages they need.

bash

cd ~/ros2_ws/src

ros2 pkg create --build-type ament_python my_first_package --dependencies rclpy std_msgs

The publisher node creates a class that inherits from Node. Inside the constructor, create a publisher object specifying the message type and topic name. A timer calls a callback function periodically to publish messages.

python

import rclpy

from rclpy.node import Node

from std_msgs.msg import String


class MinimalPublisher(Node):

    def __init__(self):

        super().__init__('minimal_publisher')

        self.publisher_ = self.create_publisher(String, 'topic', 10)

        self.timer = self.create_timer(0.5, self.timer_callback)

        self.i = 0


    def timer_callback(self):

        msg = String()

        msg.data = f'Hello World: {self.i}'

        self.publisher_.publish(msg)

        self.get_logger().info(f'Publishing: "{msg.data}"')

        self.i += 1


def main(args=None):

    rclpy.init(args=args)

    node = MinimalPublisher()

    rclpy.spin(node)

    node.destroy_node()

    rclpy.shutdown()

The subscriber node follows a similar structure but creates a subscription instead of a publisher. The subscription callback executes whenever a message arrives on the subscribed topic.

python

class MinimalSubscriber(Node):

    def __init__(self):

        super().__init__('minimal_subscriber')

        self.subscription = self.create_subscription(

            String, 'topic', self.listener_callback, 10)


    def listener_callback(self, msg):

        self.get_logger().info(f'I heard: "{msg.data}"')

After writing the code, update the package configuration to declare these scripts as executable entry points. Build your workspace with colcon and source the updated environment.

bash

cd ~/ros2_ws

colcon build --packages-select my_first_package

source install/setup.bash

Run your nodes in separate terminals to see them communicate. The publisher sends messages that the subscriber receives and displays.

bash

# Terminal 1

ros2 run my_first_package publisher


# Terminal 2  

ros2 run my_first_package subscriber

For comprehensive examples and starter code for various robotics platforms, explore Think Robotics' software examples repository featuring ROS2 implementations.

Working with Services, Parameters, and Launch Files

While topics handle streaming data, services provide request-response communication for operations that need acknowledgment or return values. A service client sends a request and waits for the response from the service server. This synchronous pattern suits tasks like triggering actions, querying state, or performing calculations.

Services use service types that define both the request structure and response structure. Creating a service server involves writing a callback function that processes requests and generates responses.

python

from example_interfaces.srv import AddTwoInts


class MinimalService(Node):

    def __init__(self):

        super().__init__('minimal_service')

        self.srv = self.create_service(AddTwoInts, 'add_two_ints', self.add_callback)


    def add_callback(self, request, response):

        response.sum = request.a + request.b

        self.get_logger().info(f'Request: {request.a} + {request.b} = {response.sum}')

        return response

Calling services from the command line helps test service functionality without writing client code.

bash

ros2 service call /add_two_ints example_interfaces/srv/AddTwoInts "{a: 5, b: 7}"

Parameters provide a mechanism for configuring node behavior without modifying code. Nodes declare parameters with names, types, and default values. External tools or launch files can set parameter values, allowing the same node to behave differently in various contexts.

bash

ros2 param list /turtlesim

ros2 param get /turtlesim background_r

ros2 param set /turtlesim background_r 255

Launch files coordinate starting multiple nodes with specified parameters and configurations. Rather than manually launching each node in separate terminals, launch files automate system startup. They can remap topic names, set parameters, and define relationships between nodes.

Next Steps in Your ROS2 Journey

The ROS2 package ecosystem contains thousands of pre-built components covering common robotics needs. Before implementing functionality yourself, search for existing packages that might already solve your problem. Popular packages like nav2 for navigation, MoveIt for manipulation planning, and cv_bridge for image processing save months of development time.

Simulation environments provide safe spaces to develop and test robot code before deploying to real hardware. Gazebo offers high-fidelity physics simulation with sensor models and visualization. Integration between ROS2 and Gazebo allows running the same code in simulation and on physical robots, dramatically accelerating development cycles.

Continuing your ROS2 education involves tackling progressively more complex projects. After mastering the basics covered here, explore navigation stacks for mobile robots, manipulation planning for robotic arms, or perception pipelines for computer vision tasks. The ROS2 documentation includes comprehensive tutorials with working code examples.

The robotics community provides extensive support for ROS2 learners. The ROS Discourse forum hosts discussions on technical questions and implementation strategies. Online courses from educational platforms offer structured learning paths with hands-on exercises.

Think Robotics supplies complete robot kits designed for ROS2 development, providing the hardware foundation for translating tutorial knowledge into working systems.

Post a comment

Frequently Asked Questions Frequently Asked Questions

Frequently Asked Questions

Do I need to know ROS1 before learning ROS2?

No, beginners can start directly with ROS2 without prior ROS1 knowledge. While some concepts carry over, ROS2 represents a significant architectural redesign. Most new robotics projects use ROS2, making it the more valuable skill to develop.

What programming languages does ROS2 support?

ROS2 primarily supports Python and C++. Python offers faster development and easier debugging, making it popular for prototyping. C++ provides better performance for computationally intensive tasks like real-time control and image processing.

Can ROS2 run on Raspberry Pi or embedded systems?

Yes, ROS2 runs on various embedded platforms including Raspberry Pi and NVIDIA Jetson. Performance depends on the specific hardware and computational requirements. ROS2's distributed architecture supports splitting computation across multiple devices.

How does ROS2 handle real-time control requirements?

ROS2 includes real-time capabilities when used with appropriate operating systems and configurations. However, achieving true real-time performance requires careful system design. Many industrial robots combine ROS2 for high-level planning with dedicated real-time controllers for low-level motor control.

What's the difference between ROS2 topics and services?

Topics provide asynchronous streaming communication where publishers send data without waiting for acknowledgment. Services offer synchronous request-response patterns where clients send requests and wait for responses. Use topics for continuous data streams and services for occasional operations that need confirmation.