ROS2理论与实践——第一章ROS概述与环境搭建(3)

1.3 ROS2快速体验

ROS2涉及的编程语言以C++和Python为主。分别使用C++和Python语言对于案例需求进行实现。
本节实现一个最基本的案例,ROS2版本的HelloWorld

1.3.1 案例简介

1.需求

编写ROS2程序,要求程序运行时,可以在终端输出文本"Helo World"。

2.准备
工作空间的创建和编译
mkdir -p ws00_helloworld/src  # 创建工作空间以及子级目录src,工作空间名称可以自定义
cd ws00_helloworld	# 进入工作空间
colcon build 	# 编译

工作空间创建并编译效果

流程简介
  1. 创建功能包
  2. 编辑源文件
  3. 编辑配置文件
  4. 编译
  5. 执行

1.3.2 HelloWorld (C++)

1.创建功能包
cd ws00_helloworld/src
ros2 pkg create pkg01_helloworld_cpp --build-type ament-cmake --dependencies rclcpp --node-name helloworld
2.编辑源文件
/*

  需求:在终端输出文本 hello world。
 流程:
 	1.包含头文件;
 	2.初始化ROS2客户端;
 	3.创建节点指针;
	4.输出日志;
	5.释放资源;

*/
#include <rclcpp/rclcpp.hpp>


// 方式1(不推荐)
/*int main(int argc, char ** argv)
{
  // 2.初始化ROS2客户端;
  rclcpp::init(argc, argv);
  // 3.创建节点指针;
  auto node = rclcpp::Node::make_shared("helloworld_node");
  // 4.输出日志;
  RCLCPP_INFO(node->get_logger(), "hello world!");
  // 5.释放资源;
  rclcpp::shutdown();
  return 0;
}
*/

// 方式2(推荐)

// 自定义类继承 Node
class MyNode : public rclcpp::Node
{
public:
    MyNode(): Node("hello_node_cpp")
    {
        RCLCPP_INFO(this->get_logger(), "hello world!(继承方式)");
    }
};

int main(int argc, char const *argv[])
{
    // 初始化
    rclcpp::init(argc, argv);
    // 实例化自定义类
    auto node = std::make_shared<MyNode>();
    // ……
    
    // 资源释放
    rclcpp::shutdown();
    return 0;
}
3.编辑配置文件

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">
  <name>pkg01_helloworld_cpp</name>
  <version>0.0.0</version>
  <description>TODO: Package description</description>
  <maintainer email="wanrs@todo.todo">wanrs</maintainer>
  <license>TODO: License declaration</license>

  <buildtool_depend>ament_cmake</buildtool_depend>

  <depend>rclcpp</depend>

  <test_depend>ament_lint_auto</test_depend>
  <test_depend>ament_lint_common</test_depend>

  <export>
    <build_type>ament_cmake</build_type>
  </export>
</package>

CMakeLists.txt

cmake_minimum_required(VERSION 3.8)
project(pkg01_helloworld_cpp)

if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
  add_compile_options(-Wall -Wextra -Wpedantic)
endif()

# find dependencies
find_package(ament_cmake REQUIRED)
find_package(rclcpp REQUIRED)

add_executable(helloworld src/helloworld.cpp)
target_include_directories(helloworld PUBLIC
  $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
  $<INSTALL_INTERFACE:include>)
target_compile_features(helloworld PUBLIC c_std_99 cxx_std_17)  # Require C99 and C++17
ament_target_dependencies(
  helloworld
  "rclcpp"
)

install(TARGETS helloworld
  DESTINATION lib/${PROJECT_NAME})

if(BUILD_TESTING)
  find_package(ament_lint_auto REQUIRED)
  # the following line skips the linter which checks for copyrights
  # comment the line when a copyright and license is added to all source files
  set(ament_cmake_copyright_FOUND TRUE)
  # the following line skips cpplint (only works in a git repo)
  # comment the line when this package is in a git repo and when
  # a copyright and license is added to all source files
  set(ament_cmake_cpplint_FOUND TRUE)
  ament_lint_auto_find_test_dependencies()
endif()

ament_package()

4.编译

终端下进入到工作空间,执行如下指令:

colcon build
5.执行
. install/setup.bash
ros2 run pkg01_helloworld_cpp helloworld

1.3.3 HelloWorld (Python)

1. 创建功能包

