ROS2 基础与设置

第九章 ROS2-Humble

名称所有者修改时间创建时间
01 ROS2 简介Yujiang2026-01-09 14:032026-01-09 14:03
02 安装 HumbleYujiang2026-01-26 12:122026-01-09 14:03
03 集成开发环境Yujiang2026-01-26 14:552026-01-09 14:24
04 工作空间Yujiang2026-01-12 12:222026-01-09 14:25
05 包Yujiang2026-01-12 12:222026-01-09 14:26
06 节点Yujiang2026-02-13 13:282026-01-09 14:26
07 话题通信Yujiang2026-02-13 13:292026-01-09 14:27
08 服务通信Yujiang2026-02-06 13:572026-01-09 14:27
09 动作通信Yujiang2026-01-27 14:482026-01-09 14:27
10 TF2 坐标变换Yujiang2026-01-27 14:552026-01-09 14:28
自定义接口消息Yujiang2026-02-06 14:452026-01-09 14:28
12 参数服务案例Yujiang2026-02-06 15:052026-01-09 14:28
13 元功能包Yujiang2026-02-06 15:162026-01-09 14:29
14 分布式通信Yujiang2026-02-06 15:252026-01-09 14:29
15 DDSYujiang2026-02-06 16:002026-01-09 14:29
时间相关 APIYujiang2026-02-06 16:202026-01-09 14:29
17 常用命令工具Yujiang2026-02-06 16:412026-01-09 14:30
18 RViz2 使用Yujiang2026-02-09 09:532026-01-09 14:30
19 Rqt 工具箱Yujiang2026-02-09 13:432026-01-09 14:38
20 Launch 配置Yujiang2026-02-09 17:122026-01-09 14:41
21 录制与回放Yujiang2026-02-09 17:322026-01-09 14:41
22 URDF 模型Yujiang2026-02-10 10:392026-01-09 14:41
23 Gazebo 仿真Yujiang2026-02-10 11:012026-01-09 14:42
24 摄像头预览Yujiang2026-02-10 11:162026-01-09 14:42
25 摄像头标定Yujiang2026-02-10 11:212026-01-09 14:42
26 AR 视觉Yujiang2026-02-10 11:322026-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. 分布式通信:多处理器、多机器分布式计算架构

  3. 丰富生态系统:包含大量开源功能包和开发工具

  4. 活跃社区:全球开发者持续贡献和商业公司的积极支持

1.2 ROS 2 核心概念

1.2.1 节点(Nodes)

节点是 ROS 2 中最基本的计算单元。一个节点是使用 ROS 2 API 与其他节点通信的进程。

节点设计原则:

  • 单一职责:每个节点专注于特定功能

  • 低耦合:通过接口在节点之间通信,以减少直接依赖

  • 可移植:多个节点可以组合复杂功能

1.2.2 话题(Topics)

话题是节点间异步通信的机制,使用发布/订阅(Pub/Sub)。

话题通信特性:

特性描述
异步发布者和订阅者不互相阻塞
一对多多个订阅者可以消费相同的话题
松散耦合节点只需在话题名称和消息类型上达成一致
流友好非常适合传感器数据、遥测和持续控制

典型话题示例:

话题名称消息类型用途
/cmd_velgeometry_msgs/msg/Twist速度控制命令
/odomnav_msgs/msg/Odometry里程数据
/scansensor_msgs/msg/LaserScan激光雷达数据
/camera/image_rawsensor_msgs/msg/Image原始图像数据

1.2.3 服务(Services)

服务是节点间同步通信的机制,使用客户端/服务器(Client/Server)模型。

服务通信特性:

特性描述
请求/响应客户端发送请求并等待响应
同步模式在需要明确完成结果时有用
一对一交互通常一个客户端与一个服务端点交互
适合短任务不适合长期运行的作业或持续反馈

1.2.4 动作(Actions)

动作是用于处理长期任务的通信机制,以支持任务的反馈和取消。

三个动作通信流:

用途
Goal描述要执行的任务
Feedback任务运行时报告进度
Result任务完成时返回最终结果

1.2.5 参数(Parameters)

参数是节点的配置值,可以在节点启动时设置或在运行时动态修改。

Code
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 提供了多语言客户端库,开发者可以选择熟悉的语言来编写节点:

语言典型用途
rclcppC++高性能生产节点
rclpyPython快速原型设计和脚本
rclcCMicro-ROS 和资源受限系统
rcljavaJava基于 JVM 的 ROS 2 集成
rclnodejsJavaScript / Node.jsWeb 和工具集成

rclcpp 与 rclpy 对比:

cpp
// 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
# 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_cppCycloneDDS开源默认选择,轻量高效
rmw_fastrtps_cppFastDDS开源功能全面,性能高
rmw_connext_cppRTI Connext商业工业级支持,最全面

DDS 提供的核心功能:

发现机制(Discovery):节点自动发现网络上的其他 ROS 2 节点

  1. 零拷贝传输(Zero-copy):高效的数据传输,减少内存复制

  2. QoS 策略(Quality of Service):控制通信的可靠性、延迟、持久性等

  3. 类型系统:强类型消息的定义和序列化

1.4 ROS 1 和 ROS 2 之间的主要差异

1.4.2 详细对比表

比较维度ROS 1ROS 2
通信中间件TCP/UDP 自定义协议DDS 标准协议
发现机制ROS Master(中心化)DDS 发现(去中心化)
构建系统CatkinColcon / Ament
Python 版本Python 2/3仅 Python 3
支持的操作系统主要 LinuxLinux / Windows / macOS / RTOS
实时支持无实时保证支持硬实时
多机器人通信需要额外配置原生支持(ROS_DOMAIN_ID)
安全性无加密或身份验证支持加密、身份验证、访问控制
发行版Noetic(最终版本)Humble、Iron、Jazzy...

