Skip to content
ImagineWorld

Controlling Robots Using the ros2 control Package

node_idnode-book_mastering-ros-2-for-robotics-programming_chapter-06-controlling-robots-using-the-ros2-control-package
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num6
chapter_titleControlling Robots Using the ros2 control Package
governed_byCORPUS
constitutional_citationCONSTITUTION
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_control framework
  • The ros2_control framework architecture
  • Interfacing with simulated controllers using Gazebo
  • Interacting with the ros2_control framework using the CLI
  • Implementing a new controller

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.

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.
  • 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 system
      • RealtimePublisher: 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 the ros2_control ecosystem. 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 effort
      • FollowJointTrajectoryAction: 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_control framework, 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_control framework follow control theory principles, comparing reference values with measured outputs and calculating system inputs based on the error. Derived from ControllerInterface and exported as plugins via pluginlib, controllers such as forward_command_controller in ros2_controllers manage their lifecycle through the LifecycleNode class. In control-loop execution, the update() method accesses the latest hardware state and enables controllers to write to command interfaces.
  • Hardware components: Hardware components in the ros2_control framework communicate with physical hardware and are exported as plugins via pluginlib. 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.

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.

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_control GitHub repository [2]: The main repository for ros2_control on 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_control connects with various hardware interfaces.
  • Controller Manager documentation [4]: Detailed information on the Controller Manager node, its role, and its services can be found within the ROS 2 documentation.
  • The ros2_control_demos package [5]: This package contains example setups demonstrating how to use ros2_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.

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_cmake

You 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 urdf folder to contain the robot model file
  • A launch folder containing the files used to start the simulation
  • A config folder for the configuration file of the controllers.

We are now ready to develop the robot model file.

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 plate
      • link1 and link2, represented by cylinders
  • Two joints:
    • A revolute joint (called base_joint), connecting link1 with base_link
      • A prismatic joint (called link1_link2), connecting link2 with link1

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:

  1. If the ros2_control framework 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
  2. At the start, we’ll use pre-built controllers from the ros2_control package. 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: commands and states
  3. In the same section, the GazeboSimSystem plugin 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>
  4. For each joint we want to control using the ros2_control package, we must define which kind of command interface is available. Basic interfaces are in position and velocity. For both joints, we defined position and velocity as the command interface:
    <joint name="base_joint">
    <command_interface name="position" />
    <command_interface name="velocity" />
  5. Similarly, we must specify state_interface. This is the output of the actuator, which can be streamed via the /joint_state topic. In this case, we specify that the state of the actuator is composed of position, velocity, and effort. In addition, we can set an initial value for the motor as a parameter of state_interface in position:
    <state_interface name="position">
    <param name="initial_value">0.0</param>
    </state_interface>
    <state_interface name="velocity"/>
    </joint>
  6. 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>
  7. Finally, to add the controllers, we must include the ros2_control plugin. In this case, we need to import the gz_ros2_control-system plugin:
    <gazebo>
    <plugin filename="gz_ros2_control-system" name="gz_ros2_control::GazeboSimROS2ControlPlugin">
  8. This plugin needs a .yaml parameter file in which the controllers are configured. In this example, we placed the configuration file into the config folder and installed it by modifying CMakeList.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:

  1. 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 .yaml type:
    controller_manager:
    ros__parameters:
    update_rate: 100 # Hz
  2. 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_control and set its type to ForwardCommandController from the forward_command_controller package. This controller forwards input from the ROS2 topic 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/ForwardCommandController
    Velocity_control:
    type: forward_command_controller/ForwardCommandController
  3. A third controller added to the list is joint_state_broadcaster. This controller publishes the /joint_state topic with the information about the motor configuration:
    joint_state_broadcaster:
    type: joint_state_broadcaster/JointStateBroadcaster
  4. The controllers defined previously are configured here, where the joints that represent the target of the control action are specified:
    position_control:
    ros__parameters:
  5. We specify that both joints are controllable using the position_control controller. 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_link2
    interface_name: position
    state_interfaces:
    - position
    - velocity
  6. A similar configuration is made for the velocity, velocity_control. The difference here is that the interface_name value is velocity:
    velocity_control:
    ros__parameters:
    joints:
    - base_joint
    - link1_link2
    interface_name: velocity
    state_interfaces:
    - position
    - velocity
  7. 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 the ros2 control command with specific parameters. This is done using the ExecuteProcess function 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
  8. 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'])
  9. We repeat the same instructions for the position and velocity controllers. However, we should choose the command interface to use, since we cannot control the robot both in position and velocity at the same time. For this reason, we choose to activate only the position controller, while setting the velocity one to inactive:
    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'])
  10. 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.

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-install

