Skip to content
Build GuidesNovember 18, 2026Intermediate

ros2_control for a Differential-Drive Robot in Gazebo Harmonic (Jazzy)

RTJ Editor
RoboTechJournal Contributor
Contents1. Install the Jazzy controller tools

When you want to exercise the ROS controller stack rather than just move a robot in Gazebo, let diff_drive_controller own the wheel velocity commands. In this example, gz_ros2_control connects the simulated joints to the controller manager. The joint-state broadcaster publishes feedback and the drive controller publishes odometry. Only the simulation clock needs a Gazebo-to-ROS bridge.

Source package: Get the controller configuration, model and launch files from the ros2_control differential-drive source package on GitHub. The example was checked in headless simulation, not on physical hardware.

You can add these files to an existing rtj_diffbot package or build the example from scratch below. Stop any other simulation of the same robot first so the controllers, clock and frames are not competing. For a refresher on topic types and overlays, see the ROS 2 beginner’s guide.

1. Install the Jazzy controller tools

These commands assume an Ubuntu 24.04 system with the ROS 2 Jazzy apt repository configured. ros-jazzy-ros2controlcli provides the ros2 control inspection commands used below.

bash
sudo apt updatesudo apt install python3-colcon-common-extensions python3-rosdep \  ros-jazzy-ros-base ros-jazzy-ros-gz ros-jazzy-xacro \  ros-jazzy-gz-ros2-control ros-jazzy-ros2-controllers \  ros-jazzy-ros2controlcli
bash
source /opt/ros/jazzy/setup.bashmkdir -p ~/rtj_ws/src/rtj_diffbot/{config,launch,urdf,worlds}cd ~/rtj_ws/src/rtj_diffbot

Save these two files at the package root. The manifest covers both tutorial variants, including the Python launch APIs and the message packages used by the bridges. Fill in your maintainer details and choose the applicable license before distributing your own package.

package.xml

xml
<?xml version="1.0"?><package format="3">  <name>rtj_diffbot</name>  <version>0.1.0</version>  <description>Differential-drive robot simulation smoke test</description>  <maintainer email="maintainer@example.invalid">Maintainer TBD</maintainer>  <license>TODO: choose a license before distributing your package</license>  <buildtool_depend>ament_cmake</buildtool_depend>  <exec_depend>ament_index_python</exec_depend>  <exec_depend>controller_manager</exec_depend>  <exec_depend>diff_drive_controller</exec_depend>  <exec_depend>gz_ros2_control</exec_depend>  <exec_depend>joint_state_broadcaster</exec_depend>  <exec_depend>geometry_msgs</exec_depend>  <exec_depend>launch</exec_depend>  <exec_depend>launch_ros</exec_depend>  <exec_depend>nav_msgs</exec_depend>  <exec_depend>ros_gz_bridge</exec_depend>  <exec_depend>ros_gz_sim</exec_depend>  <exec_depend>ros2controlcli</exec_depend>  <exec_depend>robot_state_publisher</exec_depend>  <exec_depend>rosgraph_msgs</exec_depend>  <exec_depend>sensor_msgs</exec_depend>  <exec_depend>tf2_msgs</exec_depend>  <exec_depend>tf2_tools</exec_depend>  <exec_depend>teleop_twist_keyboard</exec_depend>  <exec_depend>xacro</exec_depend>  <export><build_type>ament_cmake</build_type></export></package>

CMakeLists.txt

cmake
cmake_minimum_required(VERSION 3.8)project(rtj_diffbot) find_package(ament_cmake REQUIRED) install(DIRECTORY config launch urdf worlds  DESTINATION share/${PROJECT_NAME}) ament_package()

CMake installs the model, world, configuration and launch directories into the package share directory. Rebuild after editing these source files so the launch sees the installed versions.

worlds/rtj_world.sdf

The world supplies a ground plane and a static obstacle. Its physics and user-command systems let the simulator run and accept a spawn request without a GUI.

