ROS 2 Parameters tutorials

Parameters allow you to configure nodes at runtime. These are used to tune node behavior without needing to modify the code. For example, you can set parameters to define the robot's speed or the dimensions of a sensor's scan area.

Example: Using Parameters in ROS 2

  1. Create a Node with Parameters:

    • Open a new file simple_param_node.py and add this code:

      import rclpy
      from rclpy.node import Node
      
      class ParamNode(Node):
          def __init__(self):
              super().__init__('param_node')
              self.declare_parameter('speed', 1.0)  # Declare a parameter with default value
              self.get_logger().info(f'Speed: {self.get_parameter("speed").value}')
      
      def main(args=None):
          rclpy.init(args=args)
          node = ParamNode()
          rclpy.spin(node)
          node.destroy_node()
          rclpy.shutdown()
      
      if __name__ == '__main__':
          main()
  2. Run the Node with Parameters:

    • You can change the parameter value when running the node:

      ros2 run my_package simple_param_node --ros-args -p speed:=2.5

    This will print:

    [INFO] [<timestamp>] [param_node]: Speed: 2.5

    The parameter speed was updated from the default value 1.0 to 2.5 at runtime.

Last updated