ROS2_03 - 8BitsCoding/RobotMentor GitHub Wiki

νŒ¨ν‚€μ§€ 생성

$ source /opt/ros/crystal/setup.bash

ROS2.0 λͺ…λ Ήμ–΄λ₯Ό μ‚¬μš©ν•˜κΈ° μœ„ν•΄μ„œ source

$ ros2 pkg create topic_publisher_pkg --build-type ament_cmake --dependencies rclcpp std_msgs

ROS 2.0 νŒ¨ν‚€μ§€ 생성(μ„€λͺ…은 쉽기에 μƒλž΅)


CMake μˆ˜μ •

add_executable(simple_publisher_node src/simple_topic_publisher.cpp)
ament_target_dependencies(simple_publisher_node rclcpp std_msgs)

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

# Install launch files.
install(DIRECTORY
  launch
  DESTINATION share/${PROJECT_NAME}/
)

cpp 생성

#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/int32.hpp"

int main(int argc, char * argv[])
{
  rclcpp::init(argc, argv);
  auto node = rclcpp::Node::make_shared("simple_publisher");
  auto publisher = node->create_publisher<std_msgs::msg::Int32>("counter");
  auto message = std::make_shared<std_msgs::msg::Int32>();
  message->data = 0;
  rclcpp::WallRate loop_rate(2);

  while (rclcpp::ok()) {
    
    publisher->publish(message);
    message->data++;
    rclcpp::spin_some(node);
    loop_rate.sleep();
  }
  rclcpp::shutdown();
  return 0;
}

μƒμ„±λœ topic 확인

$ ros2 topic list | grep  '/counter'
$ ros2 topic info /counter
Topic: /counter
Publisher count: 1
Subscriber count: 0
$ ros2 topic echo /counter

일반적 publisher μ½”λ“œ

#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/int32.hpp"
#include <chrono>

using namespace std::chrono_literals;

class SimplePublisher : public rclcpp::Node
{
public:
  SimplePublisher()
  : Node("simple_publisher"), count_(0)
  {
    publisher_ = this->create_publisher<std_msgs::msg::Int32>("counter");
    timer_ = this->create_wall_timer(
      500ms, std::bind(&SimplePublisher::timer_callback, this));
  }

private:
  void timer_callback()
  {
    auto message = std_msgs::msg::Int32();
    message.data = count_;
    count_++;
    publisher_->publish(message);
  }
  rclcpp::TimerBase::SharedPtr timer_;
  rclcpp::Publisher<std_msgs::msg::Int32>::SharedPtr publisher_;
  size_t count_;
};

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

λ©”μ‹œμ§€ 확인

$ ros2 msg show <message>
# Example
$ ros2 msg show std_msgs/Int32
⚠️ **GitHub.com Fallback** ⚠️