xml
<sdf version="1.9">  <world name="rtj_world">    <physics name="1ms" type="ode">      <max_step_size>0.001</max_step_size>      <real_time_factor>1.0</real_time_factor>    </physics>     <plugin filename="gz-sim-physics-system" name="gz::sim::systems::Physics"/>    <plugin filename="gz-sim-user-commands-system" name="gz::sim::systems::UserCommands"/>    <plugin filename="gz-sim-scene-broadcaster-system" name="gz::sim::systems::SceneBroadcaster"/>     <light type="directional" name="sun">      <cast_shadows>true</cast_shadows>      <pose>0 0 10 0 0 0</pose>      <diffuse>0.9 0.9 0.9 1</diffuse>      <specular>0.2 0.2 0.2 1</specular>      <direction>-0.5 0.1 -0.9</direction>    </light>     <model name="ground_plane">      <static>true</static>      <link name="link">        <collision name="collision">          <geometry><plane><normal>0 0 1</normal><size>100 100</size></plane></geometry>        </collision>        <visual name="visual">          <geometry><plane><normal>0 0 1</normal><size>100 100</size></plane></geometry>          <material>            <ambient>0.8 0.8 0.8 1</ambient>            <diffuse>0.8 0.8 0.8 1</diffuse>          </material>        </visual>      </link>    </model>     <model name="obstacle_box">      <static>true</static>      <pose>2 0 0.25 0 0 0</pose>      <link name="link">        <collision name="collision">          <geometry><box><size>0.5 0.5 0.5</size></box></geometry>        </collision>        <visual name="visual">          <geometry><box><size>0.5 0.5 0.5</size></box></geometry>          <material>            <ambient>0.8 0.3 0.2 1</ambient>            <diffuse>0.8 0.3 0.2 1</diffuse>          </material>        </visual>      </link>    </model>  </world></sdf>

2. Expose the simulated wheel interfaces

Save the full model as urdf/diffbot_control.urdf.xacro. It deliberately does not load Gazebo’s native DiffDrive system. The gz_ros2_control/GazeboSimSystem hardware plugin exposes velocity command interfaces plus position and velocity state interfaces for both wheels. The Gazebo system plugin loads the controller configuration. See the Jazzy gz_ros2_control installation and plugin reference for the two plugin roles.

