Parameters in ROS 2

In this tutorial the parameters of ROS 2 will be worked

A parameter is like a global variable. A container were data can be stored globally and accessible by other nodes. Note that the parameters are not designed for high-performance and normally are used for static data.

The parameters can handle different type of messages like strings, floats, boolean... In this tutorial you can see how to create a ROS 2 parameter and how to read them.

In this tutorial will use the package created at tutorial #07

 ros2_ws/
  src/
    cpp_float/ #be creative and change this name
      src/
        parameters/
          test_parameters.cpp
        topics/
          listener_float.cpp
          talker_float.cpp
      CMakeLists.txt
      package.xml

#include <iostream>

#include "rclcpp/rclcpp.hpp"

int main(int argc, char ** argv)
{
  rclcpp::init(argc, argv);

  auto node = rclcpp::Node::make_shared("get_parameters");

  auto parameter_service = std::make_shared<rclcpp::parameter_service::ParameterService>(node);

  auto parameters_client = std::make_shared<rclcpp::parameter_client::SyncParametersClient>(node);
  //Set parameters
  auto set_parameters_results = parameters_client->set_parameters({
    rclcpp::parameter::ParameterVariant("parameter_number", 1),
    rclcpp::parameter::ParameterVariant("parameter_string", "hello"),
    rclcpp::parameter::ParameterVariant("parameter_boolean", true),

  });
  for (auto & result : set_parameters_results) {
    if (!result.successful) {
      std::cerr << "Failed to set parameter: " << result.reason << std::endl;
    } else {
      std::cerr << "Parameter set" << std::endl;
    }
  }

  // Get parameters
  for (auto & parameter : parameters_client->get_parameters({"parameter_number", "parameter_string", "parameter_boolean"})) {
    std::cout << "Parameter name: " << parameter.get_name() << std::endl;
    std::cout << "Parameter value (" << parameter.get_type_name() << "): " <<
      parameter.value_to_string() << std::endl;
  }

  return 0;
}

It is necessary to call the the new file at CMakeLists.txt file. Add the next line inside ´macro(targets)´

  custom_executable(parameters test_parameters)

The next command will build and install the new package

$ cd ~/ros2_ws
$ ament build --symlink-install --only-package cpp_float

Run the next command to test the package

$ test_parameters

The output should be this

Parameter set
Parameter set
Parameter set
Parameter name: parameter_number
Parameter value (integer): 1
Parameter name: parameter_string
Parameter value (string): hello
Parameter name: parameter_boolean
Parameter value (bool): true

Do you need more computing capacity in your robots? Stay tuned