ROS动态调参总结

在ROS程序中我们可以使用dynamic_reconfigure这个包实现动态调参,无需重新编译程序。

一. 主要步骤

  1. 在欲动态调参的功能包(比如pc_process)下新建cfg文件夹和相关cfg文件
mkdir cfg
cd cfg
gedit .cfg

planeSeg.cfg内容如下:

#!/usr/bin/env python
# coding=UTF-8

PACKAGE = "hello_ros"
# 包名

from dynamic_reconfigure.parameter_generator_catkin import *
#初始化ROS,并导入参数生成器

gen = ParameterGenerator()
#添加参数 (name , typt, level, description, default, min,max)
gen.add("int_param",    int_t,    0, "An Integer parameter", 1,   0, 100)
gen.add("double_param", double_t, 0, "A double parameter",   0.1, 0,   1)
gen.add("str_param",    str_t,    0, "A string parameter",  "Chapter2_dynamic_reconfigure")
gen.add("bool_param",   bool_t,   0, "A Boolean parameter",  True)

size_enum = gen.enum([ gen.const("Low",      int_t, 0, "Low is 0"),
                       gen.const("Medium",   int_t, 1, "Medium is 1"),
                       gen.const("High",     int_t, 2, "Hight is 2")],
                     "Select from the list")

gen.add("size", int_t, 0, "Select from the list", 1, 0, 3, edit_method=size_enum)

#生成必要文件并退出
exit(gen.generate(PACKAGE, "pc_process", "planeSeg")
#注意包名 以及cfg文件名 尤其是最后一个参数,很关键

修改cfg权限

sudo chmod 777 planeSeg.cfg

在CMakeLists文件中添加:

find_package(catkin REQUIRED COMPONENTS
  dynamic_reconfigure
)
##################
#add dynamic reconfigure api
generate_dynamic_reconfigure_options(
 cfg/planeSeg.cfg
 #...
 )

二.在cpp文件中添加回调函数

void paraCallback(pc_process::planeSegConfig &config, uint32_t level) {
  ROS_INFO("Reconfigure Request: %f", 
            config.threshold);
}

添加头文件:

#include <dynamic_reconfigure/server.h>
#include <pc_process/planeSegConfig.h> //planeSeg就是参数配置文件

修改主函数:

int main (int argc, char** argv)
{
  // Initialize ROS
  ros::init (argc, argv, "pc_process");//声明节点的名称
  ros::NodeHandle nh;
 
  float threshold=0.15;

  dynamic_reconfigure::Server<pc_process::planeSegConfig> server;
  dynamic_reconfigure::Server<pc_process::planeSegConfig>::CallbackType ff;

  ff = boost::bind(&paraCallback, _1, _2);
  server.setCallback(ff);
  // Create a ROS subscriber for the input point cloud
// 为接受点云数据创建一个订阅节点
// 回调函数多参数,阈值默认为0.15
// boost::bind(),_1为占位符,表示“input”是第一个参数
  ros::Subscriber sub = nh.subscribe<sensor_msgs::PointCloud2> ("input", 1, boost::bind(&cloudCallback,_1,threshold));
 
  // Create a ROS publisher for the output point cloud
//创建ROS的发布节点
  pub = nh.advertise<sensor_msgs::PointCloud2> ("output", 1);
 
  // Spin
// 回调
  ros::spin ();
}

使用boost::bind给回调函数传递动态参数
boost::bind(f,x,y) = f(x,y)
_1,_2表示占位符

修改CMakelists文件:

add_executable(pc_process src/pointcloud.cpp)
add_dependencies(pc_process ${PROJECT_NAME}_gencfg)
target_link_libraries(pc_process ${catkin_LIBRARIES})

修改package.xml文件:

<build_depend>dynamic_reconfigure</build_depend>

编译
运行程序

三. 使用动态调参

rosrun rqt_reconfigure rqt_reconfigure
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。