Controlling Robots Using the ros2 control Package
local graph
Chapter 6 — Controlling Robots Using the ros2_control Package
Section titled “Chapter 6 — Controlling Robots Using the ros2_control Package”The lowest layer of a robotic software architecture consists of controllers that connect high-level commands to the robot’s actuators, such as its wheels or joints. In this chapter, we will introduce the ros2_control package, a framework designed to simplify the integration of hardware with control algorithms in robotics applications. We will discuss the use of the Controller Manager and the framework’s structure. Then, we will demonstrate how to integrate specific controllers with a robot, consisting of two joints, simulated using Gazebo. Finally, we will show how to create custom controllers by implementing them as plugins.
Here’s a list of the main topics that will be covered in the chapter:
- Understanding the
ros2_controlframework - The
ros2_controlframework architecture - Interfacing with simulated controllers using Gazebo
- Interacting with the
ros2_controlframework using the CLI - Implementing a new controller
Technical requirements
Section titled “Technical requirements”To follow this chapter, you should have one of the following setups on your computer:
- A standard computer running Ubuntu 24.04 LTS operating system
- A Docker container installed as discussed in Chapter 2 on your Linux host machine or a ROS 2 Jazzy desktop full installation
The reference code for this chapter can be found in the Chapter06 folder of the following GitHub repository: https://github.com/PacktPublishing/Mastering-ROS-2-for-Robotics-Programming/tree/main/Chapter06.
Understanding the ros2_control framework
Section titled “Understanding the ros2_control framework”In a typical robotic application, once the desired motion—such as actuator position or wheel speed—is determined, the command must be sent to the robot’s hardware or its simulation. ROS 2 provides the ros2_control framework, a collection of packages for low-level robot control. Evolved from ros_control in ROS 1.x, ros2_control separates hardware-specific code from control logic, enabling controller reuse across different hardware with minimal changes. It offers user-friendly interfaces for interacting with sensors and actuators and tools for efficient component management. This framework simplifies hardware integration and control algorithm development, reducing the complexity of robot control system maintenance. Another important advance of the ros2_control framework is the possibility of defining a chain of controllers. In this way, controllers can be composed properly by linking their input and output.
Let’s discuss in detail the main packages comprising the ros2_control framework:
ros2_control: This is the central package, providing the main interfaces and components necessary for robot control. Some elements of this package are as follows:- Hardware interfaces: These define how to interact with different robot hardware components, such as sensors and actuators. They abstract the hardware specifics, making the control logic hardware-agnostic.
- Controller interfaces: These are standard interfaces for creating different types of controllers that perform specific tasks, such as position, velocity, or effort control.
- Controller Manager: A crucial component that manages the lifecycle of controllers. It loads, unloads, starts, and stops controllers dynamically, ensuring efficient resource management.
- Hardware interfaces: These define how to interact with different robot hardware components, such as sensors and actuators. They abstract the hardware specifics, making the control logic hardware-agnostic.
ros2_controllers: This is a collection of widely used controllers that can be easily integrated into robot applications. Some controllers are as follows:forward_command_controller: A simple controller that forwards commands directly to the hardware. It’s often used for basic control tasks where complex processing is unnecessary.joint_trajectory_controller: Manages the execution of trajectories for joints. It interpolates between points in a trajectory and sends the appropriate commands to the joints to follow the desired path.diff_drive_controller: Specifically designed for differential drive robots. It converts velocity commands into appropriate wheel commands, handling the kinematics of such robots.
realtime_tools: This is a general toolkit aimed at providing support for real-time applications. It includes components that help ensure real-time safety and performance, such as the following:RealtimeBuffer: Thread-safe buffers that allow for safe data exchange between real-time and non-real-time parts of the systemRealtimePublisher: Specialized ROS publishers designed to work within real-time constraints, ensuring timely and deterministic message publishing
control_msgs: This defines common message types used in theros2_controlecosystem. These messages facilitate communication between different parts of the control framework, ensuring standardized data exchange. The most common messages are as follows:JointControllerState: Messages that convey the state of joint controllers, including current position, velocity, and effortFollowJointTrajectoryAction: Messages used for sending and managing joint trajectory commands
These modules interact to let the hardware devices communicate with the controllers, as described in the software architecture discussed in the next section.
Understanding the ros2_control framework architecture
Section titled “Understanding the ros2_control framework architecture”Considering the packages described in the previous section, the overall ros2_control framework architecture is depicted in Figure 6.1 and the main elements are detailed in the following list:
- Controller Manager: In the
ros2_controlframework, the Controller Manager serves as the primary user entry point, connecting controllers to hardware-abstraction layers via ROS services. Implemented as a node without an internal executor, it relies on an external executor that manages callbacks, timing, and control loops for the ROS node. The Controller Manager’s responsibilities include managing controllers—loading, activating, deactivating, and unloading them—and interfacing with hardware components through the Resource Manager. It matches required and provided interfaces and reports conflicts, ensuring a smooth operation within the ROS control ecosystem. - Resource Manager: The Resource Manager coordinates access to hardware resources such as actuators (or their simulated version). It loads hardware components using
pluginlib, manages their lifecycle, and handles their state and command interfaces. - Controllers: Controllers in the
ros2_controlframework follow control theory principles, comparing reference values with measured outputs and calculating system inputs based on the error. Derived fromControllerInterfaceand exported as plugins viapluginlib, controllers such asforward_command_controllerinros2_controllersmanage their lifecycle through theLifecycleNodeclass. In control-loop execution, theupdate()method accesses the latest hardware state and enables controllers to write to command interfaces. - Hardware components: Hardware components in the
ros2_controlframework communicate with physical hardware and are exported as plugins viapluginlib. Managed by the Resource Manager, they fall into three categories:- System: For complex multi-DOF robotic hardware, supporting both reading and writing capabilities (e.g., industrial robots).
- Sensor: For sensing hardware, providing read-only capabilities (e.g., encoders, force/torque sensors).
- Actuator: For simple 1-DOF (only one joint) hardware such as motors and valves, supporting reading and writing, but reading is optional (e.g., DC motor with Arduino).
These components are modular and can be used in complex systems with independent communication channels.