After 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-demos

Assuming you already initialized and sourced the workspace, run the following commands:

  1. 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.

  1. For example, if you want to move a joint, you can directly publish the position command using the ros2 topic pub command:
    ros2 topic pub /position_control/commands std_msgs/msg/Float64MultiArray "{data: [3, 0]}"
  2. In this way, you request to move the first joint of the robot to 3 radians, while bringing the second joint to 0 radians. 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)

  1. Along with the controllers, the Controller Manager node has started as well. The Controller Manager node provides commands accessible via the command line to retrieve the state of the controllers and change their status. For example, using the list_controllers command, you can retrieve the list of current active controllers:
    ros2 control list_controllers
    joint_state_broadcaster[joint_state_broadcaster/JointStateBroadcaster] active
    position_control [forward_command_controller/ForwardCommandController] active
    velocity_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.

  1. You can switch controllers if you want to control the velocity of the actuator instead of the position. Activate velocity_control and deactivate position_control with the following:
    ros2 control switch_controllers --activate velocity_control --deactivate position_control
  2. You can now check the status of the controllers with the ros2 control command. Other useful commands are available in the ros2 control commands 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.

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.

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 pluginlib

The 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:

  1. Create a constructor to initialize member variables, although initialization can also occur in the on_init method.
  2. Implement the on_init method to perform initial setup, initialize variables, reserve memory, and declare node parameters.
  3. Implement the on_configure method to prepare the controller by reading parameters and completing any necessary setup before starting.
  4. Define the required interfaces using command_interface_configuration and state_interface_configuration.
  5. Implement the on_activate method. This checks and sorts interfaces, and assigns initial values. This method is called every time the controller has been activated.
  6. Implement the on_deactivate method. This method is called when the controller is deactivated.
  7. Implement the update method. This is the main loop of the controller, which runs with the controller frequency to update the input of the hardware interface.
  8. Export the controller class. Add the PLUGINLIB_EXPORT_CLASS macro at the end of your file after the namespace.

