Arrange the blocks to form a complete
CmdVelPublisher node and a main() function that initializes it, spins it, and shuts it down.
rclpy.node.Node, initialize our publisher on a specific topic, and set up a timer to trigger message publishing at a regular frequency.
super().__init__('node_name') registers the node name with the ROS graph.
create_publisher(): Specifies the message class type, topic name, and Quality of Service (QoS) queue size.
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!')
cmd_vel topic and spins the node.
CmdVelPublisher node and a main() function that initializes it, spins it, and shuts it down.