ROS-编写工作区、功能包、节点
新建工作区,chapt2_ws 文件夹就是一个工作区
mkdir -p chapt2_ws/src
新建功能包,功能包命名为 example_cpp,放在 chapt2_ws/src/ 中
cd chapt2_ws/src
ros2 pkg create example_cpp --build-type ament_cmake --dependencies rclcpp
- pkg create 是创建包的意思
- –build-type 用来指定该包的编译类型,一共有三个可选项
ament_python
、ament_cmake
、cmake
- –dependencies 指的是这个功能包的依赖,这里小鱼给了一个ros2的C++客户端接口
rclcpp
新建节点,在 example_cpp/src 中创建 node_01.cpp 文件,此为一个节点,文件内容为:
#include "rclcpp/rclcpp.hpp"int main(int argc, char **argv)
{/* 初始化rclcpp */rclcpp::init(argc, argv);/*产生一个node_01的节点*/auto node = std::make_shared<rclcpp::Node>("node_01");// 打印一句自我介绍RCLCPP_INFO(node->get_logger(), "node_01节点已经启动.");/* 运行节点,并检测退出信号 Ctrl+C*/rclcpp::spin(node);/* 停止运行 */rclcpp::shutdown();return 0;
}
修改 CMakeLists.txt,加入下面三行
add_executable(node_01 src/node_01.cpp)
ament_target_dependencies(node_01 rclcpp)
install(TARGETS node_01 DESTINATION lib/${PROJECT_NAME})# 若还有其他节点
add_executable(node_02 src/node_02.cpp)
ament_target_dependencies(node_02 rclcpp)
install(TARGETS node_02 DESTINATION lib/${PROJECT_NAME})
在工作空间 chapt2_ws 目录进行编译
colcon buildsource install/setup.bashros2 run example_cpp node_01