編譯與執行


接下來我們要來寫 Hello World 並編譯與執行它

  1. 進到剛剛創建的 package 下的 src 中
cd ~/tutorial_ws/src
ros2 pkg create --build-type ament_cmake my_pkg --dependencies rclcpp
cd ~/tutorial_ws/src/my_pkg/src
  1. 創建 hello.cpp
touch hello.cpp
  1. 把下面的程式碼貼上去
#include <chrono>
#include <rclcpp/rclcpp.hpp>

using namespace std::chrono_literals;

int main(int argc, char ** argv)
{
  rclcpp::init(argc, argv);

  auto node = rclcpp::Node::make_shared("demo");

  while (rclcpp::ok()) {
    RCLCPP_INFO(node->get_logger(), "Hello World");
    rclcpp::sleep_for(1s);  // 等 1 秒
  }

  rclcpp::shutdown();
  return 0;
}
  1. ctrl + s 存檔後去修改 CMakeLists.txt
find_package(ament_cmake REQUIRED)
find_package(rclcpp REQUIRED)

add_executable(hello src/hello.cpp)
ament_target_dependencies(hello rclcpp)

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

意思:

  1. 回到 workspace 然後編譯

    編譯前要先讓終端吃到 ROS2 的環境變數,告訴電腦 ROS2 已經安裝在哪裡

cd ~/tutorial_ws

source /opt/ros/humble/setup.bash

colcon build
  1. 編譯完後執行看看
source install/setup.bash

ros2 run my_pkg hello