1.4.3 关键改进的详细信息

  1. 去中心化
  • ROS 1 问题:依赖于 ROS Master,Master 失败导致整个系统崩溃

  • ROS 2 改进:发现机制,节点之间直接通信,无单点故障

  1. 实时性能
  • ROS 1 问题:非实时,无法满足工业机器人需求

  • ROS 2 改进:支持优先级运动、确定性通信,适合硬实时系统

  1. 多机器人协同工作
  • 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 发布按字母数字版本,每个版本都有一个代号:

版本代号发布时间支持系统支持状态截止时间
Ardent2017.12Ubuntu 16.04已终止2019.04
Bouncy2018.06Ubuntu 16.04/18.04已终止2019.09
Crystal2018.12Ubuntu 16.04/18.04已终止2020.12
Dashing2019.05Ubuntu 16.04/18.04已终止2021.05
Eloquent2019.11Ubuntu 18.04已终止2021.11
Foxy2020.06Ubuntu 18.04/20.04已终止2023.05
Galactic2021.05Ubuntu 20.04已终止2022.11
Humble2022.05Ubuntu 22.04LTS2027.05
Iron2023.05Ubuntu 22.04已终止2024.11
Jazzy2024.05Ubuntu 24.04LTS2029.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/ros2GitHub 仓库

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 安装:

bash
# 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 安装:

bash
sudo snap install --classic code

验证安装:

bash
code --version

3.2.2 VS Code 基本配置

启动 VS Code:

bash
code
# Or open a specific directory
code ~/ros2_ws

3.3 必需插件

3.3.1 ROS 2 核心插件

插件名称发布者用途
ROSMicrosoftROS 支持
C/C++MicrosoftC++ 语言支持
PythonMicrosoftPython 语言支持
CMake ToolsMicrosoftCMake 支持

3.3.3 安装插件的方法

bash
# 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-tools

3.4 ROS 2 工作空间配置

3.4.1 打开 ROS 2 工作空间

bash
# Open the workspace
code ~/ros2_ws

3.4.2 配置 C/C++ 智能提示

VS Code 需要知道 ROS 2 的头文件路径以提供准确的代码补全。

创建 .vscode/c_cpp_properties.json:

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

bash
# 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.json

3.4.4 配置 Python 环境

创建 .vscode/settings.json:

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:

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:

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 调试

json
{
  "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 相关):

json
{
  "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 安装

bash
sudo apt install terminator

3.11.1 启动

快捷键 Ctrl+Alt+T

3.11.2 Terminator 常用快捷键

bash
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 tab

3.12 Git 的使用

3.12.1 安装

在日常工作中,git 是不可绕过的技能,因为它涉及团队工作和版本管理。Git 是一个免费开源的分布式版本控制系统,在 Ubuntu 下安装 git:

bash
sudo apt install git

3.12.2 Git 基本操作

简单的操作步骤:

bash
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 创建基本工作空间

bash
# Createworkspacedirectory
mkdir -p ~/ros2_ws/src
cd ~/ros2_ws

# Viewdirectory structure
tree -L 2

4.3 Colcon 编译系统

4.3.1 Colcon 简介

Colcon(Command Line Compiler for CONstituents)是 ROS 2 的推荐构建工具,取代了 ROS 1 的 Catkin。

4.3.2 Colcon 的安装

bash
# Install `colcon` and common extensions
sudo apt install -y python3-colcon-common-extensions

# VerifyInstall
colcon --help

4.3.3 Colcon 基本用法

bash
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 常用编译选项

bash
# 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)

设置环境变量顺序很重要:

bash
# Correct source order (from bottom to top)
source /opt/ros/humble/setup.bash
source ~/ros2_ws/install/setup.bash
source ~/overlay_ws/install/setup.bash

4.5 详细环境设置

4.5.1 setup.bash 脚本

编译完成后,新编译的包必须通过 source 设置环境:

bash
# Source the workspace environment
source install/setup.bash

# Verify the environment variables
echo $ROS_DOMAIN_ID
echo $AMENT_PREFIX_PATH
echo $LD_LIBRARY_PATH

4.5.3 永久环境设置

方法 1:修改 ~/.bashrc

bash
echo "source ~/ros2_ws/install/setup.bash" >> ~/.bashrc
source ~/.bashrc

4.6 包管理

4.6.1 列出工作空间中的包

bash
# 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 查看包信息

bash
# 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.txt

4.7 增量编译

4.7.1 理解增量编译

bash
# 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 强制重新编译

bash
# 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 build

4.8 测试和验证

bash
# 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 --verbose

4.9 常用工作空间操作

bash
# 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_cmakeCMakeC++C++ 节点,混合项目
ament_pythonSetuptoolsPython纯 Python 项目
ament_cmake_pythonCMake + Python混合C++ 和 Python 混合项目

5.2 创建功能包

5.2.1 创建 C++ 功能包

使用 ros2 pkg create 命令创建 C++ 功能包:

bash
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_pkg

5.2.2 创建 Python 功能包

bash
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_pkg

5.3 package.xml 配置

5.3.1 package.xml 基本结构

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 常用依赖项

核心依赖:

xml
<!-- 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 基本结构

python
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:

python
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 编译单个包

bash
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 常用编译选项

bash
# 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=ON

5.7 依赖管理

5.7.1 查看包依赖

bash
# 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