xml
<robot xmlns:xacro="http://www.ros.org/wiki/xacro" name="diffbot">   <!-- Dimensions in metres, masses in kg -->  <xacro:property name="chassis_x" value="0.30"/>  <xacro:property name="chassis_y" value="0.20"/>  <xacro:property name="chassis_z" value="0.08"/>  <xacro:property name="chassis_mass" value="2.0"/>  <xacro:property name="chassis_offset_x" value="0.05"/>  <xacro:property name="wheel_radius" value="0.05"/>  <xacro:property name="wheel_width" value="0.03"/>  <xacro:property name="wheel_mass" value="0.2"/>  <xacro:property name="wheel_separation" value="0.24"/>  <xacro:property name="wheel_z" value="-0.03"/>  <xacro:property name="caster_radius" value="0.025"/>  <xacro:property name="caster_mass" value="0.1"/>  <xacro:property name="caster_x" value="0.12"/>   <material name="blue"><color rgba="0.1 0.3 0.8 1"/></material>  <material name="dark"><color rgba="0.1 0.1 0.1 1"/></material>  <material name="grey"><color rgba="0.6 0.6 0.6 1"/></material>   <xacro:macro name="box_inertia" params="m x y z">    <inertial>      <origin xyz="${chassis_offset_x} 0 0" rpy="0 0 0"/>      <mass value="${m}"/>      <inertia ixx="${m*(y*y+z*z)/12}" ixy="0" ixz="0"               iyy="${m*(x*x+z*z)/12}" iyz="0"               izz="${m*(x*x+y*y)/12}"/>    </inertial>  </xacro:macro>   <!-- Cylinder whose axis lies along the link's y axis -->  <xacro:macro name="wheel_inertia" params="m r h">    <inertial>      <mass value="${m}"/>      <inertia ixx="${m*(3*r*r+h*h)/12}" ixy="0" ixz="0"               iyy="${m*r*r/2}" iyz="0"               izz="${m*(3*r*r+h*h)/12}"/>    </inertial>  </xacro:macro>   <xacro:macro name="sphere_inertia" params="m r">    <inertial>      <mass value="${m}"/>      <inertia ixx="${2*m*r*r/5}" ixy="0" ixz="0"               iyy="${2*m*r*r/5}" iyz="0"               izz="${2*m*r*r/5}"/>    </inertial>  </xacro:macro>   <link name="base_link">    <visual>      <origin xyz="${chassis_offset_x} 0 0" rpy="0 0 0"/>      <geometry><box size="${chassis_x} ${chassis_y} ${chassis_z}"/></geometry>      <material name="blue"/>    </visual>    <collision>      <origin xyz="${chassis_offset_x} 0 0" rpy="0 0 0"/>      <geometry><box size="${chassis_x} ${chassis_y} ${chassis_z}"/></geometry>    </collision>    <xacro:box_inertia m="${chassis_mass}" x="${chassis_x}" y="${chassis_y}" z="${chassis_z}"/>  </link>   <xacro:macro name="wheel" params="name side">    <link name="${name}_wheel">      <visual>        <origin xyz="0 0 0" rpy="${pi/2} 0 0"/>        <geometry><cylinder radius="${wheel_radius}" length="${wheel_width}"/></geometry>        <material name="dark"/>      </visual>      <collision>        <origin xyz="0 0 0" rpy="${pi/2} 0 0"/>        <geometry><cylinder radius="${wheel_radius}" length="${wheel_width}"/></geometry>      </collision>      <xacro:wheel_inertia m="${wheel_mass}" r="${wheel_radius}" h="${wheel_width}"/>    </link>    <joint name="${name}_wheel_joint" type="continuous">      <parent link="base_link"/>      <child link="${name}_wheel"/>      <origin xyz="0 ${side*wheel_separation/2} ${wheel_z}" rpy="0 0 0"/>      <axis xyz="0 1 0"/>    </joint>  </xacro:macro>   <xacro:wheel name="left" side="1"/>  <xacro:wheel name="right" side="-1"/>   <link name="caster_link">    <visual>      <geometry><sphere radius="${caster_radius}"/></geometry>      <material name="grey"/>    </visual>    <collision>      <geometry><sphere radius="${caster_radius}"/></geometry>    </collision>    <xacro:sphere_inertia m="${caster_mass}" r="${caster_radius}"/>  </link>  <joint name="caster_joint" type="fixed">    <parent link="base_link"/>    <child link="caster_link"/>    <origin xyz="${caster_x} 0 ${wheel_z - wheel_radius + caster_radius}" rpy="0 0 0"/>  </joint>   <!-- Near-frictionless caster so it does not fight the drive wheels -->  <gazebo reference="caster_link">    <mu1>0.001</mu1>    <mu2>0.001</mu2>  </gazebo>   <ros2_control name="GazeboSimSystem" type="system">  <hardware>    <plugin>gz_ros2_control/GazeboSimSystem</plugin>  </hardware>  <joint name="left_wheel_joint">    <command_interface name="velocity">      <param name="min">-20</param>      <param name="max">20</param>    </command_interface>    <state_interface name="position"/>    <state_interface name="velocity"/>  </joint>  <joint name="right_wheel_joint">    <command_interface name="velocity">      <param name="min">-20</param>      <param name="max">20</param>    </command_interface>    <state_interface name="position"/>    <state_interface name="velocity"/>  </joint></ros2_control> <gazebo>  <plugin filename="libgz_ros2_control-system.so"          name="gz_ros2_control::GazeboSimROS2ControlPlugin">    <parameters>$(find rtj_diffbot)/config/controllers.yaml</parameters>  </plugin></gazebo></robot>

3. Configure the controller and clock

Save this as config/controllers.yaml. Match the wheel names to the URDF exactly, and keep the 0.24 m separation and 0.05 m radius consistent with the model. With open loop disabled and position feedback enabled, the controller calculates odometry from wheel position feedback rather than the requested body velocity.

