【ROS2】第一篇:功能包的创建和编译

一、创建工作空间

创建文件夹

mkdir -p ~/ros2_ws/src
cd ~/ros2_ws
colcon build

二、创建功能包

1、创建功能包

cd ~/ros2_ws/src
ros2 pkg create --build-type ament_cmake my_node

2、创建节点文件

cd ~/ros2_ws/src/my_node
sudo gedit my_node.cpp

my_node.cpp代码具体如下

#include 
#include "rclcpp/rclcpp.hpp"

using namespace std::chrono_literals;

/* This example creates a subclass of Node and uses a fancy C++11 lambda
 * function to shorten the timer syntax, at the expense of making the
 * code somewhat more difficult to understand at first glance if you are
 * unaccustomed to C++11 lambda expressions. */

class MinimalTimer : public rclcpp::Node
{
public:
  MinimalTimer()
  : Node("minimal_timer")
  {
    auto timer_callback = [this]() -> void { RCLCPP_INFO(this->get_logger(), "Hello, world!") };
    timer_ = create_wall_timer(500ms, timer_callback);
  }

private:
  rclcpp::TimerBase::SharedPtr timer_;
};

int main(int argc, char * argv[])
{
  rclcpp::init(argc, argv);
  rclcpp::spin(std::make_shared<MinimalTimer>());
  rclcpp::shutdown();
  return 0;
}

3、修改CMakeLists.txt

cd ~/ros2_ws/src/my_node
sudo gedit CMakeLists.txt

在 find_package(ament_cmake REQUIRED)下面添加

find_package(rclcpp REQUIRED)
find_package(std_msgs REQUIRED)

添加可执行文件的名字为my_node

add_executable(my_node src/my_node.cpp)
ament_target_dependencies(my_node rclcpp std_msgs)

添加 install(TARGETS…) 把可执行文件安装到install去

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

三、 编译和运行

cd ~/ros2_ws
colcon build --packages-select my_node
source install/setup.bash

运行节点

ros2 run my_node my_node

你可能感兴趣的:(ROS2,c++,开发语言)