终端下,进入ws00_helloworld/src目录,使用如下指令创建一个python功能包:

ros2 pkg create pkg02_helloworld_py --build-type ament_python --dependencies rclpy --node-name helloworld
2.编辑源文件
"""

  需求:在终端输出文本 hello world。
 流程:
 	1.导包;
 	2.初始化ROS2客户端;
 	3.创建节点指针;
	4.输出日志;
	5.释放资源;

"""

# 1.导包;
import rclpy
from rclpy.node import Node

# 方式1(不推荐)
"""
def main():
	# 2.初始化ROS2客户端;
	rclpy.init()
	# 3.创建节点指针;
	node = rclpy.create_node("helloworld_node_py")
	# 4.输出日志;
	node.get_logger().info("hello world!(python)")
	# 5.释放资源;
	rclpy.shutdown()
"""

# 方式2(推荐)
# 自定义类
class MyNode(Node):
      def __init__(self):
            super().__init__("hello_node_py")
            self.get_logger().info("hello world!(Python 继承方式)")
    

def main():
    # 初始化
	rclpy.init()
	# 创建对象
	node = MyNode()
    # ……
	
	# 资源释放
	rclpy.shutdown()
if __name__ == '__main__':
    main()

3.编辑配置文件

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">
  <name>pkg02_helloworld_py</name>
  <version>0.0.0</version>
  <description>TODO: Package description</description>
  <maintainer email="wanrs@todo.todo">wanrs</maintainer>
  <license>TODO: License declaration</license>

  <depend>rclpy</depend>

  <test_depend>ament_copyright</test_depend>
  <test_depend>ament_flake8</test_depend>
  <test_depend>ament_pep257</test_depend>
  <test_depend>python3-pytest</test_depend>

  <export>
    <build_type>ament_python</build_type>
  </export>
</package>

setup.py

from setuptools import find_packages, setup

package_name = 'pkg02_helloworld_py'

setup(
    name=package_name,
    version='0.0.0',
    packages=find_packages(exclude=['test']),
    data_files=[
        ('share/ament_index/resource_index/packages',
            ['resource/' + package_name]),
        ('share/' + package_name, ['package.xml']),
    ],
    install_requires=['setuptools'],
    zip_safe=True,
    maintainer='wanrs',
    maintainer_email='wanrs@todo.todo',
    description='TODO: Package description',
    license='TODO: License declaration',
    tests_require=['pytest'],
    entry_points={
        'console_scripts': [
            'helloworld = pkg02_helloworld_py.helloworld:main'
        ],
    },
)
4.编译
colcon build
执行
. install/setup.bash 
ros2 run pkg02_helloworld_py helloworld

参考内容作者:猛狮集训营 https://www.bilibili.com/read/cv26474122/?spm_id_from=333.999.0.0 出处:bilibili
侵删。CSDN私信联系

  • 11
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
ROS机器人理论实践pdf》是一本关于ROS机器人操作系统)的理论实践方面的电子书籍,内容非常丰富。ROS是一个开源的机器人软件平台,为机器人开发者提供了一套强大的工具和库,用于创建、运行和管理机器人软件。 这本书主要分为两个部分,理论实践。在理论部分,作者详细介绍了ROS的基本概念、架构和工作原理。读者可以了解到ROS的节点、话题、服务、参数等核心概念,以及ROS的通信机制和消息传递方式。此外,还介绍了ROS的软件包管理系统和常用工具,帮助读者更好地使用ROS进行机器人开发。 在实践部分,作者提供了一些具体的应用案例,涵盖了机器人的感知、控制和导航等领域。读者可以学习如何使用ROS来构建机器人的传感器驱动程序、运动控制算法和导航系统。此外,还介绍了如何使用ROS与外部硬件进行通信,以及如何将ROS与机器学习、深度学习等技术相结合,实现更智能的机器人应用。 这本书适合有一定编程基础的读者阅读,尤其对于对机器人领域感兴趣的学生和工程师来说,是一本很好的参考书。通过学习这本书,读者可以系统地学习ROS理论知识,并通过实践项目来巩固所学内容。同时,这本书也可以作为学校机器人课程的教材,帮助教师传授ROS相关知识和技能。 总之,《ROS机器人理论实践pdf》是一本全面介绍ROS的电子书,对于进一步学习和应用ROS的读者来说,具有很大的参考价值。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值