ROS(六)----参数
一、基本方法
ROS 获取参数的方式:
ros::param::get()
ros::NodeHandle::getParam()
ros::NodeHandle::param()
ROS 设置参数的方式:
ros::param::set()
ros::NodeHandle::setParam()
二、示例
#include "ros/ros.h" #include <cstdlib> using namespace std; int main (int argc,char **argv) { // initial node and name ros::init(argc,argv,"node_param"); // 检查参数个数 if(argc!=2) { cout<<"Error command paramter"<<endl; return 0; } //create node handle ros::NodeHandle nh; //param variable int IntParam; string StrParam; bool isIntParam, isStrParam; // mod flag int flag = atoi(argv[1]); switch(flag) { case 1: ROS_INFO("set param mod---- ros::param::set(): "); ros::param::set("IntParam",1); ros::param::set("StrParam","stringdemo"); break; case 2: ROS_INFO("set param mod---- ros::NodeHandle::setParam(): "); nh.setParam("IntParam",1); nh.setParam("strrParam","stringdemo"); break; case 3: ROS_INFO("get param mod---- ros::param::get(): "); isIntParam = ros::param::get("IntParam",IntParam); isStrParam = ros::param::get("StrParam",StrParam); if(isIntParam) ROS_INFO("IntParam=%d",IntParam); else ROS_INFO("Get IntParam fail! "); if(isStrParam) ROS_INFO("StrParam=%s",StrParam.c_str()); else ROS_INFO("Get StrParam fail! "); break; case 4: ROS_INFO("get param mod---- ros::NodeHandle::getParam(): "); isIntParam = nh.getParam("IntParam",IntParam); isStrParam = nh.getParam("StrParam",StrParam); if(isIntParam) ROS_INFO("IntParam=%d",IntParam); else ROS_INFO("Get IntParam fail! "); if(isStrParam) ROS_INFO("StrParam=%s",StrParam.c_str()); else ROS_INFO("Get StrParam fail! "); break; case 5: // 此方法可以设置默认数据 ROS_INFO("get param mod---- ros::NodeHandle::param(): "); isIntParam = nh.param("IntParam",IntParam,11); isStrParam = nh.param<std::string>("StrParam",StrParam,"stringdemo_default"); if(isIntParam) ROS_INFO("IntParam=%d",IntParam); else ROS_INFO("Get IntParam fail! "); if(isStrParam) ROS_INFO("StrParam=%s",StrParam.c_str()); else ROS_INFO("Get StrParam fail! "); break; default: ROS_INFO("flag=%d.is not in range [1,5]",flag); break; } return 0; }
运行节点:
rosrun params book_param 1
查看参数命令:
rosparam list
获取参数命令行:
rosparam get StrParam