you will create nodes that pass information in the form of string messages to each other over a topic. The example used here is a simple “talker” and “listener” system; one node publishes data and the other subscribes to the topic so it can receive that data.

The code used in these examples can be found here.

  • Create a package
cd ros2_ws/src
ros2 pkg create --build-type ament_python --license Apache-2.0 py_pubsub
  • Write the publisher node
cd py_pubsub/py_pubsub
wget https://raw.githubusercontent.com/ros2/examples/humble/rclpy/topics/minimal_publisher/examples_rclpy_minimal_publisher/publisher_member_function.py
  • Add dependencies
  • Open the package.xml file to add the dependencies
    • In this step, you will declare that your package depends on rclpy and std_msgs to run.
cd ..  # Navigate to the parent directory where your package.xml is located
nano package.xml  # Open the file in nano editor
# Add the following lines
<exec_depend>rclpy</exec_depend>
<exec_depend>std_msgs</exec_depend>
  • Add an entry point
    • Add 'talker = py_pubsub.publisher_member_function:main' within the console_scripts brackets
  • The contents of the setup.cfg file should be correctly populated automatically
    • This tells setuptools to put your executables in lib, because ros2 run will look for them there.
[develop]
script_dir=$base/lib/py_pubsub
[install]
install_scripts=$base/lib/py_pubsub
  • Write the subscriber node
    • The subscriber’s callback gets called as soon as it receives a message
cd py_pubsub
wget https://raw.githubusercontent.com/ros2/examples/humble/rclpy/topics/minimal_subscriber/examples_rclpy_minimal_subscriber/subscriber_member_function.py
  • Add the entry point for the subscriber node below the publisher’s entry point
entry_points={
        'console_scripts': [
                'talker = py_pubsub.publisher_member_function:main',
                'listener = py_pubsub.subscriber_member_function:main',
        ],
},
  • Check for missing dependencies before building
rosdep install -i --from-path src --rosdistro humble -y
  • Build
# cd into ros2_ws
colcon build --packages-select py_pubsub
  • Run the talker node in a new terminal
source install/setup.bash
ros2 run py_pubsub talker
[INFO] [minimal_publisher]: Publishing: "Hello World: 0"
[INFO] [minimal_publisher]: Publishing: "Hello World: 1"
[INFO] [minimal_publisher]: Publishing: "Hello World: 2"
[INFO] [minimal_publisher]: Publishing: "Hello World: 3"
[INFO] [minimal_publisher]: Publishing: "Hello World: 4"
...
  • Run the listener node in another terminal
source install/setup.bash
ros2 run py_pubsub listener
[INFO] [minimal_subscriber]: I heard: "Hello World: 10"
[INFO] [minimal_subscriber]: I heard: "Hello World: 11"
[INFO] [minimal_subscriber]: I heard: "Hello World: 12"
[INFO] [minimal_subscriber]: I heard: "Hello World: 13"
[INFO] [minimal_subscriber]: I heard: "Hello World: 14"
rqt_graph

Recap: Useful commands