ROS2 入门与实践

1.7k 词

从 ROS1 过渡到 ROS2 的关键变化、开发环境搭建和控制器编写。

基础变化

创建功能包

1
2
3
4
5
# ROS1
catkin_create_pkg my_pkg roscpp std_msgs

# ROS2
ros2 pkg create my_pkg --build-type ament_cmake --dependencies rclcpp std_msgs

编译系统

ROS1 ROS2
构建工具 catkin_make / catkin build colcon build
包格式 package.xml (format 2) package.xml (format 3)
CMake find_package(catkin REQUIRED) find_package(ament_cmake REQUIRED)

元包(metapackage)

1
2
3
4
5
# ROS1
<export><metapackage/></export>

# ROS2
<export><build_type>ament_cmake</build_type></export>

开发环境

Docker 开发 ROS2

1
2
3
4
FROM osrf/ros:humble-desktop
RUN apt update && apt install -y \
ros-humble-ros-base \
python3-colcon-common-extensions
1
2
docker build -t ros2-dev .
docker run -it --net=host -v /tmp/.X11-unix:/tmp/.X11-unix ros2-dev

CLion 配置 ROS2

  1. 在 CLion 中打开 ROS2 工作空间
  2. 设置 Build Tool 为 colcon
  3. CMake 参数添加 -DCMAKE_EXPORT_COMPILE_COMMANDS=ON

注意:需要在已 source 过 ROS2 环境的终端中启动 CLion。

编写 ROS2 Controller

与 ROS1 的 ros_control 不同,ROS2 使用 ros2_control:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <controller_interface/controller_interface.hpp>
#include <hardware_interface/types/hardware_interface_type_values.hpp>

class MyController : public controller_interface::ControllerInterface {
public:
controller_interface::return_type init(
const std::string& controller_name) override {
// 初始化
return controller_interface::return_type::OK;
}

controller_interface::return_type update() override {
// 控制循环
return controller_interface::return_type::OK;
}
};

// 注册为插件
#include <pluginlib/class_list_macros.hpp>
PLUGINLIB_EXPORT_CLASS(MyController, controller_interface::ControllerInterface)

继承了 RobotHW 后写我们自己的 rmHW,就是写我们自己的硬件抽象层。

关键命令速查

1
2
3
4
5
6
7
# 在工作空间下编译(如果报 has-built-by-catkin_build 错误,先 clean)
rm -rf build/ devel/
catkin_make # ROS1
colcon build # ROS2

# 检查依赖
rosdep check --from-paths src --ignore-src -r -y