In this tutorial, we’ll explore the power of parameters in ROS 2. Parameters are important for creating flexible and dynamic robot software.
You’ll learn how to define, access, and use parameters within your nodes, enabling you to customize your robot’s behavior without altering its code.
Join me as we dive into the essentials of parameters, setting the foundation for more complex robotics applications.
Real-World Applications
Here are some real-world examples of how ROS 2 parameters can be used in robotic arm applications:
- Joint Limits and Velocities: Parameters can be used to define the safe operating range (minimum and maximum) for each joint of the arm in terms of angles or positions. Additionally, they can set the maximum allowed speed for each joint during movement. This ensures safe and controlled operation, preventing damage to the robot or its surroundings.
- Payload Capacity: This parameter specifies the maximum weight the arm can safely carry while maintaining stability and avoiding damage to its motors or gears. This parameter is important for tasks like picking and placing objects or performing assembly operations.
- Path Planning Parameters: These parameters influence how the arm plans its trajectory to reach a target point. They can include factors like joint acceleration/deceleration rates, smoothness of the path, and collision avoidance settings.
- End-effector Calibration: Parameters can store calibration data for the gripper or any tool attached to the end of the arm. This data can include offsets, transformations, or specific configurations for different tools, ensuring accurate tool positioning during tasks.
As you can see, pretty much any variable that applies to your robot can be declared as a parameter in ROS 2. Parameters are used to configure nodes at startup (and during runtime), without changing the code.
Remember, a ROS 2 node is a mini-program (written in either Python or C++) that performs a specific task within a robot system.
Prerequisites
- You have created a ROS 2 workspace.
- You have created a ROS 2 package.
- You have Visual Studio code installed (optional but helpful)
- You have created a ROS 2 publisher.
- You have created a ROS 2 subscriber.
Here is the GitHub repository that contains the code we will develop in this tutorial.
Write the Code
Let’s start by creating a ROS 2 node that declares two parameters (a floating-point value and a string) and includes a function that executes anytime one of the parameters changes.
Open a terminal, and type these commands to open VS Code.
cd ~/ros2_ws
code .
Right-click on src/cobot_arm_examples/scripts folder, and create a new file called “minimal_py_parameters.py”.
Type the following code inside minimal_py_parameters.py:
#! /usr/bin/env python3
"""
Description:
This ROS 2 node demonstrates how to declare parameters.
-------
Publishing Topics:
None
-------
Subscription Topics:
None
-------
Author: Addison Sears-Collins
Date: March 4, 2024
"""
import rclpy # Import the ROS 2 client library for Python
from rclpy.node import Node # Import the Node class for creating ROS 2 nodes
from rcl_interfaces.msg import ParameterDescriptor # Enables the description of parameters
from rcl_interfaces.msg import SetParametersResult # Handles responses to parameter change requests
from rclpy.parameter import Parameter # Handles parameters within a node
class MinimalParameter(Node):
"""Create MinimalParameter node.
"""
def __init__(self):
""" Create a custom node class for declaring parameters.
"""
# Initialize the node with a name
super().__init__('minimal_parameter_node')
# Describe parameters
velocity_limit_descriptor = ParameterDescriptor(
description='Maximum allowed angular velocity in radians per second (ignored for fixed joints)')
robot_name_descriptor = ParameterDescriptor(description='The name of the robot')
# Declare parameters
self.declare_parameter('velocity_limit', 2.792527, velocity_limit_descriptor)
self.declare_parameter('robot_name', 'Automatic Addison Bot', robot_name_descriptor)
# Register a callback function that will be called whenever there is an attempt to
# change one or more parameters of the node.
self.add_on_set_parameters_callback(self.parameter_change_callback)
def parameter_change_callback(self, params):
"""Gets called whenever there is an attempt to change one or more parameters.
Args:
params (List[Parameter]): A list of Parameter objects representing the parameters that are
being attempted to change.
Returns:
SetParametersResult: Object indicating whether the change was successful.
"""
result = SetParametersResult()
# Iterate over each parameter in this node
for param in params:
# Check the parameter's name and type
if param.name == "velocity_limit" and param.type_ == Parameter.Type.DOUBLE:
# This parameter has changed. Display the new value to the terminal.
self.get_logger().info("Parameter velocity_limit has changed. The new value is: %f" % param.value)
# The parameter change was successfully handled.
result.successful = True
if param.name == "robot_name" and param.type_ == Parameter.Type.STRING:
self.get_logger().info("Parameter robot_name has changed. The new value is: %s" % param.value)
result.successful = True
return result
def main(args=None):
"""Main function to start the ROS 2 node.
Args:
args (List, optional): Command-line arguments. Defaults to None.
"""
# Initialize ROS 2 communication
rclpy.init(args=args)
# Create an instance of the MinimalParameter node
minimal_parameter_node = MinimalParameter()
# Keep the node running and processing events.
rclpy.spin(minimal_parameter_node)
# Destroy the node explicitly
# (optional - otherwise it will be done automatically
# when the garbage collector destroys the node object)
minimal_parameter_node.destroy_node()
# Shutdown ROS 2 communication
rclpy.shutdown()
if __name__ == '__main__':
# Execute the main function if the script is run directly
main()
Modify the CMakeLists.txt File
Now let’s configure the CMakeLists.txt file. Here is what it should look like:
cmake_minimum_required(VERSION 3.8)
project(cobot_arm_examples)
# Check if the compiler being used is GNU's C++ compiler (g++) or Clang.
# Add compiler flags for all targets that will be defined later in the
# CMakeLists file. These flags enable extra warnings to help catch
# potential issues in the code.
# Add options to the compilation process
if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
add_compile_options(-Wall -Wextra -Wpedantic)
endif()
# Locate and configure packages required by the project.
find_package(ament_cmake REQUIRED)
find_package(ament_cmake_python REQUIRED)
find_package(rclcpp REQUIRED)
find_package(rclpy REQUIRED)
find_package(rcl_interfaces REQUIRED)
find_package(std_msgs REQUIRED)
# Define a CMake variable named dependencies that lists all
# ROS 2 packages and other dependencies the project requires.
set(dependencies
rclcpp
rcl_interfaces
std_msgs
)
# Add the specified directories to the list of paths that the compiler
# uses to search for header files. This is important for C++
# projects where you have custom header files that are not located
# in the standard system include paths.
include_directories(
include
)
# Tells CMake to create an executable target named minimal_cpp_publisher
# from the source file src/minimal_cpp_publisher.cpp. Also make sure CMake
# knows about the program's dependencies.
add_executable(minimal_cpp_publisher src/minimal_cpp_publisher.cpp)
ament_target_dependencies(minimal_cpp_publisher ${dependencies})
add_executable(minimal_cpp_subscriber src/minimal_cpp_subscriber.cpp)
ament_target_dependencies(minimal_cpp_subscriber ${dependencies})
# Copy necessary files to designated locations in the project
install (
DIRECTORY cobot_arm_examples scripts
DESTINATION share/${PROJECT_NAME}
)
install(
DIRECTORY include/
DESTINATION include
)
# Install cpp executables
install(
TARGETS
minimal_cpp_publisher
minimal_cpp_subscriber
DESTINATION lib/${PROJECT_NAME}
)
# Install Python modules for import
ament_python_install_package(${PROJECT_NAME})
# Install Python executables
install(
PROGRAMS
scripts/minimal_py_publisher.py
scripts/minimal_py_subscriber.py
scripts/minimal_py_parameters.py
#scripts/example3.py
#scripts/example4.py
#scripts/example5.py
#scripts/example6.py
#scripts/example7.py
DESTINATION lib/${PROJECT_NAME}
)
# Automates the process of setting up linting for the package, which
# is the process of running tools that analyze the code for potential
# errors, style issues, and other discrepancies that do not adhere to
# specified coding standards or best practices.
if(BUILD_TESTING)
find_package(ament_lint_auto REQUIRED)
# the following line skips the linter which checks for copyrights
# comment the line when a copyright and license is added to all source files
set(ament_cmake_copyright_FOUND TRUE)
# the following line skips cpplint (only works in a git repo)
# comment the line when this package is in a git repo and when
# a copyright and license is added to all source files
set(ament_cmake_cpplint_FOUND TRUE)
ament_lint_auto_find_test_dependencies()
endif()
# Used to export include directories of a package so that they can be easily
# included by other packages that depend on this package.
ament_export_include_directories(include)
# Generate and install all the necessary CMake and environment hooks that
# allow other packages to find and use this package.
ament_package()
Build the Workspace
Open a new terminal window, and type the following commands:
cd ~/ros2_ws/
colcon build
source ~/.bashrc
Run the Node
In this section, we will finally run our node. Open a terminal window, and type:
ros2 run cobot_arm_examples minimal_py_parameters.py
Now, press Enter.
Open a new terminal window.
What are the currently active nodes?
ros2 node list
List all the parameters for all nodes in the ROS2 system.
ros2 param list
Retrieve the value of a specific parameter for a node.
ros2 param get /minimal_parameter_node robot_name
ros2 param get /minimal_parameter_node velocity_limit
Set the value of a specific parameter for a specified node.
ros2 param set /minimal_parameter_node robot_name '!!str New Automatic Addison Bot'
You should see “Set parameter successful”.
Double check the new value:
ros2 param get /minimal_parameter_node robot_name
ros2 param set /minimal_parameter_node velocity_limit 1.0
Now go back to the terminals where your scripts are running and press CTRL + C to stop the execution.
To clear the terminal window, type:
clear
That’s it! Keep building!