yaml
controller_manager:  ros__parameters:    update_rate: 100    use_sim_time: true     joint_state_broadcaster:      type: joint_state_broadcaster/JointStateBroadcaster     diff_drive_controller:      type: diff_drive_controller/DiffDriveController diff_drive_controller:  ros__parameters:    left_wheel_names: ["left_wheel_joint"]    right_wheel_names: ["right_wheel_joint"]     wheel_separation: 0.24    wheel_radius: 0.05     odom_frame_id: odom    base_frame_id: base_link    enable_odom_tf: true    open_loop: false    position_feedback: true    cmd_vel_timeout: 0.5     linear.x.max_velocity: 1.0    linear.x.min_velocity: -1.0    linear.x.max_acceleration: 1.0    angular.z.max_velocity: 2.0    angular.z.min_velocity: -2.0    angular.z.max_acceleration: 2.0

Save this as config/bridge_control.yaml. Do not add a second odometry or joint-state bridge to this launch. The Jazzy diff_drive_controller topic and parameter reference documents the controller’s own outputs and the command timeout.

yaml
- ros_topic_name: "clock"  gz_topic_name: "clock"  ros_type_name: "rosgraph_msgs/msg/Clock"  gz_type_name: "gz.msgs.Clock"  direction: GZ_TO_ROS

4. Spawn the robot, then load the controllers

Save as launch/sim_control.launch.py. The headless Gazebo launch starts the world, state publisher, create process and clock bridge. The create process exiting triggers the joint-state broadcaster spawner; that spawner exiting triggers the drive controller spawner. An exit event is not proof of success, so confirm both controllers are active before sending commands. The Jazzy controller manager and spawner documentation explains the spawner options.

python
import os from ament_index_python.packages import get_package_share_directoryfrom launch import LaunchDescriptionfrom launch.actions import IncludeLaunchDescription, RegisterEventHandlerfrom launch.event_handlers import OnProcessExitfrom launch.launch_description_sources import PythonLaunchDescriptionSourcefrom launch.substitutions import Commandfrom launch_ros.actions import Nodefrom launch_ros.parameter_descriptions import ParameterValue  def generate_launch_description():    pkg_share = get_package_share_directory('rtj_diffbot')    ros_gz_sim_share = get_package_share_directory('ros_gz_sim')     xacro_file = os.path.join(pkg_share, 'urdf', 'diffbot_control.urdf.xacro')    world_file = os.path.join(pkg_share, 'worlds', 'rtj_world.sdf')    bridge_file = os.path.join(pkg_share, 'config', 'bridge_control.yaml')     robot_description = ParameterValue(        Command(['xacro ', xacro_file]), value_type=str)     gz_sim = IncludeLaunchDescription(        PythonLaunchDescriptionSource(            os.path.join(ros_gz_sim_share, 'launch', 'gz_sim.launch.py')),        launch_arguments={            'gz_args': f'-r -s {world_file}',            'on_exit_shutdown': 'true',        }.items())     robot_state_publisher = Node(        package='robot_state_publisher',        executable='robot_state_publisher',        parameters=[{            'robot_description': robot_description,            'use_sim_time': True,        }],        output='screen')     spawn_robot = Node(        package='ros_gz_sim',        executable='create',        arguments=['-topic', 'robot_description',                   '-name', 'diffbot',                   '-z', '0.15'],        output='screen')     bridge = Node(        package='ros_gz_bridge',        executable='parameter_bridge',        parameters=[{'config_file': bridge_file}],        output='screen')     joint_state_broadcaster = Node(        package='controller_manager',        executable='spawner',        arguments=['joint_state_broadcaster'],        output='screen')     diff_drive_controller = Node(        package='controller_manager',        executable='spawner',        arguments=['diff_drive_controller'],        output='screen')     # Start controllers in order, each after the previous process exits    start_jsb = RegisterEventHandler(        OnProcessExit(target_action=spawn_robot,                      on_exit=[joint_state_broadcaster]))    start_ddc = RegisterEventHandler(        OnProcessExit(target_action=joint_state_broadcaster,                      on_exit=[diff_drive_controller]))     return LaunchDescription([        gz_sim,        robot_state_publisher,        spawn_robot,        bridge,        start_jsb,        start_ddc,    ])

