ros2 publisher code

#include 
#include 
#include 
#include 

#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
#include "string.h"

using namespace std::chrono_literals;
//define a class 
class MinimalPublisher : public rclcpp::Node
{ 
private:
  rclcpp::TimerBase::SharedPtr timer_;
  rclcpp::Publisher::SharedPtr publisher_;//define a pointer to publisher
  size_t count_;  //

public:
  MinimalPublisher(std::string str)
  : Node(str), count_(0)
  {//ros1 uses function advertise() to create a publisher
    publisher_ = this->create_publisher("topic", 10);

    //the parameter seems useless
    timer_ = this->create_wall_timer(
      500ms, std::bind(&MinimalPublisher::timer_callback, this));
  }

private:
  void timer_callback()   //callback function called by system
  {
    auto message = std_msgs::msg::String();//empty string
    message.data = "Hello, world! " + std::to_string(count_++);
    RCLCPP_INFO(this->get_logger(), "Publishing: '%s'", message.data.c_str());//printf("")
    publisher_->publish(message);
  }

};

int main(int argc, char * argv[])
{
  rclcpp::init(argc, argv);
//  rclcpp::spin(std::make_shared());
//  MinimalPublisher node1("nodeName");
  std::shared_ptr pNode=std::make_shared("nodeName");
  rclcpp::spin(pNode);

  rclcpp::shutdown();
  return 0;
}

你可能感兴趣的:(算法,机器人,ros2,ros)