ROS2与C++入门教程-使用参数
ROS2与C++入门教程-使用参数
说明:
- 介绍如何在ros2中使用参数
步骤:
- 创建包
cd ~/dev_ws/src
ros2 pkg create --build-type ament_cmake cpp_parameters --dependencies rclcpp
- 新增cpp_parameters_node.cpp文件在dev_ws/src/cpp_parameters/src目录
- 内容如下:
#include <rclcpp/rclcpp.hpp>
#include <chrono>
#include <string>
#include <functional>
using namespace std::chrono_literals;
class ParametersClass: public rclcpp::Node
{
public:
ParametersClass()
: Node("parameter_node")
{
this->declare_parameter<std::string>("my_parameter", "world");
timer_ = this->create_wall_timer(
1000ms, std::bind(&ParametersClass::respond, this));
}
void respond()
{
this->get_parameter("my_parameter", parameter_string_);
RCLCPP_INFO(this->get_logger(), "Hello %s", parameter_string_.c_str());
}
private:
std::string parameter_string_;
rclcpp::TimerBase::SharedPtr timer_;
};
int main(int argc, char** argv)
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<ParametersClass>());
rclcpp::shutdown();
return 0;
}
- 修改CMakeLists.txt
- 内容如下:
add_executable(parameter_node src/cpp_parameters_node.cpp)
ament_target_dependencies(parameter_node rclcpp)
install(TARGETS
parameter_node
DESTINATION lib/${PROJECT_NAME}
)
- 安装依赖
cd ~/dev_ws/
rosdep install -i --from-path src --rosdistro foxy -y
- 编译
colcon build --packages-select cpp_parameters
- 运行
. install/setup.bash
ros2 run cpp_parameters parameter_node
- 查看值:
ros2 param get /parameter_node my_parameter
在终端下更改参数值:
- 运行节点:
ros2 run cpp_parameters parameter_node
- 新开终端,显示参数列表
ros2 param list
- 更改值
ros2 param set /parameter_node my_parameter earth
- 新开终端,查看
ros2 param get /parameter_node my_parameter
在launch文件中更改参数值:
- 新建cpp_parameters_launch.py,在~/dev_ws/src/cpp_parameters/launch目录下
- 内容如下:
from launch import LaunchDescription
from launch_ros.actions import Node
def generate_launch_description():
return LaunchDescription([
Node(
package="cpp_parameters",
executable="parameter_node",
name="custom_parameter_node",
output="screen",
emulate_tty=True,
parameters=[
{"my_parameter": "earth"}
]
)
])
- 更改CMakelist.txt
install(
DIRECTORY launch
DESTINATION share/${PROJECT_NAME}
)
- 重新编译
colcon build --packages-select cpp_parameters
- 运行
. install/setup.bash
ros2 launch cpp_parameters cpp_parameters_launch.py
- 效果如下:
[parameter_node-1] [INFO] [custom_parameter_node]: Hello earth
获取最新文章: 扫一扫右上角的二维码加入“创客智造”公众号