The source code implementing the described steps is shown in the following code blocks:

  1. At the start, we include the header files to use the ROS 2 function, access the controller interface, and handle the Float32MultiArray data. 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
  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 {
  3. Among the different variables, we have to provide the joint state interface with access to the current state of an actuator (position, velocity, and effort). The ros2_control framework implements this with LoanedStateInterface, 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>
  4. To use LoanedStateInterface, we define a type alias for a 2D vector of std::reference_wrapper<T>. The joint_state_interfaces_ variable uses this type to manage references to hardware_interface::LoanedStateInterface objects:
    using InterfaceReferences = std::vector<std::vector<std::reference_wrapper<T>>>;
    InterfaceReferences<hardware_interface::LoanedStateInterface> joint_state_interfaces_;
  5. Finally, a vector of string vectors is declared to define the interface name. We have to consider a new name for each joint and interface, such as joint_name/position, joint_name/velocity, joint_name_2/position, and so on:
    std::vector<std::vector<std::string>> state_interface_names_;
  6. 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_;
  7. 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, and frequency joint 2:
    rclcpp::Subscription<std_msgs::msg::Float32MultiArray>::SharedPtr sine_param_sub_;
    public:
    SineController() : controller_interface::ControllerInterface(), dt_(0, 0) {}
  8. The callback uses the received data to fill in amplitude and frequency defined 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];
    }
  9. 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 {
  10. 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 the state_interfaces_config_names vector:
    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.

  1. To effectively set the interfaces, we have to return the interface list. In this case, we specify them using the INDIVIDUAL property; 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};}
  2. 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");
  3. Also, in this case, we return the list of the INDIVIDUAL interfaces participating in the motor control:
    return {
    controller_interface::interface_configuration_type::INDIVIDUAL, command_interfaces_config_names};}
  4. In the on_configure function, 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));
  5. As for the _dt variable, it is the step time of the update function. The get_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 .yaml file 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;
  6. Then, we resize the command to the interface vectors. The state interface is the only one that needs four elements (two elements, velocity and position, 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);
  7. 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";
    }
  8. This function must return the eventual SUCCESS or FAILURE state 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 get FAILURE in return; however, it’s SUCCESS in our case:
    return controller_interface::CallbackReturn::SUCCESS;
    }
  9. Another function to implement is the on_activate function. This function is called when the controller passes from an inactive to active state:
    controller_interface::CallbackReturn on_activate(const rclcpp_lifecycle::State &) {
    for(int i = 0; i < J_SIZE; i++)
  10. We call the get_ordered_interfaces function from the controller_interface namespace, 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]);
  11. 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");
  12. The local time variable, used to calculate the sinusoidal signal, is reset every time the controller is activated. Finally, we set the SUCCESS state 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;
}
  1. Finally, we can write the update function. 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 & ) {
  2. 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_));
  3. 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;
    }};}
  4. We are now ready to install the plugin. At this stage, we use the PLUGINLIB_EXPORT_CLASS macro. This macro is defined in the pluginlib/class_list_macros.hpp header 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 is controller_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:

  1. First, we define a .xml file called sine_controller.xml describing the plugin class. This file is called from the CMakeLists.txt file, 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>
  2. Now, we can edit the CMakeLists.txt file. Here, we add a library called sine_controller, which was written in the previous step:
    add_library(sine_controller SHARED src/sine_controller.cpp)
  3. We can export the plugin of the controller by exploiting the .xml file written earlier:
    pluginlib_export_plugin_description_file(controller_interface sine_controller.xml)
  4. Remember to add the dependencies to the sine_controller library and install the generated objects:
    ament_target_dependencies(sine_controller
    rclcpp controller_interface pluginlib
    )
    install( TARGETS sine_controller
    LIBRARY 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.

Now, the controller is ready to be inserted into the simulated robot model:

  1. Let’s move into the package where the robot model is implemented (in our case, the two_joints_robot package). Here, let’s add the dependency to the CMakeLists.txt file:
    find_package(sine_ctrl REQUIRED)

Next, we need to modify the controller.yaml file adding the sinusoidal controller.

  1. First, define the controller type:
    sine_controller:
    type: sine_controller/SineController
  2. Then, configure the controller:
    sine_controller:
    ros__parameters:
    update_rate: 100
    joints:
    - base_joint
    - link1_link2
  3. Finally, request the loading of the controller from the start_simu launch file:
    load_velocity_controller = ExecuteProcess(
    cmd=['ros2', 'control', 'load_controller', '--set-state', 'inactive', 'sine_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.py

You can check whether the controller is present in the controller list with this command:

ros2 control list_controllers
velocity_control [forward_command_controller/ForwardCommandController] inactive
joint_state_broadcaster[joint_state_broadcaster/JointStateBroadcaster] active
position_control [forward_command_controller/ForwardCommandController] active
sine_controller [sine_controller/SineController] inactive

As 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_control

Now, 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.

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 trajectories
      • effort_controllers / JointEffortController: Provides low-level effort control for specific joints, often used in research or advanced tasks
      • joint_trajectory_controller: Enables trajectory-based control of the arm, facilitating smooth motion between waypoints in Cartesian or joint space
  • Gripper controller (gripper_controller or position_controllers for 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.

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.