- System: For complex multi-DOF robotic hardware, supporting both reading and writing capabilities (e.g., industrial robots).
Figure 6.1: The ros2_control framework architecture
Figure 6.1: The ros2_control framework architecture
In this chapter, we will go through the different elements implemented in the ros2_control framework. This framework consists of different resources that are continuously updated. For this reason, in the next section, we will list some important references.
The ros2_control framework documentation
Section titled “The ros2_control framework documentation”In the following, the main references of the ros2_control framework are listed:
- ROS2 documentation [1]: The official ROS2 documentation provides an overview of
ros2_control, including its architecture and main components. - The
ros2_controlGitHub repository [2]: The main repository forros2_controlon GitHub is a great place to explore source code, issues, and discussions. The repository also includes example configurations and explanations of the system’s structure. - ROS 2 hardware interface documentation [3]: This documentation explains the hardware abstraction layer and how
ros2_controlconnects with various hardware interfaces. - Controller Manager documentation [4]: Detailed information on the
Controller Managernode, its role, and its services can be found within the ROS 2 documentation. - The
ros2_control_demospackage [5]: This package contains example setups demonstrating how to useros2_control. It’s helpful for seeing practical implementations.
These resources should give you a strong starting point for exploring ros2_control and understanding its parts and functions in ROS 2. Let me know if you need more specific information. However, we need a way to simulate the presence of a controller connected to the simulated robot models. For this reason, in the next section, we will learn how to include controllers in our robot simulation models.
Interfacing with simulated controllers using Gazebo
Section titled “Interfacing with simulated controllers using Gazebo”A crucial aspect of robot simulations is accurately replicating real-world conditions, including modeling control interfaces. The ros2_control framework enables simulating robot controllers to interact with simulated hardware. This section covers integrating ros2_control with Gazebo, starting with creating a robot model containing ros2_control plugins to move the robot’s joints. To do this, the following steps must be taken.
Step 1 – Creating the ROS 2 package
Section titled “Step 1 – Creating the ROS 2 package”The first step to include controllers in a simulated robot is to obtain the simulation model. We already discussed the 3D simulation models of robots and showed how to create them and import them in simulation software such as Gazebo in Chapters 4 and 5 of this book. Let’s create a package containing the necessary files to simulate a robot with two joints: a revolute one and a prismatic one. Move into the source folder of your ROS 2 workspace and use the following command:
ros2 pkg create two_joints_robot --build-type ament_cmakeYou can download this package from the /two_joints_robot folder of the book repository.
However, inside this package directory, let’s create the following directories:
- A
urdffolder to contain the robot model file - A
launchfolder containing the files used to start the simulation - A
configfolder for the configuration file of the controllers.
We are now ready to develop the robot model file.
Step 2 – Creating a robot model
Section titled “Step 2 – Creating a robot model”We already discussed the xacro formalisms to develop new robot models. For this reason, and to improve the chapter’s readability, we avoid reporting the whole content of the file here. However, the full content of the robot model file can be found in the package in the urdf subfolder in the urdf/two_joints_robot.xacro file. This file model contains the following elements:
- Three links:
base_link, defined as a base platelink1andlink2, represented by cylinders
- Two joints:
- A revolute joint (called
base_joint), connectinglink1withbase_link- A prismatic joint (called
link1_link2), connectinglink2withlink1
- A prismatic joint (called
- A revolute joint (called
The model can be visualized in Rviz2 after implementing a proper launch file, in which the xacro file is loaded, and then joint_state_publisher_gui and robot_state_publisher are started, along with Rviz2. In Rviz2, the model description can be added to see the robot in the scene, as shown in Figure 6.2:

Figure 6.2: The two-joint robot implemented in the xacro file
Figure 6.2: The two-joint robot implemented in the xacro file
Step 3 – Adding controllers to the robot
Section titled “Step 3 – Adding controllers to the robot”Now, let’s add controllers to the robot using ros2_control plugins:
- If the
ros2_controlframework is not yet installed in your system, you can install it using the following command:sudo apt install ros-jazzy-ros2-control ros-jazzy-ros2-controllers - At the start, we’ll use pre-built controllers from the
ros2_controlpackage. Later, we’ll implement a custom controller as a plugin enabled by the Controller Manager. To use controllers in the simulated robot, modify the robot model file to include the<ros2_control>tag for accessing and controlling robot interfaces. We should include the following:- A specific
<plugin>for our robot- A
<joint>tag including the robot controllers:commandsandstates
- A
- A specific
- In the same section, the
GazeboSimSystemplugin is used to define that the hardware we are contacting is a simulated system:<ros2_control name="2DofControl" type="system"><hardware><plugin>gz_ros2_control/GazeboSimSystem</plugin></hardware> - For each joint we want to control using the
ros2_controlpackage, we must define which kind of command interface is available. Basic interfaces are inpositionandvelocity. For both joints, we definedpositionandvelocityas the command interface:<joint name="base_joint"><command_interface name="position" /><command_interface name="velocity" /> - Similarly, we must specify
state_interface. This is the output of the actuator, which can be streamed via the/joint_statetopic. In this case, we specify that the state of the actuator is composed ofposition,velocity, andeffort. In addition, we can set an initial value for the motor as a parameter ofstate_interfaceinposition:<state_interface name="position"><param name="initial_value">0.0</param></state_interface><state_interface name="velocity"/></joint> - A similar configuration is added for the second joint of the robot:
<joint name="link1_link2"><command_interface name="position" /><command_interface name="velocity" /><state_interface name="position" /><state_interface name="velocity"/></joint></ros2_control>
- Finally, to add the controllers, we must include the
ros2_controlplugin. In this case, we need to import thegz_ros2_control-systemplugin:<gazebo><plugin filename="gz_ros2_control-system" name="gz_ros2_control::GazeboSimROS2ControlPlugin"> - This plugin needs a
.yamlparameter file in which the controllers are configured. In this example, we placed the configuration file into theconfigfolder and installed it by modifyingCMakeList.txt(we will discuss this in step 5). To find this file in the computer files system, we can use the$(find PKG_NAME)command:<parameters>$(find two_joints_robot)/config/controller.yaml</parameters></plugin></gazebo>
Step 4 – Creating launch and configuration files
Section titled “Step 4 – Creating launch and configuration files”In the previous step, we saw how a .yaml file is needed to inform the ros2_control framework about the controller configuration. In this example, we place the configuration file into the config folder of the two_joints_robots package:
- Of course, before we can use this file, we have to install it. For now, just check its content. This is a typical ROS 2 parameter file of the
.yamltype:controller_manager:ros__parameters:update_rate: 100 # Hz - To add a new controller, specify its name and type. The name is arbitrary for later reference, while the type must be chosen from available low-level controllers in your system. For instance, you might name the first controller
position_controland set its type toForwardCommandControllerfrom theforward_command_controllerpackage. This controller forwards input from theROS2topic to the robot joint. The control interface will be detailed later. We define two such controllers to enable both position and velocity control:position_control:type: forward_command_controller/ForwardCommandControllerVelocity_control:type: forward_command_controller/ForwardCommandController - A third controller added to the list is
joint_state_broadcaster. This controller publishes the/joint_statetopic with the information about the motor configuration:joint_state_broadcaster:type: joint_state_broadcaster/JointStateBroadcaster - The controllers defined previously are configured here, where the joints that represent the target of the control action are specified:
position_control:ros__parameters:
- We specify that both joints are controllable using the
position_controlcontroller. Also, the state interface of this control (which kind of data can be used from the joint state) is reported here:joints:- base_joint- link1_link2interface_name: positionstate_interfaces:- position- velocity - A similar configuration is made for the velocity,
velocity_control. The difference here is that theinterface_namevalue isvelocity:velocity_control:ros__parameters:joints:- base_joint- link1_link2interface_name: velocitystate_interfaces:- position- velocity - After defining the configuration files, add a launch file to your package to start the simulation and spawn the robot. In the example package, the launch file is called
launch/start_simu.launch.py. This is similar to the launch file discussed in Chapter 5. However, you need to add nodes to configure the controllers. For each controller, initialize the ones to be used to actuate the robot using theros2 controlcommand with specific parameters. This is done using theExecuteProcessfunction in the launch file to run a command-line command. In this case, the command is the following:ros2 control load_controller --set-state active joint_state_broadcaster - The code in the launch file instead will be the following:
load_joint_state_broadcaster = ExecuteProcess(cmd=['ros2', 'control', 'load_controller', '--set-state', 'active', 'joint_state_broadcaster'])
- We repeat the same instructions for the
positionandvelocitycontrollers. However, we should choose the command interface to use, since we cannot control the robot both inpositionandvelocityat the same time. For this reason, we choose to activate only thepositioncontroller, while setting thevelocityone toinactive:load_position_controller = ExecuteProcess(cmd=['ros2', 'control', 'load_controller', '--set-state', 'active', 'position_control'])load_velocity_controller = ExecuteProcess(cmd=['ros2', 'control', 'load_controller', '--set-state', 'inactive','velocity_control']) - Of course, with the previous code block, we are defining nodes to launch. We have to insert them in the launch description object created from the launch file. Here is an example:
ld = LaunchDescription()ld.add_action( load_position_controller )return ld
Just one last step is missing before testing our ros2_control in the Gazebo simulation: the installation of configuration and launchS files, as discussed in the following step.
Step 5 – Installing the necessary files
Section titled “Step 5 – Installing the necessary files”The last step before launching the simulation with the ros2_control integration is to install the necessary files such as the robot model, the launch files, and the .yaml configuration. These files must be placed into the install folder of the workspace in order to be fully accessible as a shared resource of the ROS 2 system. To do this, edit the CMakeList.txt file of the two_joints_robot package, as shown in the following:
install(DIRECTORY launch urdf config DESTINATION share/${PROJECT_NAME})Now, you can compile the workspace using the colcon build command, after moving in your ROS 2 workspace with the terminal:
colcon build --symlink-installAfter successfully compiling the workspace, you can start the simulation and interact with the ros2_control framework using command-line tools, as discussed in the next section.
Interacting with the ros2_control framework using the CLI
Section titled “Interacting with the ros2_control framework using the CLI”It is now time to start the simulation to interact with the controllers. Let’s start by installing the dependencies:
sudo apt-get install ros-jazzy-xacro ros-jazzy-ros-gz-sim ros-jazzy-gz-ros2-control-demosAssuming you already initialized and sourced the workspace, run the following commands:
- To start the simulation, use the following command:
ros2 launch two_joints_robot start_simu.launch.py
With this command, along with the simulation, we launch the controllers of the robot.
- For example, if you want to move a joint, you can directly publish the
positioncommand using theros2 topic pubcommand:ros2 topic pub /position_control/commands std_msgs/msg/Float64MultiArray "{data: [3, 0]}" - In this way, you request to move the first joint of the robot to
3radians, while bringing the second joint to0radians. The result of this motion can be seen in Figure 6.3.
Figure 6.3: Robot configuration – initial (left) and final after accomplishing the requested motion (right)
Figure 6.3: Robot configuration – initial (left) and final after accomplishing the requested motion (right)
- Along with the controllers, the
Controller Managernode has started as well. TheController Managernode provides commands accessible via the command line to retrieve the state of the controllers and change their status. For example, using thelist_controllerscommand, you can retrieve the list of current active controllers:ros2 control list_controllersjoint_state_broadcaster[joint_state_broadcaster/JointStateBroadcaster] activeposition_control [forward_command_controller/ForwardCommandController] activevelocity_control [forward_command_controller/ForwardCommandController] inactive
As you can see from the command output, the controllers specified in the launch file are listed and, as requested, velocity_control is inactive.
- You can switch controllers if you want to control the velocity of the actuator instead of the position. Activate
velocity_controland deactivateposition_controlwith the following:ros2 control switch_controllers --activate velocity_control --deactivate position_control - You can now check the status of the controllers with the
ros2 controlcommand. Other useful commands are available in theros2 controlcommands list, and you can easily print them, with a small description, by typing the following command (of course, you can use the Tab key to see all the available commands):ros2 control
Up to now, we just used the controllers already defined in the ros2_control package. Sometimes, this is not enough, and custom controllers must be implemented, as discussed in the next section.
Implementing a new controller
Section titled “Implementing a new controller”The ros2_control framework supports various controllers beyond the basic forward_command_controller, such as diff_drive_controller for mobile robots. For custom needs, you can create specialized controllers that directly implement control laws and interact with hardware without using ROS 2 communication. These controllers are dynamic libraries loaded by the Controller Manager via pluginlib, allowing modular and on-demand loading. For instance, we’ll create a controller that generates sinusoidal motion for the robot’s joints, using ROS 2 topics for signal specifications. This setup is useful for testing motor performance and involves specific creation steps.
Step 1 – Creating the ros2 package
Section titled “Step 1 – Creating the ros2 package”The first step is to set up the ros2 package continuing our controller. Let’s create it with the following command to include all the dependencies:
ros2 pkg create sine_ctrl --dependencies rclcpp std_msgs controller_interface pluginlibThe source code of the controller can be placed in the source directory of the package. Let’s create a source called sine_controller.cpp. We are now ready to write the source code of the controller.
Step 2 – Writing the source code of the controller
Section titled “Step 2 – Writing the source code of the controller”The source code of a ROS 2 controller of the ros2_control package has a fixed structure with a well-defined pipeline. The controller is developed as a plugin that inherits from the ControllerInterface class and, as such, must implement several abstract methods defined in its base class. The entry point of the controller is the object constructor. The following are the steps needed to implement a new controller:
- Create a constructor to initialize member variables, although initialization can also occur in the
on_initmethod. - Implement the
on_initmethod to perform initial setup, initialize variables, reserve memory, and declare node parameters. - Implement the
on_configuremethod to prepare the controller by reading parameters and completing any necessary setup before starting. - Define the required interfaces using
command_interface_configurationandstate_interface_configuration. - Implement the
on_activatemethod. This checks and sorts interfaces, and assigns initial values. This method is called every time the controller has been activated. - Implement the
on_deactivatemethod. This method is called when the controller is deactivated. - Implement the
updatemethod. This is the main loop of the controller, which runs with the controller frequency to update the input of the hardware interface. - Export the controller class. Add the
PLUGINLIB_EXPORT_CLASSmacro at the end of your file after the namespace.
The source code implementing the described steps is shown in the following code blocks:
- At the start, we include the header files to use the ROS 2 function, access the controller interface, and handle the
Float32MultiArraydata. Finally, we define a variable specifying the number of joints for the robot:#include "rclcpp/rclcpp.hpp"#include "controller_interface/controller_interface.hpp"#include "controller_interface/helpers.hpp"#include "std_msgs/msg/float32_multi_array.hpp"#define J_SIZE 2 - The controller must be implemented inside a namespace. Inside the namespace, we must define the controller class that inherits from the base class:
namespace sine_controller {class SineController : public controller_interface::ControllerInterface {
- Among the different variables, we have to provide the joint state interface with access to the current state of an actuator (
position,velocity, andeffort). Theros2_controlframework implements this withLoanedStateInterface, which provides temporary, controlled access to state data for real-time operations, ensuring safe and synchronized interactions within a controller. It helps manage access to state data without causing conflicts or inconsistencies in the system.rclcpp::Duration dt_;template<typename T> - To use
LoanedStateInterface, we define a type alias for a 2D vector ofstd::reference_wrapper<T>. Thejoint_state_interfaces_variable uses this type to manage references tohardware_interface::LoanedStateInterfaceobjects:using InterfaceReferences = std::vector<std::vector<std::reference_wrapper<T>>>;InterfaceReferences<hardware_interface::LoanedStateInterface> joint_state_interfaces_; - Finally, a vector of
stringvectors is declared to define the interface name. We have to consider a new name for each joint and interface, such asjoint_name/position,joint_name/velocity,joint_name_2/position, and so on:std::vector<std::vector<std::string>> state_interface_names_; - Other class variables are used to handle the control data generated into the controller:
float initial_joint_position_[J_SIZE];float desired_joint_positions_[J_SIZE];float amplitude_[J_SIZE];float frequency_[J_SIZE];double t_;
- As already stated, the sinusoidal specifications are set via ROS 2 topics, using a vector of four elements:
amplitude joint 1,frequency joint 1,amplitude joint 2, andfrequency joint 2:rclcpp::Subscription<std_msgs::msg::Float32MultiArray>::SharedPtr sine_param_sub_;public:SineController() : controller_interface::ControllerInterface(), dt_(0, 0) {} - The callback uses the received data to fill in
amplitudeandfrequencydefined as class members. First, we check that the format of the data is correct. We need four numbers to set the parameters correctly:void sine_param_cb(const std_msgs::msg::Float32MultiArray::SharedPtr msg) {if( msg->data.size() != 4 ) {RCLCPP_ERROR(this->get_node()->get_logger(), "Wrong number of sine parameters");return;}amplitude_[0] = msg->data[0];amplitude_[1] = msg->data[2];frequency_[0] = msg->data[1];frequency_[1] = msg->data[3];} - We are now ready to define the state and the command interfaces. These functions are called automatically by the Controller Manager:
controller_interface::InterfaceConfiguration state_interface_configuration() const {
- Here, we can hardcode the name of the state interfaces. The syntax is
joint_name/interface. Since in the configuration of the joints we share the position and the velocity as joint states and we have two joints, we will add four elements to thestate_interfaces_config_namesvector:std::vector<std::string> tate_interfaces_config_names;state_interfaces_config_names.push_back("base_joint/position");state_interfaces_config_names.push_back("link1_link2/position");state_interfaces_config_names.push_back("link1_link2/velocity");
In this section of code, we hardcoded the names of the joints. A more industrial-ready solution would be loading the names from a YAML param file.
- To effectively set the interfaces, we have to return the interface list. In this case, we specify them using the
INDIVIDUALproperty; we specify a detailed list of required interfaces, formatted as<joint_name>/<interface_type>:return {controller_interface::interface_configuration_type::INDIVIDUAL, state_interfaces_config_names};} - The same thing is done with the command interfaces. Of course, in this case, we just specify the position since we want to control the position of the joints:
controller_interface::InterfaceConfiguration command_interface_configuration() const {std::vector<std::string> command_interfaces_config_names;command_interfaces_config_names.push_back("base_joint/position");command_interfaces_config_names.push_back("link1_link2/position");
- Also, in this case, we return the list of the
INDIVIDUALinterfaces participating in the motor control:return {controller_interface::interface_configuration_type::INDIVIDUAL, command_interfaces_config_names};} - In the
on_configurefunction, we can do all the operations needed before starting the controllers. Here, we initialize the subscriber of the sinusoidal parameters:controller_interface::CallbackReturn on_configure(const rclcpp_lifecycle::State & ){_sine_param_sub = get_node()->create_subscription<std_msgs::msg::Float32MultiArray>("/sine_param", 10, std::bind(&SineController::sine_param_cb, this, std::placeholders::_1)); - As for the
_dtvariable, it is the step time of theupdatefunction. Theget_update_rate()function is used to retrieve the rate of the controller from the ROS 2 parameter server. As seen, we specified the parameters in the.yamlfile to configure the controllers:dt_ = rclcpp::Duration(std::chrono::duration<double, std::milli>(1e3 / get_update_rate()));amplitude_[0] = amplitude_[1] = frequency_[0] = frequency_[1] = 0.0; - Then, we resize the command to the interface vectors. The state interface is the only one that needs four elements (two elements,
velocityandposition, for each joint):command_interfaces_.reserve(J_SIZE); state_interfaces_.reserve(2*J_SIZE);joint_state_interfaces_.resize(J_SIZE);state_interface_names_.resize(J_SIZE); - We also initialize a list of the interfaces, as we will use it later:
std::vector<std::string> joint_name = {"base_joint", "link1_link2"};for(int i = 0; i < J_SIZE; i++) {state_interface_names_[i].resize(2);state_interface_names_[i][0] = joint_name[i] + "/position";state_interface_names_[i][1] = joint_name[i] + "/velocity";}
- This function must return the eventual
SUCCESSorFAILUREstate of the initialization. Imagine that you need to read some parameters in this function. If the parameters don’t exist or are not correctly specified, you could getFAILUREin return; however, it’sSUCCESSin our case:return controller_interface::CallbackReturn::SUCCESS;} - Another function to implement is the
on_activatefunction. This function is called when the controller passes from aninactivetoactivestate:controller_interface::CallbackReturn on_activate(const rclcpp_lifecycle::State &) {for(int i = 0; i < J_SIZE; i++) - We call the
get_ordered_interfacesfunction from thecontroller_interfacenamespace, which is used to retrieve and organize a list of interfaces, specifically,state_interfaces:controller_interface::get_ordered_interfaces( state_interfaces_, state_interface_names_[i], std::string(""),joint_state_interfaces_[i]); - Then, we retrieve the joint position to save the initial value of the motor control:
initial_joint_position_[0] = joint_state_interfaces_[0][0].get().get_value();initial_joint_position_[1] = joint_state_interfaces_[1][0].get().get_value();RCLCPP_INFO(get_node()->get_logger(), "Activate successful");
- The local time variable, used to calculate the sinusoidal signal, is reset every time the controller is activated. Finally, we set the
SUCCESSstate as the return value of the function:t_ = 0.0;return controller_interface::CallbackReturn::SUCCESS;}
We don’t do any operation in the on_init and deactivate functions:
controller_interface::CallbackReturn on_init() { return controller_interface::CallbackReturn::SUCCESS;}controller_interface::CallbackReturn on_deactivate(const rclcpp_lifecycle::State & ) { return controller_interface::CallbackReturn::SUCCESS;}- Finally, we can write the
updatefunction. Here, we must calculate the desired values of the joints that follow the sinusoidal profile:controller_interface::return_type update(const rclcpp::Time & , const rclcpp::Duration & ) { - We increment the local time variable that is used to proceed with the sinusoidal signal. Then, for each joint, we calculate the desired position with the classical sinusoidal formula –
x(t) = Amplitude*sin(2*pi*Frequency*time):t_ += _dt.seconds();for (int i = 0; i < J_SIZE; i++) {desired_joint_positions_ [i] =initial_joint_position_[i] + (amplitude _ [i] * std::sin(2 * M_PI * frequency_[i] * t_)); - Finally, we can set the desired position value using the command interface:
command_interfaces_[i].set_value(desired_joint_positions_[i]);}return controller_interface::return_type::OK;}};}
- We are now ready to install the plugin. At this stage, we use the
PLUGINLIB_EXPORT_CLASSmacro. This macro is defined in thepluginlib/class_list_macros.hppheader file. For this reason, we need to include this header file in our source code. To successfully export the controller, we must specify the class containing the controller implementation as the first parameter, such as<controller_name_namespace>::<ControllerName>, and the base class of the controller as the second parameter, which iscontroller_interface::ControllerInterface:#include "pluginlib/class_list_macros.hpp"PLUGINLIB_EXPORT_CLASS(sine_controller::SineController, controller_interface::ControllerInterface)
Step 3 – Compiling the controller plugin
Section titled “Step 3 – Compiling the controller plugin”Before integrating the controller into our robot, we must properly install the controller into the ROS 2 system:
- First, we define a
.xmlfile calledsine_controller.xmldescribing the plugin class. This file is called from theCMakeLists.txtfile, as described later. Note that the class name is fundamental to specify the right controller:<library path="sine_controller"><class name="sine_controller/SineController" type="sine_controller::SineController" base_class_type="controller_interface::ControllerInterface"><description>..</description></class></library> - Now, we can edit the
CMakeLists.txtfile. Here, we add a library calledsine_controller, which was written in the previous step:add_library(sine_controller SHARED src/sine_controller.cpp) - We can export the plugin of the controller by exploiting the
.xmlfile written earlier:pluginlib_export_plugin_description_file(controller_interface sine_controller.xml) - Remember to add the dependencies to the
sine_controllerlibrary and install the generated objects:ament_target_dependencies(sine_controllerrclcpp controller_interface pluginlib)install( TARGETS sine_controllerLIBRARY DESTINATION lib)
Before configuring the controller, use the colcon build command to compile the workspace and source it. We are now ready to add the controller to the robot.
Step 4 – Configuring the controller
Section titled “Step 4 – Configuring the controller”Now, the controller is ready to be inserted into the simulated robot model:
- Let’s move into the package where the robot model is implemented (in our case, the
two_joints_robotpackage). Here, let’s add the dependency to theCMakeLists.txtfile:find_package(sine_ctrl REQUIRED)
Next, we need to modify the controller.yaml file adding the sinusoidal controller.
- First, define the controller type:
sine_controller:type: sine_controller/SineController
- Then, configure the controller:
sine_controller:ros__parameters:update_rate: 100joints:- base_joint- link1_link2
- Finally, request the loading of the controller from the
start_simulaunch file:load_velocity_controller = ExecuteProcess(cmd=['ros2', 'control', 'load_controller', '--set-state', 'inactive', 'sine_controller'])
Step 5 – Starting the controller
Section titled “Step 5 – Starting the controller”We already saw how to start and activate the controller. Compile and source the workspac and then start the simulation using the following command:
ros2 launch two_joints_robot start_simu.launch.pyYou can check whether the controller is present in the controller list with this command:
ros2 control list_controllersvelocity_control [forward_command_controller/ForwardCommandController] inactivejoint_state_broadcaster[joint_state_broadcaster/JointStateBroadcaster] activeposition_control [forward_command_controller/ForwardCommandController] activesine_controller [sine_controller/SineController] inactiveAs you can see, position_control is active, while sine_controller and velocity_control are inactive. Let’s now shut down the position controller by turning on the sine_controller. The switch_controllers method of the ros2 control command allows you to do both steps at the same time:
ros2 control switch_controllers --activate sine_controller --deactivate position_controlNow, the controller is active, but the robot on Gazebo is not moving. This is because we have to set the sinusoidal parameters. We can do this with the following command:
ros2 topic pub /sine_param std_msgs/msg/Float32MultiArray "{data: [1.3, 0.1, 0.02, 0.1]}"Looking at the Gazebo scene, you can see that both the joints are moving, demonstrating the effectiveness of the controller. This motion is depicted in Figure 6.4.

Figure 6.4: The motion of the robot actuated using sine_controller
Figure 6.4: The motion of the robot actuated using sine_controller
Of course, the motion depicted in Figure 6.4 is never-ending and cyclical. To stop the robot’s motion, sine_controller must be deactivated.
ros2_control on real robots
Section titled “ros2_control on real robots”In this chapter, we explored how to use standard controllers on simulated robots and how to design new ones. However, many modern robots rely on the ros2_control framework. This framework enables the native integration of controllers to operate actuators and control the robot base. A notable example is the Take It And Go (TIAGo) platform developed by the Spanish robotics company PAL Robotics. TIAGo is a mobile manipulator robot that combines a mobile base with one or two arms and a pan-and-tilt head. It is widely used in industrial and research tasks.
TIAGo leverages the ros2_control framework to manage its hardware interfaces for mobility, manipulation, and sensors. The specific controllers used depend on the robot’s configuration (e.g., base, arm, or sensors) and its intended use. The following are the common types of controllers typically employed by TIAGo:
- Base controllers (
diff_drive_controller): Manages the differential drive base providing velocity control for the wheels, enabling the robot to move and rotate in 2D space. - Arm controllers:
position_controllers/JointPositionController: Controls the arm’s joints individually or as a group for static positions or trajectorieseffort_controllers/JointEffortController: Provides low-level effort control for specific joints, often used in research or advanced tasksjoint_trajectory_controller: Enables trajectory-based control of the arm, facilitating smooth motion between waypoints in Cartesian or joint space
- Gripper controller (
gripper_controllerorposition_controllersfor gripper joints): Tiago is endowed with a gripper to perform object manipulation. This controller is used to control the opening and closing of the gripper fingers for grasping tasks. - Head controllers (
position_controllers/JointPositionController): Manages the pan and tilt movements of the robot’s head. - Torso controllers (
position_controllers/JointPositionController): Adjusts the height of the torso to provide flexibility for tasks requiring varying workspace levels.
TIAGo uses additional controllers to manage its sensors, such as the IMU and the force-torque sensor, which can be installed between the robot arm and the gripper. This demonstrates how TIAGo effectively integrates multiple controllers to handle the diverse components of its platform. It combines a mobile base and various actuators that need to be controlled simultaneously, making it an excellent example of managing heterogeneous systems.
Summary
Section titled “Summary”In this chapter, we discussed a fundamental problem of all robotic systems: how to control the motors of the robot. The main solution offered by ROS 2 is provided from the ros2_control framework, a collection of packages allowing developers to directly contact the robot hardware. ROS 2 already comes with a series of controllers: both basic controllers that directly forward a desired command to a hardware interface, and something more complex, such as the differential drive controller (diff_drive_controller) that transforms the input data to desired commands for the joints.
Another possibility offered by the ros2_control framework is the possibility of implementing a custom controller to perform specific actions. This topic was discussed with the implementation of a controller moving the joints of a simulated robot in Gazebo.
In this chapter, we discussed the possibility of controlling a robot from a low-level point of view; in the next chapter, we will see how to schedule and handle the execution of the high-level action of an autonomous agent using the behavior tree formalism, using the BehaviorTree.cpp library integrated with ROS 2.
References
Section titled “References”- [1] https://control.ros.org/humble/index.html
- [2] https://github.com/ros-controls/ros2_control
- [3] https://control.ros.org/humble/doc/ros2_control/hardware_interface/doc/hardware_interface_types_userdoc.html
- [4] https://control.ros.org/rolling/doc/ros2_control/controller_manager/doc/userdoc.html
- [5] https://github.com/ros-controls/ros2_control_demos
- [6] https://pal-robotics.com/es/robot/tiago/
- [7] https://pal-robotics.com/