ROS2 基础与设置
第九章 ROS2-Humble
| 名称 | 所有者 | 修改时间 | 创建时间 |
|---|---|---|---|
| 01 ROS2 简介 | Yujiang | 2026-01-09 14:03 | 2026-01-09 14:03 |
| 02 安装 Humble | Yujiang | 2026-01-26 12:12 | 2026-01-09 14:03 |
| 03 集成开发环境 | Yujiang | 2026-01-26 14:55 | 2026-01-09 14:24 |
| 04 工作空间 | Yujiang | 2026-01-12 12:22 | 2026-01-09 14:25 |
| 05 包 | Yujiang | 2026-01-12 12:22 | 2026-01-09 14:26 |
| 06 节点 | Yujiang | 2026-02-13 13:28 | 2026-01-09 14:26 |
| 07 话题通信 | Yujiang | 2026-02-13 13:29 | 2026-01-09 14:27 |
| 08 服务通信 | Yujiang | 2026-02-06 13:57 | 2026-01-09 14:27 |
| 09 动作通信 | Yujiang | 2026-01-27 14:48 | 2026-01-09 14:27 |
| 10 TF2 坐标变换 | Yujiang | 2026-01-27 14:55 | 2026-01-09 14:28 |
| 自定义接口消息 | Yujiang | 2026-02-06 14:45 | 2026-01-09 14:28 |
| 12 参数服务案例 | Yujiang | 2026-02-06 15:05 | 2026-01-09 14:28 |
| 13 元功能包 | Yujiang | 2026-02-06 15:16 | 2026-01-09 14:29 |
| 14 分布式通信 | Yujiang | 2026-02-06 15:25 | 2026-01-09 14:29 |
| 15 DDS | Yujiang | 2026-02-06 16:00 | 2026-01-09 14:29 |
| 时间相关 API | Yujiang | 2026-02-06 16:20 | 2026-01-09 14:29 |
| 17 常用命令工具 | Yujiang | 2026-02-06 16:41 | 2026-01-09 14:30 |
| 18 RViz2 使用 | Yujiang | 2026-02-09 09:53 | 2026-01-09 14:30 |
| 19 Rqt 工具箱 | Yujiang | 2026-02-09 13:43 | 2026-01-09 14:38 |
| 20 Launch 配置 | Yujiang | 2026-02-09 17:12 | 2026-01-09 14:41 |
| 21 录制与回放 | Yujiang | 2026-02-09 17:32 | 2026-01-09 14:41 |
| 22 URDF 模型 | Yujiang | 2026-02-10 10:39 | 2026-01-09 14:41 |
| 23 Gazebo 仿真 | Yujiang | 2026-02-10 11:01 | 2026-01-09 14:42 |
| 24 摄像头预览 | Yujiang | 2026-02-10 11:16 | 2026-01-09 14:42 |
| 25 摄像头标定 | Yujiang | 2026-02-10 11:21 | 2026-01-09 14:42 |
| 26 AR 视觉 | Yujiang | 2026-02-10 11:32 | 2026-01-09 14:43 |
内容维护中...
01 ROS2 简介
01 ROS2 简介
1.1 什么是 ROS 2
ROS 2(Robot Operation System 2)是用于开发机器人软件的开源中间件框架。尽管名称中包含"操作系统",ROS 2 实际上不是一个传统的操作系统,而是一个软件仓库和工具集,帮助开发者创建机器人应用程序。
1.1.1 ROS 2 的定义
ROS 2 提供了操作系统的服务,通常在进程之间传递消息并执行包管理。它是一个分布式框架,使应用程序能够控制机器人硬件、处理传感器数据、执行算法,并与其他应用程序或系统通信。
1.1.2 ROS 2 的设计目标
ROS 2 的设计基于现代机器人应用程序的需求,具有以下主要目标:
| 目标 | 重要性 |
|---|---|
| 实时友好 | 更好地支持低延迟机器人工作负载 |
| 分布式部署 | 多个节点可以在多个进程或机器上运行 |
| 可靠性和可维护性 | 比 ROS 1 时代假设更适合生产机器人 |
| 安全性 | 支持安全通信和访问控制 |
| 跨平台支持 | 在 Linux、嵌入式目标和其他现代环境中运行 |
1.1.3 ROS 2 核心价值
-
模块化设计:代码组织成独立的包,易于维护、重用和分发
-
分布式通信:多处理器、多机器分布式计算架构
-
丰富生态系统:包含大量开源功能包和开发工具
-
活跃社区:全球开发者持续贡献和商业公司的积极支持
1.2 ROS 2 核心概念
1.2.1 节点(Nodes)
节点是 ROS 2 中最基本的计算单元。一个节点是使用 ROS 2 API 与其他节点通信的进程。
节点设计原则:
-
单一职责:每个节点专注于特定功能
-
低耦合:通过接口在节点之间通信,以减少直接依赖
-
可移植:多个节点可以组合复杂功能
1.2.2 话题(Topics)
话题是节点间异步通信的机制,使用发布/订阅(Pub/Sub)。
话题通信特性:
| 特性 | 描述 |
|---|---|
| 异步 | 发布者和订阅者不互相阻塞 |
| 一对多 | 多个订阅者可以消费相同的话题 |
| 松散耦合 | 节点只需在话题名称和消息类型上达成一致 |
| 流友好 | 非常适合传感器数据、遥测和持续控制 |
典型话题示例:
| 话题名称 | 消息类型 | 用途 |
|---|---|---|
| /cmd_vel | geometry_msgs/msg/Twist | 速度控制命令 |
| /odom | nav_msgs/msg/Odometry | 里程数据 |
| /scan | sensor_msgs/msg/LaserScan | 激光雷达数据 |
| /camera/image_raw | sensor_msgs/msg/Image | 原始图像数据 |
1.2.3 服务(Services)
服务是节点间同步通信的机制,使用客户端/服务器(Client/Server)模型。
服务通信特性:
| 特性 | 描述 |
|---|---|
| 请求/响应 | 客户端发送请求并等待响应 |
| 同步模式 | 在需要明确完成结果时有用 |
| 一对一交互 | 通常一个客户端与一个服务端点交互 |
| 适合短任务 | 不适合长期运行的作业或持续反馈 |
1.2.4 动作(Actions)
动作是用于处理长期任务的通信机制,以支持任务的反馈和取消。
三个动作通信流:
| 流 | 用途 |
|---|---|
| Goal | 描述要执行的任务 |
| Feedback | 任务运行时报告进度 |
| Result | 任务完成时返回最终结果 |
1.2.5 参数(Parameters)
参数是节点的配置值,可以在节点启动时设置或在运行时动态修改。
Plain Text
Node: camera_node
├── Parameter: frame_id = "camera_link"
├── Parameter: width = 640
├── Parameter: height = 480
├── Parameter: fps = 30
└── Parameter: exposure_mode = "auto"
Dynamic update example:
$ ros2 param set camera_node exposure_mode "manual"参数类型:
| 类型 | 注释 | 示例值 |
|---|---|---|
| Bool | 布尔值 | true, false |
| Int | 整数 | 42, 10 |
| Float / double | 浮点数 | 3.14, -0.001 |
| string | 字符串 | "Hello world" |
| Byte array | 字节 | [0x01, 0x02, 0x03] |
| Bool array | 布尔数组 | [True, false, true] |
| Int array | 整数数组 | [1, 2, 3, 4, 5] |
| Float array | 浮点数组 | [1.0, 2.0, 3.0] |
| string array | 字符串数组 | ["a", "b", "c"] |
1.3 ROS 2 结构
1.3.1 层级结构
ROS 2 设计了从底层操作系统到上层的清晰层级结构。
1.3.2 客户端库(Client Libraries)
ROS 2 提供了多语言客户端库,开发者可以选择熟悉的语言来编写节点:
| 库 | 语言 | 典型用途 |
|---|---|---|
rclcpp | C++ | 高性能生产节点 |
rclpy | Python | 快速原型设计和脚本 |
rclc | C | Micro-ROS 和资源受限系统 |
rcljava | Java | 基于 JVM 的 ROS 2 集成 |
rclnodejs | JavaScript / Node.js | Web 和工具集成 |
rclcpp 与 rclpy 对比:
// C++ publisher example (rclcpp)
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
class Publisher : public rclcpp::Node {
public:
Publisher() : Node("publisher") {
publisher_ = this->create_publisher<std_msgs::msg::String>("topic", 10);
timer_ = this->create_wall_timer(
std::chrono::milliseconds(500),
[this]() { this->timer_callback(); });
}
private:
void timer_callback() {
auto msg = std_msgs::msg::String();
msg.data = "Hello ROS 2";
publisher_->publish(msg);
}
rclcpp::TimerBase::SharedPtr timer_;
rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_;
};# Python publisher example (rclpy)
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
class Publisher(Node):
def __init__(self):
super().__init__('publisher')
self.publisher_ = self.create_publisher(String, 'topic', 10)
self.timer = self.create_timer(0.5, self.timer_callback)
def timer_callback(self):
msg = String()
msg.data = 'Hello ROS 2'
self.publisher_.publish(msg)1.3.3 RMW 和 DDS
RMW(ROS Middleware Interface)是 ROS 2 中间件的抽象接口层,允许 ROS 2 使用不同的 DDS 来实现:
DDS 实现比较:
| RMW 实现 | DDS 后端 | 开源/商业 | 特性 |
|---|---|---|---|
| rmw_cyclonedds_cpp | CycloneDDS | 开源 | 默认选择,轻量高效 |
| rmw_fastrtps_cpp | FastDDS | 开源 | 功能全面,性能高 |
| rmw_connext_cpp | RTI Connext | 商业 | 工业级支持,最全面 |
DDS 提供的核心功能:
发现机制(Discovery):节点自动发现网络上的其他 ROS 2 节点
-
零拷贝传输(Zero-copy):高效的数据传输,减少内存复制
-
QoS 策略(Quality of Service):控制通信的可靠性、延迟、持久性等
-
类型系统:强类型消息的定义和序列化
1.4 ROS 1 和 ROS 2 之间的主要差异
1.4.2 详细对比表
| 比较维度 | ROS 1 | ROS 2 |
|---|---|---|
| 通信中间件 | TCP/UDP 自定义协议 | DDS 标准协议 |
| 发现机制 | ROS Master(中心化) | DDS 发现(去中心化) |
| 构建系统 | Catkin | Colcon / Ament |
| Python 版本 | Python 2/3 | 仅 Python 3 |
| 支持的操作系统 | 主要 Linux | Linux / Windows / macOS / RTOS |
| 实时支持 | 无实时保证 | 支持硬实时 |
| 多机器人通信 | 需要额外配置 | 原生支持(ROS_DOMAIN_ID) |
| 安全性 | 无加密或身份验证 | 支持加密、身份验证、访问控制 |
| 发行版 | Noetic(最终版本) | Humble、Iron、Jazzy... |
1.4.3 关键改进的详细信息
- 去中心化
-
ROS 1 问题:依赖于 ROS Master,Master 失败导致整个系统崩溃
-
ROS 2 改进:发现机制,节点之间直接通信,无单点故障
- 实时性能
-
ROS 1 问题:非实时,无法满足工业机器人需求
-
ROS 2 改进:支持优先级运动、确定性通信,适合硬实时系统
- 多机器人协同工作
-
ROS 1 问题:同一网络上的多个机器人会相互干扰
-
ROS 2 改进:通过 ROS_DOMAIN_ID 分离不同机器人的电信域
跨平台支持
-
ROS 1:主要支持 Linux
-
ROS 2:原生支持 Windows、macOS、Linux,可移植到 RTOS
1.5 ROS 2 发行版
1.5.1 版本历史
ROS 2 发布按字母数字版本,每个版本都有一个代号:
| 版本代号 | 发布时间 | 支持系统 | 支持状态 | 截止时间 |
|---|---|---|---|---|
| Ardent | 2017.12 | Ubuntu 16.04 | 已终止 | 2019.04 |
| Bouncy | 2018.06 | Ubuntu 16.04/18.04 | 已终止 | 2019.09 |
| Crystal | 2018.12 | Ubuntu 16.04/18.04 | 已终止 | 2020.12 |
| Dashing | 2019.05 | Ubuntu 16.04/18.04 | 已终止 | 2021.05 |
| Eloquent | 2019.11 | Ubuntu 18.04 | 已终止 | 2021.11 |
| Foxy | 2020.06 | Ubuntu 18.04/20.04 | 已终止 | 2023.05 |
| Galactic | 2021.05 | Ubuntu 20.04 | 已终止 | 2022.11 |
| Humble | 2022.05 | Ubuntu 22.04 | LTS | 2027.05 |
| Iron | 2023.05 | Ubuntu 22.04 | 已终止 | 2024.11 |
| Jazzy | 2024.05 | Ubuntu 24.04 | LTS | 2029.05 |
1.5.3 版本选择建议
| 使用场景 | 推荐版本 | 原因 |
|---|---|---|
| 生产环境 | Humble | 稳定,长期支持 |
| 新项目开发 | Jazzy | 最新 LTS,长期支持 |
| 学习/实验 | Recent Scroll | 最新功能 |
| 旧系统维护 | Humble | 兼容性好。 |
1.6 ROS 2 应用领域
包括工业机器人(机械臂控制、移动机器人 AGV/AMR、协作机器人、质量测试)、服务机器人(送餐、清洁、向导、陪伴机器人)、自动驾驶(感知、定位、规划、控制)、无人机(飞行控制、视觉避障、任务执行、电报处理)、教育与科研(SLAM、Path Planning、强化学习)。
1.7 学习路径建议
1.7.1 基础知识准备
| 知识领域 | 具体内容 | 重要性 |
|---|---|---|
| Linux 操作 | 文件系统、终端命令、权限管理 | 必需 |
| 编程语言 | Python 或 C++ | 必需 |
| 版本控制 | Git 基本操作 | 推荐 |
| 网络基础 | TCP/UDP、端口、IP 地址 | 推荐 |
| 数学基础 | 线性代数、概率统计 | 高级 |
1.7.3 推荐的学习资源
官方资源:
| 资源名称 | URL | 描述 |
|---|---|---|
| ROS 2 官方文档 | https://docs.ros.org/en/humble/ | 完整权威文档 |
| ROS 2 学院 | https://docs.ros.org/en/humble/Tutorials.html | 官方课程集 |
| ROS 2 设计文档 | https://design.ros2.org/ | 架构设计说明 |
| ROS 2 源代码 | https://github.com/ros2 | GitHub 仓库 |
03 集成开发环境
03 集成开发环境(IDE Setup)
3.1 概述
良好的开发环境配置可以显著提高 ROS 2 开发效率。本章将提供有关如何配置 Visual Studio Code(VS Code)作为 ROS 2 主要开发环境的详细信息,包括插件安装、智能代码补全、调试配置等。
3.1.1 开发环境选项
| IDE | 优点 | 缺点 | 推荐 |
|---|---|---|---|
| VS Code | 轻量,丰富的插件,免费 | C++ 支持需要额外配置 | 推荐 |
| CLion | 强大的 C++ 支持,内置调试 | 付费,重量级 | 推荐 |
| Qt Creator | 跨平台,CMake 支持 | ROS 2 支持需要手动配置 | 一般 |
| Vim/Neovim | 轻量,高度可自定义 | 学习曲线陡峭 | 一般 |
3.1.2 推荐配置
本文档推荐使用 VS Code + ROS 扩展的组合:
跨平台支持(Linux/Windows/macOS)
丰富的插件生态系统
完美的 ROS 2 支持
免费
3.2 Visual Studio Code 安装
3.2.1 VS Code 的安装
Ubuntu 22.04 通过 APT 安装:
# Download and install VS Code
wget -qO- https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > packages.microsoft.gpg
sudo install -o root -g root -m 644 packages.microsoft.gpg /etc/apt/trusted.gpg.d/
sudo sh -c 'echo "deb [arch=amd64,arm64,armhf signed-by=/etc/apt/trusted.gpg.d/packages.microsoft.gpg] https://packages.microsoft.com/repos/code stable main" > /etc/apt/sources.list.d/vscode.list'
sudo apt update
sudo apt install -y code通过 Snap 安装:
sudo snap install --classic code验证安装:
code --version3.2.2 VS Code 基本配置
启动 VS Code:
code
# Or open a specific directory
code ~/ros2_ws3.3 必需插件
3.3.1 ROS 2 核心插件
| 插件名称 | 发布者 | 用途 |
|---|---|---|
| ROS | Microsoft | ROS 支持 |
| C/C++ | Microsoft | C++ 语言支持 |
| Python | Microsoft | Python 语言支持 |
| CMake Tools | Microsoft | CMake 支持 |
3.3.3 安装插件的方法
# Install the ROS extension
code --install-extension ms-iot.vscode-ros
# Install the C/C++ extension
code --install-extension ms-vscode.cpptools
# Install the Python extension
code --install-extension ms-python.python
# Install CMake Tools
code --install-extension ms-vscode.cmake-tools3.4 ROS 2 工作空间配置
3.4.1 打开 ROS 2 工作空间
# Open the workspace
code ~/ros2_ws3.4.2 配置 C/C++ 智能提示
VS Code 需要知道 ROS 2 的头文件路径以提供准确的代码补全。
创建 .vscode/c_cpp_properties.json:
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**",
"/opt/ros/humble/include/**",
"/usr/include/**"
],
"defines": [],
"compilerPath": "/usr/bin/gcc",
"cStandard": "c17",
"cppStandard": "c++17",
"intelliSenseMode": "linux-gcc-x64",
"compileCommands": "${workspaceFolder}/build/compile_commands.json"
}
],
"version": 4
}4.4.3 生成 compile_commands.json
# From the workspace root directory
cd ~/ros2_ws
# Generate compile_commands.json during the build
colcon build --cmake-args -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
# Create a symbolic link to the src directory (optional, useful for some tools)
ln -s build/compile_commands.json3.4.4 配置 Python 环境
创建 .vscode/settings.json:
{
"python.autoComplete.extraPaths": [
"${workspaceFolder}/install/*/lib/python3.10/site-packages",
"/opt/ros/humble/lib/python3.10/site-packages"
],
"python.analysis.extraPaths": [
"${workspaceFolder}/install/*/lib/python3.10/site-packages",
"/opt/ros/humble/lib/python3.10/site-packages"
],
"python.formatting.provider": "black",
"python.linting.enabled": true,
"python.linting.pylintEnabled": true,
"python.linting.pylintArgs": [
"--rcfile=${workspaceFolder}/.pylintrc"
]
}3.5 VS Code 任务配置
3.5.1 配置构建任务
创建 .vscode/tasks.json:
{
"version": "2.0.0",
"tasks": [
{
"label": "colcon build",
"type": "shell",
"command": "colcon build --symlink-install",
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": [],
"presentation": {
"reveal": "always",
"panel": "new"
}
},
{
"label": "colcon build (selected package)",
"type": "shell",
"command": "colcon build --symlink-install --packages-select ${input:packageName}",
"group": "build",
"problemMatcher": []
},
{
"label": "source workspace",
"type": "shell",
"command": "source install/setup.bash && echo 'Workspace sourced'",
"problemMatcher": []
},
{
"label": "clean build",
"type": "shell",
"command": "rm -rf build install log && colcon build --symlink-install",
"group": "build",
"problemMatcher": []
}
],
"inputs": [
{
"id": "packageName",
"type": "promptString",
"description": "Enter package name to build"
}
]
}3.6 调试配置
3.6.1 C++ 调试节点
创建 .vscode/launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "ROS2: C++ Node",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/install/${input:packageName}/lib/${input:packageName}/${input:executableName}",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [
{
"name": "ROS_DOMAIN_ID",
"value": "0"
},
{
"name": "RMW_IMPLEMENTATION",
"value": "rmw_cyclonedds_cpp"
}
],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
],
"inputs": [
{
"id": "packageName",
"type": "promptString",
"description": "Package name"
},
{
"id": "executableName",
"type": "promptString",
"description": "Executable name"
}
]
}3.6.2 Python 调试
{
"name": "ROS2: Python Node",
"type": "python",
"request": "launch",
"module": "rclpy.executors",
"args": [
"${workspaceFolder}/install/${input:packageName}/lib/${input:packageName}/${input:moduleName}"
],
"console": "integratedTerminal",
"env": {
"ROS_DOMAIN_ID": "0",
"PYTHONPATH": "${workspaceFolder}/install/${input:packageName}/lib/python3.10/site-packages:${env:PYTHONPATH}"
}
}3.6.3 调试
调试快捷键:
| 快捷键 | 功能 |
|---|---|
| F5 | 开始调试 |
| Ctrl+Shift+F5 | 重启调试 |
| Shift+F5 | 停止调试 |
| F9 | 设置/关闭断点 |
| F10 | 单步跳过 |
| F11 | 单步进入 |
| Shift+F11 | 单步退出 |
3.7 ROS 2 特殊功能配置
3.7.1 ROS 扩展
创建 .vscode/settings.json(ROS 相关):
{
"ros.distro": "humble",
"ros.pythonPath": "/usr/bin/python3",
"ros.defaultWorkspace": "${workspaceFolder}",
"ros.rosSetupScript": "/opt/ros/humble/setup.bash",
"ros.rosWorkspace": "${workspaceFolder}",
"files.associations": {
"*.world": "xml",
"*.urdf": "xml",
"*.xacro": "xml",
"*.rviz": "yaml",
"*.launch.py": "python"
}
}3.11 Terminator 安装
sudo apt install terminator3.11.1 启动
快捷键 Ctrl+Alt+T
3.11.2 Terminator 常用快捷键
Operations within the same tab:
Alt+Up // Move to the terminal above
Alt+Down // Move to the terminal below
Alt+Left // Move to the terminal on the left
Alt+Right // Move to the terminal on the right
Ctrl+Shift+O // Split the terminal horizontally
Ctrl+Shift+E // Split the terminal vertically
Ctrl+Shift+W // Close the current terminal
Ctrl+Shift+Q // Quit the current window
Ctrl+Shift+T // Open a new tab3.12 Git 的使用
3.12.1 安装
在日常工作中,git 是不可绕过的技能,因为它涉及团队工作和版本管理。Git 是一个免费开源的分布式版本控制系统,在 Ubuntu 下安装 git:
sudo apt install git3.12.2 Git 基本操作
简单的操作步骤:
git init
git add .
git commit| 命令 | 用途 |
|---|---|
git init | 创建新的本地仓库 |
git status | 检查当前仓库状态 |
git add <file> | 暂存文件以进行下一次提交 |
git add . | 暂存所有当前更改 |
git commit -m "message" | 创建带有消息的新快照 |
git diff | 显示未暂存的更改 |
git log | 显示提交历史 |
git remote -v | 列出已配置的远程 |
git push -u origin main | 推送并设置上游分支 |
git pull | 获取并合并远程更新 |
3.13 后续步骤
完成开发配置后,您可以:
04 工作空间 - 学习工作空间管理
05 功能包 - 创建功能包
06 节点 - 编写节点代码
04 工作空间
04 工作空间(Workspace)
4.1 工作空间概述
4.1.1 什么是工作空间?
工作空间是 ROS 2 中组织和管理功能包的目录结构。它是包含源代码、编译产品和安装文档的根目录,是 ROS 2 开发的基本环境。
4.1.2 工作空间目录结构
标准 ROS 2 工作空间包含以下目录:
| 目录 | 用途 | 是否版本控制 |
|---|---|---|
| src/ | 存储功能包源代码 | 是 |
| build/ | 编译中间产物 | 否 |
| install/ | 最终安装文件 | 否 |
| log/ | 编译和测试日志 | 否 |
4.1.3 工作空间的类型
| 类型 | 示例路径 | 用途 |
|---|---|---|
| 系统工作空间 | /opt/ros/humble/ | 已安装的 ROS 2 软件 |
| 用户工作空间 | ~/ros2_ws/ | 个人开发工作空间 |
| 覆盖工作空间 | ~/overlay_ws/ | 扩展或覆盖现有包 |
4.2 创建工作空间
4.2.1 创建基本工作空间
# Createworkspacedirectory
mkdir -p ~/ros2_ws/src
cd ~/ros2_ws
# Viewdirectory structure
tree -L 24.3 Colcon 编译系统
4.3.1 Colcon 简介
Colcon(Command Line Compiler for CONstituents)是 ROS 2 的推荐构建工具,取代了 ROS 1 的 Catkin。
4.3.2 Colcon 的安装
# Install `colcon` and common extensions
sudo apt install -y python3-colcon-common-extensions
# VerifyInstall
colcon --help4.3.3 Colcon 基本用法
cd ~/ros2_ws
colcon build
colcon build --packages-select <package_name>
colcon build --packages-select <pkg1> <pkg2> <pkg3>
colcon build --packages-skip <package_name>4.3.4 常用编译选项
# Development and debugging configuration (recommended)
colcon build --symlink-install --cmake-args -DCMAKE_BUILD_TYPE=Debug
# Release configuration
colcon build --cmake-args -DCMAKE_BUILD_TYPE=Release
# Generate the compile command database (for VS Code)
colcon build --symlink-install --cmake-args -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
# Detailed output (for debugging build issues)
colcon build --event-handlers console_direct+4.4 工作空间覆盖(Overlaying)
设置环境变量顺序很重要:
# Correct source order (from bottom to top)
source /opt/ros/humble/setup.bash
source ~/ros2_ws/install/setup.bash
source ~/overlay_ws/install/setup.bash4.5 详细环境设置
4.5.1 setup.bash 脚本
编译完成后,新编译的包必须通过 source 设置环境:
# Source the workspace environment
source install/setup.bash
# Verify the environment variables
echo $ROS_DOMAIN_ID
echo $AMENT_PREFIX_PATH
echo $LD_LIBRARY_PATH4.5.3 永久环境设置
方法 1:修改 ~/.bashrc
echo "source ~/ros2_ws/install/setup.bash" >> ~/.bashrc
source ~/.bashrc4.6 包管理
4.6.1 列出工作空间中的包
# List all available packages
ros2 pkg list
# List the path of a specific package
ros2 pkg prefix <package_name>
# List packages in the workspace `src` directory
find src -maxdepth 2 -name package.xml -exec dirname {} \;4.6.2 查看包信息
# View package metadata
ros2 pkg xml <package_name>
# View package dependencies
ros2 pkg dependencies <package_name>
# Export the package list
ros2 pkg list > packages_list.txt4.7 增量编译
4.7.1 理解增量编译
# Run a full build for the first time
colcon build
# After modifying the code of a package
# Rebuild only that package and its dependents
colcon build --packages-select <modified_package>4.7.2 强制重新编译
# Clean and rebuild a single package
colcon build --packages-select <package_name> --cmake-force-configure
# Clean and rebuild the entire workspace
rm -rf build install log
colcon build4.8 测试和验证
# Build and run all tests
colcon test
# Run tests for a specific package
colcon test --packages-select <package_name>
# View test results
colcon test-result --all
colcon test-result --verbose4.9 常用工作空间操作
# Clean build artifacts
rm -rf build/ install/ log/
# Or use colcon cleanup features
colcon clean --all
# Clean a specific package
colcon clean --packages-select <package_name>4.12 后续步骤
1.05 包 - 学习创建和管理功能包
2.06 节点 - 准备第一个节点
05 包
05 功能包(Packages)
5.1 功能包摘要
5.1.1 什么是功能包?
包是 ROS 2 中代码组织的基本单元。它包含源代码、配置文件、数据文件、构建脚本和特定功能的文档。功能包可以依赖、使用和与其他包共享。
5.1.2 功能包的命名规则
只允许小写字母、数字和下划线
必须以字母开头
推荐描述性名称
避免使用 ROS 2 保留名称
5.1.3 功能包的类型
| 类型 | 构建系统 | 主要语言 | 用途 |
|---|---|---|---|
| ament_cmake | CMake | C++ | C++ 节点,混合项目 |
| ament_python | Setuptools | Python | 纯 Python 项目 |
| ament_cmake_python | CMake + Python | 混合 | C++ 和 Python 混合项目 |
5.2 创建功能包
5.2.1 创建 C++ 功能包
使用 ros2 pkg create 命令创建 C++ 功能包:
cd ~/ros2_ws/src
# Create a basic C++ package
ros2 pkg create --build-type ament_cmake my_cpp_pkg
# Create a C++ package with dependencies
ros2 pkg create --build-type ament_cmake \
--dependencies rclcpp std_msgs \
my_robot_controller
# Create a complete C++ package structure
ros2 pkg create --build-type ament_cmake \
--dependencies rclcpp std_msgs geometry_msgs \
--node-name my_node \
--library-name my_library \
my_cpp_pkg5.2.2 创建 Python 功能包
cd ~/ros2_ws/src
# Create a basic Python package
ros2 pkg create --build-type ament_python my_py_pkg
# Create a Python package with dependencies
ros2 pkg create --build-type ament_python \
--dependencies rclpy std_msgs \
my_python_package
# Create a Python package that includes nodes
ros2 pkg create --build-type ament_python \
--dependencies rclpy \
--node-name my_node \
my_py_pkg5.3 package.xml 配置
5.3.1 package.xml 基本结构
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<!-- Basic information -->
<name>my_package</name>
<version>1.0.0</version>
<description>My ROS 2 package description</description>
<maintainer email="user@example.com">Your Name</maintainer>
<license>Apache-2.0</license>
<!-- Build tools -->
<buildtool_depend>ament_cmake</buildtool_depend>
<!-- Dependencies -->
<depend>rclcpp</depend>
<depend>std_msgs</depend>
<!-- Test dependencies -->
<test_depend>ament_lint_auto</test_depend>
<test_depend>ament_lint_common</test_depend>
<!-- Export information -->
<export>
<build_type>ament_cmake</build_type>
</export>
</package>5.3.3 常用依赖项
核心依赖:
<!-- C++ support -->
<depend>rclcpp</depend>
<!-- Python support -->
<depend>rclpy</depend>
<!-- Standard messages -->
<depend>std_msgs</depend>
<!-- Geometry messages -->
<depend>geometry_msgs</depend>
<!-- Sensor messages -->
<depend>sensor_msgs</depend>
<!-- Navigation messages -->
<depend>nav_msgs</depend>
<!-- TF2 transforms -->
<depend>tf2</depend>
<depend>tf2_ros</depend>
<depend>tf2_geometry_msgs</depend>5.5 setup.py 配置(Python)
5.5.1 基本结构
from setuptools import setup
package_name = 'my_py_pkg'
setup(
name=package_name,
version='1.0.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
('share/' + package_name + '/launch', ['launch/my_launch.py']),
('share/' + package_name + '/config', ['config/params.yaml']),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='Your Name',
maintainer_email='user@example.com',
description='My ROS 2 Python package',
license='Apache-2.0',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'my_node = my_py_pkg.my_node:main',
],
},
)5.5.3 添加可执行节点
使用 entry_points:
entry_points={
'console_scripts': [
# Node name = module path:function name
'talker = my_py_pkg.talker:main',
'listener = my_py_pkg.listener:main',
'camera_node = my_py_pkg.camera:main',
],
}5.6 包的编译和安装
5.6.1 编译单个包
cd ~/ros2_ws
# Build a specified package
colcon build --packages-select my_cpp_pkg
# Build and show detailed output
colcon build --packages-select my_cpp_pkg --event-handlers console_direct+5.6.3 常用编译选项
# Use symbolic-link install (recommended during development)
colcon build --symlink-install
# Build in Debug mode
colcon build --cmake-args -DCMAKE_BUILD_TYPE=Debug
# Build in Release mode
colcon build --cmake-args -DCMAKE_BUILD_TYPE=Release
# Generate the compile command database
colcon build --cmake-args -DCMAKE_EXPORT_COMPILE_COMMANDS=ON5.7 依赖管理
5.7.1 查看包依赖
# View the package direct dependencies
ros2 pkg dependencies my_package
# View all dependent packages (recursive)
ros2 pkg dependencies my_package --all
# View which packages depend on this package
ros2 pkg dependents my_package
# View package metadata
ros2 pkg xml my_package