In ROS 2, a node parameter is a configurable value used to adjust a node's behavior without modifying its code. Parameters are important because they provide flexibility, allowing dynamic tuning and reusability of nodes across different scenarios. For instance say you had a ROS node that took data from a USB camera and published it to a topic. You could use parameters to set the frame rate, USB port, and color depth.
ROS 2 Parameters CLI
The following command are help full when you are debugging or tracking down a problem.
Command to list parameters
ros2paramlist/node_name
Command to get parameter value
ros2paramget/node_nameparam_name
Adding ROS 2 Parameters
Adding Parameters to a ROS 2 program is not that hard. Below you can see the steps.
#!/usr/bin/env python3importrclpyfromrclpy.nodeimportNodefromexample_interfaces.msgimportInt64classNumberPublisherNode(Node):def__init__(self):super().__init__("number_publisher")self.declare_parameter("number_to_publish",2)self.declare_parameter("publish_frequency",1.0)self.number_=self.get_parameter("number_to_publish").valueself.publish_frequency_=self.get_parameter("publish_frequency").valueself.number_publisher_=self.create_publisher(Int64,"number",10)self.number_timer_=self.create_timer(1.0/self.publish_frequency_,self.publish_number)self.get_logger().info("Number publisher has been started.")defpublish_number(self):msg=Int64()msg.data=self.number_self.number_publisher_.publish(msg)defmain(args=None):rclpy.init(args=args)node=NumberPublisherNode()rclpy.spin(node)rclpy.shutdown()if__name__=="__main__":main()
#include"rclcpp/rclcpp.hpp"#include"example_interfaces/msg/int64.hpp"classNumberPublisherNode:publicrclcpp::Node{public:NumberPublisherNode():Node("number_publisher"){this->declare_parameter("number_to_publish",2);this->declare_parameter("publish_frequency",1.0);number_=this->get_parameter("number_to_publish").as_int();doublepublish_frequency=this->get_parameter("publish_frequency").as_double();number_publisher_=this->create_publisher<example_interfaces::msg::Int64>("number",10);number_timer_=this->create_wall_timer(std::chrono::milliseconds((int)(1000.0/publish_frequency)),std::bind(&NumberPublisherNode::publishNumber,this));RCLCPP_INFO(this->get_logger(),"Number publisher has been started.");}private:voidpublishNumber(){automsg=example_interfaces::msg::Int64();msg.data=number_;number_publisher_->publish(msg);}intnumber_;rclcpp::Publisher<example_interfaces::msg::Int64>::SharedPtrnumber_publisher_;rclcpp::TimerBase::SharedPtrnumber_timer_;};intmain(intargc,char**argv){rclcpp::init(argc,argv);autonode=std::make_shared<NumberPublisherNode>();rclcpp::spin(node);rclcpp::shutdown();return0;}