ROS 2 Humble Beginner Lesson

Create Workspace, Package, Nodes (Publisher/Subscriber)

Overview

This tutorial covers:

  • Setting up a ROS 2 workspace
  • Creating a Python package
  • Writing a publisher and subscriber node
  • Building and running your package

1. Create a ROS 2 Workspace

A workspace is where you organize your ROS 2 packages.

Step 1: Create a workspace directory.

mkdir -p ~/ros2_ws/src

Step 2: Navigate to the workspace.

cd ~/ros2_ws

Step 3: Initialize the workspace.

colcon build

Step 4: Source the workspace.

source install/setup.bash

Now, you’re ready to create your first package.


2. Create a ROS 2 Python Package

Step 1: Navigate to the src directory.

cd ~/ros2_ws/src

Step 2: Create the package.

ros2 pkg create --build-type ament_python my_python_pkg

This creates the package structure including package.xml and setup.py.


3. Create Publisher and Subscriber Nodes

Publisher Node

Step 1: Create the folder for the Python node.

mkdir -p ~/ros2_ws/src/my_python_pkg/my_python_pkg

Step 2: Create the simple_publisher.py file.

touch ~/ros2_ws/src/my_python_pkg/my_python_pkg/simple_publisher.py

Publisher Code

Step 3: Add this code to simple_publisher.py:

import rclpy
from rclpy.node import Node
from std_msgs.msg import String
 
class SimplePublisher(Node):
    def __init__(self):
        super().__init__('simple_publisher')
        self.publisher_ = self.create_publisher(String, 'topic', 10)
        self.timer = self.create_timer(0.5, self.publish_message)
 
    def publish_message(self):
        msg = String()
        msg.data = 'Hello, ROS 2!'
        self.publisher_.publish(msg)
        self.get_logger().info(f'Publishing: {msg.data}')
 
def main(args=None):
    rclpy.init(args=args)
    node = SimplePublisher()
    rclpy.spin(node)
    node.destroy_node()
    rclpy.shutdown()
 
if __name__ == '__main__':
    main()

Subscriber Node

Step 1: Create the subscriber file.

touch ~/ros2_ws/src/my_python_pkg/my_python_pkg/simple_subscriber.py

Step 2: Add the following code to simple_subscriber.py:

import rclpy
from rclpy.node import Node
from std_msgs.msg import String
 
class SimpleSubscriber(Node):
    def __init__(self):
        super().__init__('simple_subscriber')
        self.subscription = self.create_subscription(
            String,
            'topic',
            self.listener_callback,
            10
        )
        self.subscription
 
    def listener_callback(self, msg):
        self.get_logger().info(f'Received: {msg.data}')
 
def main(args=None):
    rclpy.init(args=args)
    node = SimpleSubscriber()
    rclpy.spin(node)
    node.destroy_node()
    rclpy.shutdown()
 
if __name__ == '__main__':
    main()

4. Update setup.py

Step 1: Open setup.py in the my_python_pkg package.

nano ~/ros2_ws/src/my_python_pkg/setup.py

Step 2: Modify the entry_points section:

entry_points={
    'console_scripts': [
        'simple_publisher = my_python_pkg.simple_publisher:main',
        'simple_subscriber = my_python_pkg.simple_subscriber:main',
    ],
},

5. Build the Package

Step 1: Navigate to your workspace.

cd ~/ros2_ws

Step 2: Build the package.

colcon build

Step 3: Source the workspace.

source install/setup.bash

6. Running the Nodes

Step 1: In one terminal, run the publisher node.

ros2 run my_python_pkg simple_publisher

Step 2: In another terminal, run the subscriber node.

ros2 run my_python_pkg simple_subscriber

You should see messages being published and received.


Explanation

  • Node: A process that performs computation in ROS 2.
  • Publisher: A node that sends messages to a topic.
  • Subscriber: A node that listens to messages from a topic.
  • Topic: A communication channel in ROS 2.

Role of setup.py

In a ROS 2 Python package, setup.py defines:

  • Package metadata: Name, version, description, author, etc.
  • Dependencies: Ensures Python dependencies are installed.
  • Entry points: Registers Python functions as executables (like nodes).

Structure of setup.py

Here’s the breakdown of the important sections:

from setuptools import setup
 
package_name = 'my_python_pkg'
 
setup(
    name=package_name,
    version='0.0.0',
    packages=[package_name],
    data_files=[
        ('share/ament_index/resource_index/packages',
         ['resource/' + package_name]),
        ('share/' + package_name, ['package.xml']),
    ],
    install_requires=['setuptools'],
    zip_safe=True,
    maintainer='your_name',
    maintainer_email='[email protected]',
    description='My Python package for ROS 2',
    license='License declaration',
    tests_require=['pytest'],
    entry_points={
        'console_scripts': [
            'simple_publisher = my_python_pkg.simple_publisher:main',
            'simple_subscriber = my_python_pkg.simple_subscriber:main',
        ],
    },
)

/setup.py Explanation

The /setup.py file is located in your package’s root folder and tells ROS 2 how to:

  1. Build and Install the package.
  2. Register Executable Nodes so they can be run with ros2 run <package> <node>.


And as always we are free as in freedom

tech_leef