Writing a simple publisher and subscriber in ROS2 creates nodes that pass information to each other over a topic. In this simple example, you will be creating a “talker” and “listener” that pass information in the form of a string message. One node publishes data and the other subscribes to the topic so that it can receive that data.
All nodes should be written in the scripts folder of your package. In this example, the package name is ros_basics
. Instructions on creating a package can be found in a. Creating a package. Navigate to the appropriate folder of your ros_basics
package.
cd ~/humble_ws/src/ros_basics/ros_basics/
Download the example talker code by entering the following command:
wget <https://raw.githubusercontent.com/ros2/examples/humble/rclpy/topics/minimal_publisher/examples_rclpy_minimal_publisher/publisher_member_function.py>
Now there will be a new file named publisher_member_function.py
adjacent to __init__.py
.
Video
Open the file using VS Code or your preferred text editor.
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)
timer_period = 0.5 # seconds
self.timer = self.create_timer(timer_period, self.timer_callback)
self.i = 0
def timer_callback(self):
msg = String()
msg.data = 'Hello World: %d' % self.i
self.publisher_.publish(msg)
self.get_logger().info('Publishing: "%s"' % msg.data)
self.i += 1
def main(args=None):
rclpy.init(args=args)
minimal_publisher = MinimalPublisher()
rclpy.spin(minimal_publisher)
# Destroy the node explicitly
# (optional - otherwise it will be done automatically
# when the garbage collector destroys the node object)
minimal_publisher.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
The first lines of code after the comments import rclpy
and the Node
class from the rclpy.node
library. rclpy
is the ROS Client Library Python, this allows the ROS predefined functions to be used in your code.
import rclpy
from rclpy.node import Node
The next statement imports the built-in string messages type that the node uses to structure the data that it passes on the topic.
from std_msgs.msg import String
<aside> 💡 This message importing will be used frequently when creating ROS nodes. Common ROS message types can be found here.
</aside>
These lines represent the node’s dependencies. Recall that dependencies have to be added to package.xml
, which you’ll do in the next section.