Blog

cmd_vel Explained: From a Twist Message to Wheels Actually Turning

Tom Cosgrove,

Reading Room: The Fictionlab Blog

TL;DR: In ROS 2, cmd_vel is a conventional topic name for desired robot-base velocity commands. Depending on the stack configuration, it carries a geometry_msgs/msg/Twist or geometry_msgs/msg/TwistStamped message. A motor controller node subscribes to it, runs inverse kinematics for the drivetrain (differential, skid-steer, Ackermann, or omni), may apply velocity and acceleration limits, and sends per-wheel setpoints to the motor drivers. Publishing a Twist by itself does nothing until a controller listens on the correct namespace, receives messages within its safety timeout, and the drivetrain is enabled. This article walks through the full path from a ros2 topic pub command to a spinning wheel, with examples for the Leo Rover.

What cmd_vel Is in ROS 2 and Why It Matters

The cmd_vel ros 2 twist convention is a widely used interface between high-level navigation software and the mobile base. Nodes that plan or teleoperate motion (Nav2, teleop_twist_keyboard, a custom behavior tree, or a joystick bridge) commonly publish velocity commands on /cmd_vel or a namespaced equivalent. A base driver subscribes to that command topic. This decoupling is what lets you swap a Leo Rover for another mobile base, or a simulated robot for a real one, without rewriting the navigation stack.

The message itself is small. geometry_msgs/msg/Twist contains two Vector3 fields:

  • linear.x, linear.y, linear.z – translational velocity in meters per second.
  • angular.x, angular.y, angular.z – rotational velocity in radians per second around the base axes.

The reference frame is a convention established by the publisher and subscriber; for mobile bases it is normally the robot base frame. For a ground robot with a differential drive, only linear.x (forward/backward) and angular.z (yaw rate) are normally used. A holonomic platform also uses linear.y. Other components may be ignored or rejected by the controller.

ROS 2 stacks increasingly use geometry_msgs/msg/TwistStamped, which wraps a Twist with a header containing a timestamp and frame ID. Nav2 in Jazzy and newer uses stamped velocity commands by default, allowing receivers to use the command timestamp when handling stale commands.

How the Path from Twist to Wheel Rotation Actually Works

Between the publisher and the physical motor, several stages can happen. Understanding each one is what separates “my robot won’t move” from a working system.

1. Topic and Namespace

The publisher writes to a topic, typically /cmd_vel. The base driver subscribes to the same topic. If either side is inside a namespace (for example /leo/cmd_vel) and the other is not, no messages arrive. This is a common beginner mistake. Check with:

ros2 topic info /cmd_vel --verbose

You should see at least one publisher and one subscriber with compatible message types and QoS settings. A common cmd_vel QoS profile is reliable, volatile, with a depth of 10, but the actual settings depend on the nodes involved.

2. The Base Controller Node

On the Leo Rover, the firmware and ROS bringup components provide the interface between velocity commands and the drivetrain. On other platforms this might be ros2_control with a DiffDriveController, AckermannSteeringController, or a custom node. Depending on the implementation, the controller may:

  1. Validate and clip the incoming velocity command against configured limits.
  2. Run inverse kinematics to convert body velocities into per-wheel angular velocities.
  3. Send setpoints to motor drivers, which may close a local PID loop on wheel speed.

3. Differential and Skid-Steer Kinematics

The Leo Rover uses a four-wheel skid-steer drive, which can be modeled as a differential drive for control purposes. The inverse kinematics for the left and right wheel angular velocities are:

ω_left = (v_x - ω_z * b / 2) / r
ω_right = (v_x + ω_z * b / 2) / r

where v_x is linear.x in m/s, ω_z is angular.z in rad/s, b is the effective track width in meters, and r is the wheel radius. Use the wheel radius and track-width values configured for the specific robot model and controller. For skid-steer vehicles, the effective track width is often empirically larger than the geometric track width because of wheel slip.

4. Velocity and Acceleration Limits

A well-behaved controller commonly enforces:

  • Maximum linear velocity.
  • Maximum angular velocity.
  • Acceleration limits to protect the drivetrain and reduce abrupt motion.
  • A command timeout. If no new Twist arrives within the configured window, the controller commands zero velocity. This is a safety feature, not a bug.

The exact limits and timeout are controller- and configuration-dependent. Check the Leo Rover firmware and ROS 2 configuration for the values used by a particular robot.

How to Publish cmd_vel from the Command Line

The fastest way to test whether your base driver is alive is ros2 topic pub. Move forward at 0.2 m/s:

ros2 topic pub /cmd_vel geometry_msgs/msg/Twist "{linear: {x: 0.2, y: 0.0, z: 0.0}, angular: {x: 0.0, y: 0.0, z: 0.0}}" -r 10

The -r 10 flag republishes at 10 Hz, which keeps a typical safety timeout satisfied. Without it, ros2 topic pub publishes once and exits, so the robot stops after the timeout expires.

To rotate in place at 0.5 rad/s:

ros2 topic pub /cmd_vel geometry_msgs/msg/Twist "{linear: {x: 0.0}, angular: {z: 0.5}}" -r 10

To stop cleanly, send zeros:

ros2 topic pub --once /cmd_vel geometry_msgs/msg/Twist "{linear: {x: 0.0}, angular: {z: 0.0}}"

How to Publish cmd_vel from Python (rclpy)

