节点是什么意思呢,类似于模型开发的SWC,每一个SWC就可以看作是一个Node

我现在就用一个功能命名来创建一个节点

1.使用之前的脚本创建一个工程

使用的Shell脚本在之前已经提过

(base) lxj@ubuntuXuejun:~/Desktop/ROS2/myclass$ sh Ros2_CreateProject.sh 
请输入文件夹名称:
Class
工程文件夹 'Class' 创建成功!
Create Finish
(base) lxj@ubuntuXuejun:~/Desktop/ROS2/myclass$ 

2.创建FunctionPackage

在Src路径下创建FunctionPackage,名字就叫做PilotAssistCtrl

ros2 pkg create --build-type ament_cmake PilotAssistCtrl

文件树如下


├── build
├── install
├── log
└── src
    └── PilotAssistCtrl
        ├── CMakeLists.txt
        ├── include
        │   └── PilotAssistCtrl
        ├── package.xml
        └── src

我们在功能包下的src文件里创建一个我们的主源代码文件,命名为PilotAssistCtrl_Sys.cpp

touch pilotassistctrl_sys.cpp

然后我们简单的配置下Cmakelist.txt文件

原始的文件如下,此部分都是自动生成的

cmake_minimum_required(VERSION 3.8)
project(PilotAssistCtrl)

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)
# uncomment the following section in order to fill in
# further dependencies manually.
# find_package(<dependency> 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()

一顿改 主要就是加依赖,可执行文件的配置,然后就是把可执行文件拷贝到install文件夹下

然后我们正常运构建,然后我们去Clion进行开发

colcon build --event-handlers console_direct+ --cmake-args -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -G Ninja --no-warn-unused-cli

3.创建一个自己的节点类

#include <cstdio>
#include <string>
#include "rclcpp/rclcpp.hpp"


namespace rclcpp {
    class Node;
}

class PersonNode : public rclcpp::Node
{
private:
    std::string name_;
    int age_;
public:
    PersonNode(const std::string& node_name,const std::string& name,const int age)
    : rclcpp::Node(node_name) {
        this->name_ = name;
        this->age_ = age;
    }
    void eat(const std::string& food_name) {
        RCLCPP_INFO(this->get_logger(),"I am %s,%d years old,love eat %s",this->name_.c_str(),this->age_,food_name.c_str());
    }
};
int main(int argc, char ** argv)
{
    (void) argc;
    (void) argv;

    rclcpp::init(argc, argv);
    auto node = std::make_shared<PersonNode>("person_node","Xuejun",18);
    RCLCPP_INFO(node->get_logger(), "Hello person_node Node");
    node->eat("food");
    rclcpp::spin(node);
    rclcpp::shutdown();
    return 0;
}

编译后运行就是如下形式