交互式机器人编程:使用Jupyter Notebook运行ROS2程序

文章目录

  • [1. ROS2运行环境](#1. ROS2运行环境)
  • [2. Jupyter运行环境](#2. Jupyter运行环境)
  • [3. 运行测试](#3. 运行测试)
    • [3.1 发布话题](#3.1 发布话题)
    • [3.2 运行多节点](#3.2 运行多节点)
  • 报错

jupyter这种可见即可得的运行方式,非常方便代码调试。它允许我们逐段、即时地执行代码并查看结果,非常适合在开发过程中实时测试和验证代码逻辑。因此,想在jupyter中运行ros2的代码,从而方便调试机器人控制指令。下面记录运行环境的搭建过程,其他可参考:https://docs.isaacsim.omniverse.nvidia.com/latest/ros2_tutorials/tutorial_ros2_manipulation.html,https://github.com/isaac-sim/IsaacSim-ros_workspaces

1. ROS2运行环境

为了能在jupyter中使用ros2,需要在相同的虚拟环境中安装ros2,这里使用鱼香ros的一键安装指令:

shell 复制代码
wget http://fishros.com/install -O fishros && . fishros

如果这种方式,可参考官网的安装方法https://docs.ros.org/en/humble/Installation/Ubuntu-Install-Debs.html

2. Jupyter运行环境

创建Python虚拟环境,用于与Ubuntu的Python环境隔离,避免Ubuntu系统逐渐臃肿。通过以下指令创建虚拟环境:

shell 复制代码
wget https://repo.anaconda.com/archive/Anaconda3-2025.06-0-Linux-x86_64.sh

chmod +x Anaconda3-2025.06-0-Linux-x86_64.sh
bash Anaconda3-2025.06-0-Linux-x86_64.sh

# 创建虚拟环境
conda create -n ros2_env python=3.10 -y

# 切换到新创建的虚拟环境
conda activate ros2_env 

# 安装jupyter notebook
conda install jupyter notebook -y
conda install jupyter_contrib_nbextensions -y

# 安装C++ kernel
conda install xeus-cling -c conda-forge -y

# 检查是否成功安装了kernel
jupyter kernelspec list

# 运行jupyter notebook
# conda activate ros2_env 
# jupyter notebook
# # 或者启动lab【有目录】
# jupyter lab

Ubuntu安装必要的ros2库

shell 复制代码
sudo apt install python3-colcon-common-extensions -y

安装Python的第三方库:

shell 复制代码
pip install empy catkin_pkg lark jinja2 typeguard jupyter notebook jupyter_contrib_nbextensions -i https://pypi.tuna.tsinghua.edu.cn/simple

运行jupyter服务:

shell 复制代码
# 如果需要在jupyter中使用某个项目的功能包,需要运行
# source install/setup.bash
jupyter lab

在vscode中创建notebook文件control_code.ipynb

然后,配置jupyter文件的运行环境。



接来下输入代码运行测试一下:

3. 运行测试

3.1 发布话题

先初始化ros2

python 复制代码
import rclpy
rclpy.init(args=None)

然后运行主程序

python 复制代码
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
import time

class SimplePublisher(Node):
    def __init__(self):
        super().__init__('simple_publisher')
        
        # 创建发布者,话题名为 "my_topic",队列大小为10
        self.publisher_ = self.create_publisher(String, 'my_topic1', 10)
        
        # 创建定时器,每1秒发布一次消息
        timer_period = 1.0  # 秒
        self.timer = self.create_timer(timer_period, self.timer_callback)
        
        self.count = 0
        self.get_logger().info('发布者节点已启动,开始发布消息...')

    def timer_callback(self):
        # 创建消息
        msg = String()
        msg.data = f'Hello ROS2! 消息编号: {self.count}'
        
        # 发布消息
        self.publisher_.publish(msg)
        
        # 记录日志
        self.get_logger().info(f'发布消息: "{msg.data}"')
        
        self.count += 1

# rclpy.init(args=None)
publisher = SimplePublisher()
rclpy.spin(publisher)

在终端查看节点和话题是否存在:ros2 node list && ros2 topic list

3.2 运行多节点

在实际开发中,经常需要运行多个节点,以实现数据的观测和目标的控制。接下来介绍如何在单个jupyter文件中运行多个节点。

创建并使用多线程启动节点:

python 复制代码
import rclpy
from rclpy.node import Node
from rclpy.executors import MultiThreadedExecutor
from std_msgs.msg import Int32
import threading
import time

# 定义发布者节点
class PublisherNode(Node):
    def __init__(self):
        super().__init__('publisher_node')
        self.publisher_ = self.create_publisher(Int32, 'int_topic', 10)
        self.timer = self.create_timer(0.5, self.timer_callback)  # 每0.5秒触发一次
        self.count = 0

    def timer_callback(self):
        msg = Int32()
        msg.data = self.count
        self.publisher_.publish(msg)
        self.get_logger().info(f'Publishing: "{msg.data}"')
        self.count += 1

# 定义订阅者节点
class SubscriberNode(Node):
    def __init__(self):
        super().__init__('subscriber_node')
        self.subscription = self.create_subscription(
            Int32,
            'int_topic',
            self.listener_callback,
            10)
        self.subscription  # 防止未使用变量警告

    def listener_callback(self, msg):
        self.get_logger().info(f'I heard: "{msg.data}"')

# 初始化rclpy
rclpy.init()

# 创建节点对象
pub_node = PublisherNode()
sub_node = SubscriberNode()

# 创建多线程执行器并添加节点
executor = MultiThreadedExecutor()
executor.add_node(pub_node)
executor.add_node(sub_node)

# 在一个新线程中启动执行器,以避免阻塞Notebook
def spin_thread(executor):
    executor.spin()

spin_thread = threading.Thread(target=spin_thread, args=(executor,), daemon=True)
spin_thread.start()

# 提示信息
print("所有节点已启动。可以继续使用此Notebook,或创建新Cell进行其他操作。")
print("要停止所有节点,请重启内核(Kernel -> Restart Kernel)。")

停止节点:

python 复制代码
executor.shutdown()  # 停止执行器,不再处理节点的回调

清理节点:

python 复制代码
# 清理节点
pub_node.destroy_node()
sub_node.destroy_node()

关闭ros2上下文:

python 复制代码
rclpy.shutdown()

报错

问题:ros2和jupyter运行环境的Python版本不一致

shell 复制代码
ModuleNotFoundError: No module named 'rclpy._rclpy_pybind11'
The C extension '/opt/ros/humble/lib/python3.10/site-packages

分析:这个问题可以通过重新构建并指定jupyter运行的Python环境解决。这里ros2 humble要求python3.10,那么jupyter的python环境也应该为python3.10

相关推荐
Light Gao5 小时前
LeRobot 全链路原理:用一个“1+1=2“的例子讲透机械臂与模型如何接入
机器人·具身智能·vla·模仿学习·lerobot
GlobalInfo10 小时前
全球及中国风电叶片检测机器人行业研究报告(2026版):市场现状、行业前景与占有率分析
运维·网络·人工智能·机器人
天树星智源19 小时前
相机轨迹为什么对不上:问题不在控制模块,而在两段噪声不是同一份
论文阅读·机器人·大模型
Wanda121420 小时前
机器人与机电一体化3D数字孪生机器-Day7
人工智能·3d·机器人·数字孪生
ergevv1 天前
如何使用 NIS 判断观测是否可靠:从卡尔曼滤波推导到机器人实践
机器人·卡尔曼滤波·nis·观测可靠性
todoitbo1 天前
在 Ubuntu ARM64 上运行 Q1 V3.0 MuJoCo 模型:加载、步进和单执行器响应
linux·运维·ubuntu·ai·机器人·仿真教程·启元
dghongcheng1 天前
喷涂机器人品牌推荐:六轴 vs 协作机器人怎么选
机器人·喷涂·喷漆设备·自动喷涂线·自动喷涂
todoitbo1 天前
Q1 MuJoCo 模型里的 49 项传感器定义与 60 维数据:一次关节和 IMU 输出核验
人工智能·ai·机器人·1024程序员节·启元机器人
SteveSenna2 天前
aubo学习:启动真实机械臂
机器人
热金鼠2 天前
2.ROS2 核心机制与命令行实操
ros2