Loading the lesson...
In the print dialog, choose "Save as PDF" as the destination.
ROS 2 Practical - Lesson 2
The pub/sub model in practice
Publisher
sends messages
Topic
Subscriber
receives messages
Worked Example
/chatter/chatter and prints what it receivesros2 run demo_nodes_py talker
ros2 run demo_nodes_py listenerros2 topic list
ros2 topic echo /chatterturtlesim gives a graphical way to see pub/sub in actionros2 run turtlesim turtlesim_node
ros2 run turtlesim turtle_teleop_keyturtle_teleop_key
publishes velocity commands
/turtle1/cmd_vel
turtlesim_node
moves the turtle
ros2 topic list
ros2 topic echo /turtle1/cmd_vel
ros2 topic info /turtle1/cmd_vel
ros2 interface show geometry_msgs/msg/Twistros2 topic info shows the message type plus publisher/subscriber countsTwistx, y, z) plus angular velocity (x, y, z), all float64package.xml: rclpy, geometry_msgs, turtlesimTwist messages on a timer to move the turtle in a circleclass DrawCircleNode(Node):
def __init__(self):
super().__init__("draw_circle")
self.cmd_vel_pub = self.create_publisher(Twist, "/turtle1/cmd_vel", 10)
self.timer = self.create_timer(0.5, self.send_velocity_command)
def send_velocity_command(self):
msg = Twist()
msg.linear.x = 2.0
msg.angular.z = 1.0
self.cmd_vel_pub.publish(msg)create_publisher + create_timer = periodic publishing.turtlesim/msg/Pose/turtle1/pose: x, y, theta, linear_velocity, angular_velocitypackage.xml: rclpy, turtlesimclass PoseSubscriberNode(Node):
def __init__(self):
super().__init__("pose_subscriber")
self.subscription = self.create_subscription(
Pose, "/turtle1/pose", self.pose_callback, 10)
def pose_callback(self, msg):
self.get_logger().info(
f"x: {msg.x}, y: {msg.y}, theta: {msg.theta}")create_subscription + a callback = reacting to incoming messages.colcon build --symlink-install
source install/setup.bash
ros2 run my_first_py_pkg draw_circle
ros2 run my_first_py_pkg pose_subscriber # separate terminalrqt_graph shows nodes and topic connections visuallyrqt_graph
ros2 topic list
ros2 topic echo /topicros2 topic info + ros2 interface show reveal a topic's message type and structurecreate_publisher + create_timer = periodic publishingcreate_subscription + a callback = reacting to incoming messagessetup.py before running themrqt_graph and ros2 topic echo are essential for debugging pub/subMahmoud Abas|ROS 2 Topics, Publisher, and Subscriber Nodes