1.使用c++方式创建节点
在d2lros2/chapt2/chapt2_ws/src/example_cpp/src
下新建node_03.cpp
,接着输入下面的代码。
#include "rclcpp/rclcpp.hpp"
/*
创建一个类节点,名字叫做Node03,继承自Node.
*/
class Node03 : public rclcpp::Node
{
public:
// 构造函数,有一个参数为节点名称
Node03(std::string name) : Node(name)
{
// 打印一句
RCLCPP_INFO(this->get_logger(), "大家好,我是%s.",name.c_str());
}
private:
};
int main(int argc, char **argv)
{
rclcpp::init(argc, argv);
/*产生一个node_03的节点*/
auto node = std::make_shared<Node03>("node_03");
/* 运行节点,并检测退出信号*/
rclcpp::spin(node);
rclcpp::shutdown();
return 0;
}
1.2修改CMakeLists.txt
cmake_minimum_required(VERSION 3.8)
project(example_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)
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()
add_executable(node_01 src/node_01.cpp)
ament_target_dependencies(node_01 rclcpp)
install(TARGETS
node_01
DESTINATION lib/${PROJECT_NAME}
)
add_executable(node_03 src/node_03.cpp)
ament_target_dependencies(node_03 rclcpp)
install(TARGETS
node_03
DESTINATION lib/${PROJECT_NAME}
)
1.3编译节点
colcon build --packages-select example_cpp
1.4运行节点
打开新窗口,移动到项目路径
source install/setup.bash
ros2 run example_cpp node_03
运行结果
2.Python版本
在d2lros2/d2lros2/chapt2/chapt2_ws_py/src/example_py/example_py
下新建node_04.py
,输入下面的代码
#!/usr/bin/env python3
import rclpy
from rclpy.node import Node
class Node04(Node):
"""
创建一个Node04节点,并在初始化时输出一个话
"""
def __init__(self,name):
super().__init__(name)
self.get_logger().info("大家好,我是%s!" % name)
def main(args=None):
rclpy.init(args=args) # 初始化rclpy
node = Node04("node_04") # 新建一个节点
rclpy.spin(node) # 保持节点运行,检测是否收到退出指令(Ctrl+C)
rclpy.shutdown() # 关闭rclpy
2.2修改setup.py
from setuptools import find_packages, setup
package_name = 'example_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='joe',
maintainer_email='joe@todo.todo',
description='TODO: Package description',
license='TODO: License declaration',
tests_require=['pytest'],
entry_points={
'console_scripts': [
"node_02 = example_py.node_02:main",
"node_04 = example_py.node_04:main"
],
},
)
2.3编译运行节点
colcon build --packages-select example_py
source install/setup.bash
ros2 run example_py node_04
运行结果如下: