ROS 接口调参 加载参数 动态参数 从NodeHandle中加载参数

参数类型

ROS 参数服务器本质上是可以网络访问的参数词典, ROS 参数服务器能保存的数据类型包括字符串 、整型、浮点型、布尔型、列表、词典等;
参数根据类型不同可以分为全局参数、相对参数、私有参数等;
其中以 “/” 开头的参数为全局参数,以 开头的参数为私有参数,其他参数为相对参数;

参数接口

操作参数的四种方法:
ROS 提供了两种管理参数的 API 实时的存储、获取参数:
一个是通过 ros::param 命令空间                      一个是通过 ros::NodeHandle 接口
Launch 文件中加载参数
从参数文件中加载参数
通过动态参数 dynamic_reconfigure 接口调整参数

获取的两种方式:

通过NodeHandle操作参数

参数的设置、删除、获取、查询等操作方式。
void NodeHandle::setParam(const std::string& key, double d)                             设置
bool NodeHandle::deleteParam(const std::string& key)                                        删除
bool NodeHandle::getParam(const std::string& key, double& d)                           获取
bool NodeHandle::searchParam(const std::string& key, std::string& result_out)   查询
  

查看参数

ROS 中,
rosparam 命令可以用来查看参数。需注意,利用 rosparam 操作参数必须在 roscore 启动后才能
进行,主要方法有:
# 设置参数            $rosparam set [参数名 ]
# 删除参数            $rosparam delete
# 获取参数            $rosparam get [参数名 ]
# 查看参数列表     $rosparam list

从NodeHandle中加载参数---实例查看参数:

#include <ros/ros.h>

int main(int argc, char **argv){
    ros::init(argc,argv,"hello");        // 初始化节点
    ros::NodeHandle nh("~");             // 初始化句柄
    bool isRun = false;
    nh.setParam("is_run",true);          // 注入全局参数
    nh.setParam("/is_test",true);      
    if(nh.hasParam("is_run") == true){   // 判断是否有该节点
         nh.getParam("is_run",isRun);
         ROS_INFO("the status is %d",isRun);
    }else{
         ROS_INFO("the is_run status is not defined");
    }
    return 0;
}

从launch文件中加载参数

参数通过 param 标签实现。
参数为全局参数, param 标签作为 launch 标签的子标签
参数为相对参数, param 标签作为 node 标签的子标签
<launch>

<param name="serial" value="5"/>

<node name="client" pkg="example_3" type="client" output="screen">

<param name="client_x" type="int" value="1" />

</node>
</launch

从配置文件中加载参数

         YAML 是一种可读性高、轻量级的标记语言,
         广泛用于 ROS Spring 等框架的配置,它对大小写敏感,
         使用缩进表示层级关系,但缩进使用空格(2个或者4个)而非Tab 键表示。
         YAML 支持对象、数组、常量三种 数据类型。
参数配置在 YAML 文件中,注意冒号后面有空格
YAML 文件通常放置于程序包的 config 目录下
通过 launch 文件的 rosparam 标签加载配置文件来完成参数配置,添加路径
<launch> <node name="yaml" pkg="example_2" type="yaml" clear_params="true" output="screen"> 
    <!--相对参数--> 
    <rosparam file="$(find example_2)/config/test.yaml"/>
 </node> 
</launch>

加载参数示例

 步骤1: 创建 load.launch (从 Launch 中加载参数)
 步骤2: 创建配置文件 config/test.yaml
 步骤3: 创建 yaml.launch (从配置文件中加载参数)
 步骤4: 读取参数,创建 yaml.cpp
 步骤5: 修改 CMakeLists.txt
 步骤1: 创建load.launch
<launch>
   <param name="isLoad" type="bool" value="true"/>       #定义全局标签 bool 
   <node name="yaml" pkg="example_2" type="yaml" clear_params="true" output="screen">
   #四个相对应的参数
       <param name="first_name" type="string" value="fabio" />
       <param name="last_name" type="string" value="miao" />
       <param name="age" type="int" value="39" />
       <param name="score" type="int" value="150" />
   </node>
</launch>

 步骤2:创建配置文件config/test.yaml

first_name: fabio
last_name: miaozl
age: 37
score: 100


#注意中间一定需要空格

 步骤4:读取参数,创建yaml.cpp

#include <ros/ros.h>

int main(int argc, char **argv)
{
  ros::init(argc, argv, "yaml");           // 生成yaml的节点
  ros::NodeHandle nh;                      // 
  std::string first,last;
  int age = 0 , score = 100;
  bool isLoad = false;
  nh.getParam("/yaml/first_name",first);  // 读出节点中的值加入读出
  nh.getParam("/yaml/last_name",last);
  ROS_INFO("his first name is %s,his last name is %s",first.c_str(),last.c_str());  
  nh.getParam("/yaml/age",age);            // 读年龄 读分数
  ROS_INFO("first name is %d",age);
  nh.getParam("/yaml/score",score);
  ROS_INFO("first name is %d",score);
  nh.getParam("/isLoad",isLoad);
  if(isLoad){
    ROS_INFO("the param is load");
  }else{
    ROS_INFO("the param isn't load");
  }
}

 步骤5:修改CMakeLists.txt

主要添加修改文件 ---  编译link Libraries 库文件

cmake_minimum_required(VERSION 3.0.2)
project(example_2)

## Compile as C++11, supported in ROS Kinetic and newer
# add_compile_options(-std=c++11)

## Find catkin macros and libraries
## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz)
## is used, also find other catkin packages
find_package(catkin REQUIRED COMPONENTS
  roscpp
  rospy
  std_msgs
  message_generation
  dynamic_reconfigure
)

## System dependencies are found with CMake's conventions
# find_package(Boost REQUIRED COMPONENTS system)


## Uncomment this if the package has a setup.py. This macro ensures
## modules and global scripts declared therein get installed
## See http://ros.org/doc/api/catkin/html/user_guide/setup_dot_py.html
# catkin_python_setup()

################################################
## Declare ROS messages, services and actions ##
################################################

## To declare and build messages, services or actions from within this
## package, follow these steps:
## * Let MSG_DEP_SET be the set of packages whose message types you use in
##   your messages/services/actions (e.g. std_msgs, actionlib_msgs, ...).
## * In the file package.xml:
##   * add a build_depend tag for "message_generation"
##   * add a build_depend and a exec_depend tag for each package in MSG_DEP_SET
##   * If MSG_DEP_SET isn't empty the following dependency has been pulled in
##     but can be declared for certainty nonetheless:
##     * add a exec_depend tag for "message_runtime"
## * In this file (CMakeLists.txt):
##   * add "message_generation" and every package in MSG_DEP_SET to
##     find_package(catkin REQUIRED COMPONENTS ...)
##   * add "message_runtime" and every package in MSG_DEP_SET to
##     catkin_package(CATKIN_DEPENDS ...)
##   * uncomment the add_*_files sections below as needed
##     and list every .msg/.srv/.action file to be processed
##   * uncomment the generate_messages entry below
##   * add every package in MSG_DEP_SET to generate_messages(DEPENDENCIES ...)

## Generate messages in the 'msg' folder
# add_message_files(
#   FILES
#   Message1.msg
#   Message2.msg
# )

## Generate services in the 'srv' folder
# add_service_files(
#   FILES
#   Service1.srv
#   Service2.srv
# )

## Generate actions in the 'action' folder
# add_action_files(
#   FILES
#   Action1.action
#   Action2.action
# )

## Generate added messages and services with any dependencies listed here
# generate_messages(
#   DEPENDENCIES
#   std_msgs
# )

################################################
## Declare ROS dynamic reconfigure parameters ##
################################################

## To declare and build dynamic reconfigure parameters within this
## package, follow these steps:
## * In the file package.xml:
##   * add a build_depend and a exec_depend tag for "dynamic_reconfigure"
## * In this file (CMakeLists.txt):
##   * add "dynamic_reconfigure" to
##     find_package(catkin REQUIRED COMPONENTS ...)
##   * uncomment the "generate_dynamic_reconfigure_options" section below
##     and list every .cfg file to be processed

## Generate dynamic reconfigure parameters in the 'cfg' folder
 generate_dynamic_reconfigure_options(
   cfg/Test.cfg
 )

###################################
## catkin specific configuration ##
###################################
## The catkin_package macro generates cmake config files for your package
## Declare things to be passed to dependent projects
## INCLUDE_DIRS: uncomment this if your package contains header files
## LIBRARIES: libraries you create in this project that dependent projects also need
## CATKIN_DEPENDS: catkin_packages dependent projects also need
## DEPENDS: system dependencies of this project that dependent projects also need
catkin_package(
#  INCLUDE_DIRS include
#  LIBRARIES example_2
#  CATKIN_DEPENDS roscpp rospy std_msgs
#  DEPENDS system_lib
)

###########
## Build ##
###########

## Specify additional locations of header files
## Your package locations should be listed before other locations
include_directories(
# include
  ${catkin_INCLUDE_DIRS}
)

## Declare a C++ library
# add_library(${PROJECT_NAME}
#   src/${PROJECT_NAME}/example_2.cpp
# )

## Add cmake target dependencies of the library
## as an example, code may need to be generated before libraries
## either from message generation or dynamic reconfigure
# add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})

## Declare a C++ executable
## With catkin_make all packages are built within a single CMake context
## The recommended prefix ensures that target names across packages don't collide
# add_executable(${PROJECT_NAME}_node src/example_2_node.cpp)
add_executable(yaml src/yaml.cpp)
add_executable(param src/param.cpp)
## Rename C++ executable without prefix
## The above recommended prefix causes long target names, the following renames the
## target back to the shorter version for ease of user use
## e.g. "rosrun someones_pkg node" instead of "rosrun someones_pkg someones_pkg_node"
# set_target_properties(${PROJECT_NAME}_node PROPERTIES OUTPUT_NAME node PREFIX "")

## Add cmake target dependencies of the executable
## same as for the library above
# add_dependencies(${PROJECT_NAME}_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})

## Specify libraries to link a library or executable target against
# target_link_libraries(${PROJECT_NAME}_node
#   ${catkin_LIBRARIES}
# )
target_link_libraries(yaml
   ${catkin_LIBRARIES}
)
target_link_libraries(param
   ${catkin_LIBRARIES}
)
#############
## Install ##
#############

# all install targets should use catkin DESTINATION variables
# See http://ros.org/doc/api/catkin/html/adv_user_guide/variables.html

## Mark executable scripts (Python etc.) for installation
## in contrast to setup.py, you can choose the destination
# catkin_install_python(PROGRAMS
#   scripts/my_python_script
#   DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
# )

## Mark executables for installation
## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_executables.html
# install(TARGETS ${PROJECT_NAME}_node
#   RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
# )

## Mark libraries for installation
## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html
# install(TARGETS ${PROJECT_NAME}
#   ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
#   LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
#   RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
# )

## Mark cpp header files for installation
# install(DIRECTORY include/${PROJECT_NAME}/
#   DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
#   FILES_MATCHING PATTERN "*.h"
#   PATTERN ".svn" EXCLUDE
# )

## Mark other files for installation (e.g. launch and bag files, etc.)
# install(FILES
#   # myfile1
#   # myfile2
#   DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
# )

#############
## Testing ##
#############

## Add gtest based cpp test target and link libraries
# catkin_add_gtest(${PROJECT_NAME}-test test/test_example_2.cpp)
# if(TARGET ${PROJECT_NAME}-test)
#   target_link_libraries(${PROJECT_NAME}-test ${PROJECT_NAME})
# endif()

## Add folders to be run by python nosetests
# catkin_add_nosetests(test)

执行launch后得到

