接下來我們要來寫 Hello World 並編譯與執行它
cd ~/tutorial_ws/src
ros2 pkg create --build-type ament_cmake my_pkg --dependencies rclcpp
cd ~/tutorial_ws/src/my_pkg/src
touch hello.cpp
#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;
}
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}
)
意思:
add_executable:編譯出執行檔 helloinstall:把執行檔放進 install,讓 ros2 run 找得到回到 workspace 然後編譯
編譯前要先讓終端吃到 ROS2 的環境變數,告訴電腦 ROS2 已經安裝在哪裡
cd ~/tutorial_ws
source /opt/ros/humble/setup.bash
colcon build
source install/setup.bash
ros2 run my_pkg hello