Skip to main content

Section 10.2 Writing ROS 2 Publishers

To create a publisher in Python, we inherit from rclpy.node.Node, initialize our publisher on a specific topic, and set up a timer to trigger message publishing at a regular frequency.

Subsection 10.2.1 Key Components of a Publisher Node

  1. Node Initialization: Calling super().__init__('node_name') registers the node name with the ROS graph.
  2. create_publisher(): Specifies the message class type, topic name, and Quality of Service (QoS) queue size.
  3. create_timer(): Sets a period (in seconds) and links it to a timer callback method that executes periodically.
import rclpy
from rclpy.node import Node
from geometry_msgs.msg import Twist

class VelocityPublisher(Node):
    def __init__(self):
        super().__init__('velocity_publisher')
        # Create publisher on topic 'cmd_vel' with queue size 10
        self.publisher_ = self.create_publisher(Twist, 'cmd_vel', 10)
        # Create a timer firing every 0.5 seconds (2 Hz)
        self.timer = self.create_timer(0.5, self.timer_callback)

    def timer_callback(self):
        msg = Twist()
        msg.linear.x = 0.2   # Drive forward at 0.2 m/s
        msg.angular.z = 0.0  # No rotation
        self.publisher_.publish(msg)
        self.get_logger().info('Publishing velocity command!')

Subsection 10.2.2 Section 10.2 Interactive Exercises

Subsubsection 10.2.2.1 Exercise 10.2.1: Parsons Problem β€” Assemble a Minimal ROS 2 Publisher

Reorder the lines below to construct a complete, functional Python ROS 2 publisher node that publishes velocity commands to the cmd_vel topic and spins the node.

Checkpoint 10.2.1.

Arrange the blocks to form a complete CmdVelPublisher node and a main() function that initializes it, spins it, and shuts it down.
You have attempted of activities on this page.