... logging to /home/xtark/.ros/log/deb4219e-2151-11ed-a25f-874955d4690a/roslaunch-xtark-vmpc-6737.log
Checking log directory for disk usage. This may take a while.
Press Ctrl-C to interrupt
Done checking log file disk usage. Usage is <1GB.

started roslaunch server http://xtark-vmpc:33649/

SUMMARY
========

CLEAR PARAMETERS
 * /yaml/

PARAMETERS
 * /isLoad: True
 * /rosdistro: noetic
 * /rosversion: 1.15.13
 * /yaml/age: 39
 * /yaml/first_name: fabio
 * /yaml/last_name: miao
 * /yaml/score: 150

NODES
  /
    yaml (example_2/yaml)

ROS_MASTER_URI=http://localhost:11311

process[yaml-1]: started with pid [6755]
[ INFO] [1661087150.225233609]: his first name is fabio,his last name is miao
[ INFO] [1661087150.226000645]: first name is 39
[ INFO] [1661087150.226231003]: first name is 150
[ INFO] [1661087150.226447102]: the param is load
[yaml-1] process has finished cleanly
log file: /home/xtark/.ros/log/deb4219e-2151-11ed-a25f-874955d4690a/yaml-1*.log
all processes on machine have died, roslaunch will exit
shutting down processing monitor...
... shutting down processing monitor complete
done

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
ROS(Robot Operating System)是一个开源的机器人操作系统,它为机器人应用程序提供了一个框架和一系列的工具。ROS参数服务器是一种非常有用的工具,用于配置机器人应用程序的参数,如机器人的传感器和执行器参数、控制算法的参数等等。在ROS参数服务器是一个全局的键值存储容器,它允许机器人的各个组件共享参数,并且可以在运行时动态修改参数。 在机器人的应用程序参数服务器通常用于存储和管理机器人的配置参数。例如,机器人的底盘控制节点可能需要访问机器人轮子的半径、轮距等参数,传感器节点可能需要访问传感器的采样频率、测量范围等参数。这些参数通常存储在yaml文件,然后由ROS参数服务器加载和管理。 YAML(YAML Ain't Markup Language)是一种轻量级的数据序列化格式,它可以非常方便地表示复杂的数据结构,并且易于阅读和编辑。在ROS,可以使用YAML文件来定义机器人的参数,然后通过参数服务器加载ROS节点。下面是一个简单的YAML文件示例: ``` robot_name: my_robot wheel_radius: 0.1 wheel_distance: 0.5 sensor: type: lidar range: 10.0 frequency: 20.0 ``` 这个文件定义了机器人的名称、轮子半径和轮距,以及一个激光雷达传感器的类型、测量范围和采样频率。可以使用ROS参数服务器将这些参数加载到机器人的各个节点: ``` rosparam load robot_params.yaml rosrun my_robot_controller my_robot_controller_node rosrun sensor_node sensor_node.py ``` 在这个例子,首先使用rosparam load命令将yaml文件加载ROS参数服务器,然后启动机器人的控制节点和传感器节点。这些节点可以使用ROS参数服务器来访问机器人的配置参数: ``` ros::NodeHandle nh; std::string robot_name; double wheel_radius, wheel_distance; nh.getParam("robot_name", robot_name); nh.getParam("wheel_radius", wheel_radius); nh.getParam("wheel_distance", wheel_distance); ``` 在这个例子,控制节点可以使用ros::NodeHandle对象来访问参数服务器的机器人名称、轮子半径和轮距参数。传感器节点也可以使用类似的方式来访问传感器的参数。 需要注意的是,ROS参数服务器是一个全局的存储容器,参数的命名规则和命名空间需要遵循ROS的命名规范。在实际应用,可以使用rosparam命令行工具或者ROS的API来操作参数服务器,例如设置参数、获取参数、删除参数等等。 总之,ROS参数服务器是一个非常有用的工具,它可以简化机器人应用程序的参数管理和配置,并且可以在运行时动态修改参数。通过使用YAML文件来定义机器人的参数,可以使参数的管理更加方便和可读性更高。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

忒懂先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值