On a fresh setup, run sudo rosdep init once if rosdep has not been initialized. Then resolve dependencies, build and source the overlay:

bash
cd ~/rtj_wssource /opt/ros/jazzy/setup.bashrosdep updaterosdep install --from-paths src --ignore-src --rosdistro jazzy -r -yrosdep check --from-paths src --ignore-src --rosdistro jazzycolcon build --packages-select rtj_diffbotsource install/setup.bash
bash
ros2 launch rtj_diffbot sim_control.launch.py

5. Verify interfaces and send a TwistStamped command

In a second terminal, look for both controllers in the active state and both wheel velocity interfaces marked claimed. Confirm the topic type before publishing: a plain Twist on /cmd_vel is not the input for this configuration.

bash
source /opt/ros/jazzy/setup.bashsource ~/rtj_ws/install/setup.bashros2 control list_controllersros2 control list_hardware_interfacesros2 topic info /diff_drive_controller/cmd_vel --verboseros2 topic echo --once /diff_drive_controller/odom

Send a command at 10 Hz. The example publisher ends after four seconds; the controller is configured with a 0.5 s command timeout. Compare odometry to the baseline after publishing.

bash
timeout 4s ros2 topic pub --rate 10 \  /diff_drive_controller/cmd_vel geometry_msgs/msg/TwistStamped \  '{twist: {linear: {x: 0.2}}}'ros2 topic echo --once /diff_drive_controller/odom

In the recorded Jazzy check, the CLI’s default zero stamp was accepted and the controller substituted current simulation time. Both controllers activated, both wheel velocity interfaces were claimed, and odometry advanced from approximately zero to 0.520 m in that run. This is a recorded observation, not a target distance or a guarantee for a different controller build. If sending a nonzero stamp, use the same simulated clock as the controller. For keyboard input, see the Jazzy keyboard teleop documentation for stamped and remap cmd_vel to the controller’s input topic.

Troubleshoot and know what does not transfer to hardware

  • Controller manager not found: check whether the robot spawned, the Gazebo control plugin loaded, and the installed path to controllers.yaml resolved.
  • Controller inactive: inspect the spawner output. Check the joint names and whether the manager exposes the expected command and state interfaces.
  • Commands arrive but motion stops: verify the stamped message type, advancing simulation clock, command rate and timeout. If TF or odometry appears twice, check for another launch or the old Gazebo DiffDrive system.

A real base needs a hardware interface that suits its motor drivers and feedback, verified units and wheel geometry, and independent checks for limits and safe stopping. The simulated controller configuration is a starting point, not proof of hardware compatibility. For the hardware selection part of that work, see the robot motor selection guide.

More from Build Guides

ROS 2 for Beginners: Setting Up Your First Project
RoboticsApr 29, 2026Foundational

ROS 2 for Beginners: Setting Up Your First Project

A gentle introduction to ROS 2 concepts, installation, and getting a first publisher/subscriber project running before diving into Nav2 and SLAM.

Servo vs Stepper vs DC Motors: The Complete Guide for Robot Builders
RoboticsJun 10, 2026Foundational

Servo vs Stepper vs DC Motors: The Complete Guide for Robot Builders

A complete comparison of DC motors, servo motors, and stepper motors — how each works, where each fits, and how to choose for your robot project.

Configuring ROS 2 Nav2 Costmaps: Inflation, Footprints, and Clearing for Constrained Corridors
Build GuidesSep 21, 2026Intermediate

Configuring ROS 2 Nav2 Costmaps: Inflation, Footprints, and Clearing for Constrained Corridors

Tune ROS 2 Nav2 costmaps for constrained corridors. Define footprints, balance inflation costs, clear ghost obstacles, and validate safe navigation in RViz.