ROS2学习之路之话题发布(Publisher)

主要代码:

//topic-pub
rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_;
publisher_ = nodePtr_->create_publisher<std_msgs::msg::String>("topic", 10);
publisher_->publish(msg);

eg.1


#include <rclcpp/rclcpp.hpp>
#include <std_msgs/msg/int8.hpp>
#include <chrono>
#include <functional>
#include <memory>
#include <string>
#include "std_msgs/msg/string.hpp"

using namespace std::chrono_literals;


class MinimalPublisher
{
  private:
    rclcpp::Node::SharedPtr nodePtr_;
    rclcpp::TimerBase::SharedPtr timer_;
    rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_;
    size_t count_;
  public:
    MinimalPublisher(rclcpp::Node::SharedPtr& nodePtr):nodePtr_(nodePtr),count_(0)
    {
      publisher_ = nodePtr_->create_publisher<std_msgs::msg::String>("topic", 10);
      timer_ = nodePtr_->create_wall_timer(500ms, std::bind(&MinimalPublisher::timer_callback, this));
    }
    void timer_callback()
    {
      auto message = std_msgs::msg::String();
      message.data = "Hello, world! " + std::to_string(count_++);
      RCLCPP_INFO(nodePtr_->get_logger(), "Publishing: '%s'", message.data.c_str());
      publisher_->publish(message);
    }

};

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

  auto nodePtr = rclcpp::Node::make_shared("mpac_points_filter");
  auto heartBeatPubPtr = nodePtr->create_publisher<std_msgs::msg::Int8>("heartBeat", 10);

  std_msgs::msg::Int8 heartBeatData;
  heartBeatData.data = 6;  //6-filter node
  auto heartBeatTimer = nodePtr->create_wall_timer(std::chrono::seconds(1), [heartBeatPubPtr, heartBeatData]() { heartBeatPubPtr->publish(heartBeatData); });
  
  MinimalPublisher vc(nodePtr);

  rclcpp::spin(nodePtr);
  rclcpp::shutdown();

  return 0;
}

//topic-pub
rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_;
publisher_ = nodePtr_->create_publisher<std_msgs::msg::String>("topic", 10);
publisher_->publish(message);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值