For anything beyond a smoke test, you want a proper node. Here is a minimal publisher that drives a square pattern:

import rclpy
from rclpy.node import Node
from geometry_msgs.msg import Twist

class SquareDriver(Node):
    def __init__(self):
        super().__init__('square_driver')
        self.pub = self.create_publisher(Twist, 'cmd_vel', 10)
        self.timer = self.create_timer(0.1, self.tick)
        self.t0 = self.get_clock().now()

    def tick(self):
        elapsed = (self.get_clock().now() - self.t0).nanoseconds / 1e9
        phase = int(elapsed) % 8
        msg = Twist()
        if phase < 4:
            msg.linear.x = 0.2
        else:
            msg.angular.z = 0.392699
        self.pub.publish(msg)

def main():
    rclpy.init()
    rclpy.spin(SquareDriver())

if __name__ == '__main__':
    main()

Notice the topic is cmd_vel without a leading slash. That way the node inherits any namespace applied at launch, which is portable across single-robot and multi-robot setups.

What Common Mistakes Break cmd_vel in Practice

These are the failure modes that show up on forums and support tickets, day after day, on Leo Rover and every other mobile base:

  • Wrong namespace. Your publisher writes to /cmd_vel but the driver subscribes to /leo/cmd_vel. Use ros2 topic list and ros2 topic info to verify. Set namespaces consistently in launch files.
  • No repeat rate. Safety timeouts stop the robot if commands stop arriving. Publish regularly for continuous motion; 10 Hz is commonly sufficient when the controller timeout is 0.5 s.
  • Twist vs TwistStamped mismatch. Nav2 in newer distributions publishes TwistStamped. If your base driver only subscribes to Twist, configure Nav2 for the message type supported by the driver or use an adapter that converts in the required direction.
  • QoS incompatibility. If a publisher uses BEST_EFFORT and the subscriber requires RELIABLE, no messages flow. Ensure the publisher and subscriber use compatible QoS profiles.
  • Motors not enabled. An emergency stop, a hardware fault, a motor-power issue, or an incomplete bringup sequence can prevent motion even when cmd_vel messages arrive. Check diagnostics and the robot’s hardware status.
  • Exceeding velocity limits. Sending a command beyond the configured maximum usually causes saturation or rejection. It will not make the robot go faster and may hide bugs in your controller tuning.
  • Multiple publishers. Teleop and Nav2 both publishing to /cmd_vel can produce jittery motion. Use a twist_mux node, or another command-arbitration mechanism compatible with your message type, to manage priorities.

How cmd_vel Fits into Larger Systems

Once the base responds to Twist reliably, everything else in the ROS 2 ecosystem plugs in. Nav2 publishes velocity commands from its controller server. SLAM Toolbox and robot_localization can consume odometry that the base publishes on /odom, closing the loop. Teleoperation nodes, gamepads over joy, web dashboards, and behavior trees can all use the same velocity-command interface. This is why cmd_vel is one of the first things to verify on a new robot. It is also why platforms used in robotics education lean on it: students can drive a real robot from a short publisher and then graduate to autonomous navigation without changing the base driver.

FAQ

What is the difference between Twist and TwistStamped?

Twist is just the velocity vectors. TwistStamped adds a std_msgs/Header with a timestamp and a frame ID, allowing subscribers to use the timestamp when detecting stale commands and to identify the declared reference frame. Nav2 in recent releases uses TwistStamped by default.

Why does my robot stop moving after half a second?

The base controller likely has a safety timeout. If no new cmd_vel arrives within its configured timeout window, it commands zero velocity. Publish regularly for continuous motion; ros2 topic pub -r 10 is suitable for a typical 0.5 s timeout.

Can I publish negative velocities?

Yes. Negative linear.x drives the robot backward, and negative angular.z rotates clockwise when positive z points upward under the usual ROS coordinate convention. The controller will clip or reject commands according to its configured limits.

How do I know which topic name to use?

Run ros2 topic list after starting the base driver. Look for cmd_vel under the robot’s namespace. On the Leo Rover default configuration, it is /cmd_vel. Use ros2 topic info /cmd_vel --verbose to confirm a subscriber exists.

What if I have two nodes trying to publish cmd_vel?

Use twist_mux, or another compatible command multiplexer, to arbitrate multiple velocity command sources by priority and timeout. A typical setup gives the joystick higher priority than Nav2, while a virtual bumper can override both with zero commands.

Does cmd_vel work in simulation?

Yes. Gazebo and other simulators can provide differential-drive controllers or plugins that subscribe to cmd_vel in the same way as a real base driver. In some simulators, including Isaac Sim, this may require configuring the appropriate controller graph or ROS 2 bridge. The navigation code can then use the same velocity-command interface for physical and simulated robots.

Why does my robot drift when I command pure angular velocity?

Skid-steer platforms slip. The relationship between commanded angular.z and actual yaw rate depends on surface friction, wheel wear, and payload. Calibrating the effective track width or using closed-loop yaw control from an IMU improves accuracy.

Next Steps

For working launch files, wiring diagrams, and the full ROS 2 API of the Leo Rover base, see the official documentation at docs.fictionlab.pl. It covers namespace conventions, twist_mux configuration, and the velocity limits enforced by the firmware, so you can go from a first ros2 topic pub to a fully autonomous mission without guesswork.


Read more