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/srcros2 pkg create --build-type ament_python --license Apache-2.0 py_pubsub
Write the publisher node
cd py_pubsub/py_pubsubwget https://raw.githubusercontent.com/ros2/examples/humble/rclpy/topics/minimal_publisher/examples_rclpy_minimal_publisher/publisher_member_function.py
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 locatednano 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 subscriber’s callback gets called as soon as it receives a message
cd py_pubsubwget https://raw.githubusercontent.com/ros2/examples/humble/rclpy/topics/minimal_subscriber/examples_rclpy_minimal_subscriber/subscriber_member_function.py
subscriber_member_function.py
import rclpyfrom rclpy.node import Nodefrom std_msgs.msg import Stringclass MinimalSubscriber(Node): def __init__(self): super().__init__('minimal_subscriber') self.subscription = self.create_subscription( String, 'topic', self.listener_callback, 10) self.subscription # prevent unused variable warning def listener_callback(self, msg): self.get_logger().info('I heard: "%s"' % msg.data)def main(args=None): rclpy.init(args=args) minimal_subscriber = MinimalSubscriber() rclpy.spin(minimal_subscriber) # Destroy the node explicitly # (optional - otherwise it will be done automatically # when the garbage collector destroys the node object) minimal_subscriber.destroy_node() rclpy.shutdown()if __name__ == '__main__': main()
Add the entry point for the subscriber node below the publisher’s entry point