目录
1. 创建工程目录
mkdir -p project/src
2. 创建功能包
# 1. 创建 C/C++ 功能包 命令行
ros2 pkg create --build-type ament_cmake node_name --dependencies rclcpp std_msgs
# 2. 创建 Python 功能包 命令行
ros2 pkg create --build-type ament_python node_name
# 注意:
ament_cmake 使用 C/C++ 的功能包
ament_python 使用 Python 功能包
3. 创建节点源文件
1. 进入 src 目录
cd ./project/src/
2. 编写代码:
vi ./test/src/test.cpp
3. 填入内容:
#include <chrono>
#include "rclcpp/rclcpp.hpp"
using namespace std::chrono_literals;
class MyTimer : public rclcpp::Node {
rclcpp::TimerBase::SharedPtr mTimer;
public:
MyTimer() : Node("MyTimer"){
auto timer_cb = [this]() -> void {
RCLCPP_INFO(this->get_logger(), "Hello !!!!"); };
this->mTimer = create_wall_timer(100ms, timer_cb);
}
};
int main(int argc, char * argv[]){
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<MyTimer>());
rclcpp::shutdown();
return 0;
}
4. 编写 CMake 脚本
# 1. 打开 CMakeLists.txt
vi test/CMakeLists.txt
# 2. 增加节点编译脚本
add_executable(r2_test src/test.cpp)
ament_target_dependencies(r2_test rclcpp std_msgs)
# 3. 增加安装脚本
install(TARGETS r2_test DESTINATION lib/test)
5. 编译 ROS2 程序
1. 进入根目录
cd ./project
2. 编译程序
colcon build --packages-select test # 编译指定节点
colcon build # 编译全部节点
6. 运行 ROS2 程序
1. 进入目录
cd ./project
2. 加载环境
source ./install/setup.bash
3. 运行程序
ros2 run test r2_test
7. 查看 ROS2 消息
ros2 topic list # 查看话题列表
ros2 topic info <topic_name> # 查看话题信息
ros2 topic hz <topic_name> # 查看话题发布频率
ros2 topic bw <topic_name> # 查看话题传输带宽
ros2 topic echo <topic_name> # 查看话题数据
ros2 topic pub <topic_name> <msg_type> <msg_data> # 发布话题消息