ROS2 Programming Basics Using Python

Written by 박진석

22/08/2024

What we are going to learn:

How to send a message using Topic Publisher and Subscriber using Python

To ensure stability, I’ll guide you through ROS2 Foxy on Ubuntu 20.04 system. I’ll be using Docker images for installation, but the process is similar to a local Ubuntu setup.

Prerequisites:

Ubuntu 20.04 installed on your computer.

We will actually create and run a ROS2 package that sends and receives messages through Publisher and Subscriber.

If you want to learn ROS 2 Python in a practical, hands-on way, check out the course ROS 2 Basics in 5 Days: https://app.theconstruct.ai/courses/132

In this course, you’ll cover the foundational concepts needed to start working with ROS 2, as well as more advanced topics, all while engaging in hands-on practice.

1. Make Package:


The command to create a package is as follows:

ros2 pkg create [package_name] --build-type [build_type] --dependencies [dependent package1][dependent package2]

Lets’ make ros2_ws and create the ros_topic_pkg package

mkdir ~/ros2_ws/src
cd ~/ros2_ws/src
ros2 pkg create ros_topic_pkg --build-type ament_python --dependencies rclpy std_msgs

2. Write Publisher and Subscriber script

Firstly, we will make empty script publisher.py, subscriber.py in ros_topic_pkg_folder

cd ~/ros2_ws/src/ros_topic_pkg/ros_topic_pkg
touch publisher.py
touch subscriber.py

After make empty script, Using Vim or VsCode, write down this publisher and subscriber code

publihser.py
import rclpy
from rclpy.node import Node
from rclpy.qos import QoSProfile
from std_msgs.msg import String

class Publisher(Node):
def __init__(self):
super().__init__('Publisher')
qos_profile = QoSProfile(depth=10)
self.publisher = self.create_publisher(String, 'topic', qos_profile)
self.timer = self.create_timer(1, self.publish_msg)
self.count = 0

def publish_msg(self):
msg = String()
msg.data = 'Number: {0}'.format(self.count)
self.publisher.publish(msg)
self.get_logger().info('Published message: {0}'.format(msg.data))
self.count += 1

def main(args=None):
rclpy.init(args=args)
node = Publisher()
try:
rclpy.spin(node)
except KeyboardInterrupt:
node.get_logger().info('Keyboard Interrupt')
finally:
node.destroy_node()
rclpy.shutdown()

if __name__ == '__main__':
main()

subscriber.py
import rclpy
from rclpy.node import Node
from rclpy.qos import QoSProfile
from std_msgs.msg import String​

class Subscriber(Node):

def __init__(self):
super().__init__('Subscriber')
qos_profile = QoSProfile(depth=10)
self.subscriber = self.create_subscription(
String,
'topic',
self.subscribe_topic_message,
qos_profile)

def subscribe_topic_message(self, msg):
self.get_logger().info('Received message: {0}'.format(msg.data))​

def main(args=None):
rclpy.init(args=args)
node = Subscriber()
try:
rclpy.spin(node)
except KeyboardInterrupt:
node.get_logger().info('Keyboard Interrupt')
finally:
node.destroy_node()
rclpy.shutdown()​

if __name__ == '__main__':
main()


3. Write a Python package configuration file

Lastly, we have to write down this setup.py file to build Ros2 package

from setuptools import find_packages, setup

package_name = 'ros_topic_pkg'

setup(
name=package_name,
version='0.0.0',
packages=find_packages(exclude=['test']),
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='user',
maintainer_email='user@todo.todo',
description='TODO: Package description',
license='TODO: License declaration',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'publisher = ros_topic_pkg.publisher:main',
'subscriber = ros_topic_pkg.subscriber:main'
],
},
)

4 Build package:

If you write down all the code correctly, Now we will build ros2_topic pkg

cd ~/ros2_ws && colcon build --symlink-install

If the build is completely normal, you must load the configuration file and set the node for the executable package to run the build node

You can see the file that writes a lot of commands, at the end of the file, Input i to change insert mode and write
source install/setup.bash

Now let’s run the publisher and subscriber we created

First, run publisher to issue a topic

ros2 run ros_topic_pkg publisher

Then Run a new terminal and run the Subscriber after proceeding with the configuration file load

source install/setup.bash


If you wrote the code correctly, you can see that the subscriber is properly subscribing to the numbers issued by the publisher.

Congratulations. You have now learned how to send a message using Topic Publisher and Subscriber using Python.

To learn more about ROS 2, have a look at the course below:

We hope this tutorial was really helpful to you.

This tutorial is created by Robotics Ambassador Park.

Masterclass 2023 batch2 blog banner

Check Out These Related Posts

0 Comments

Pin It on Pinterest

Share This