ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
0

stop publishing in condition

asked 2022-12-29 19:40:34 -0500

Young gravatar image

updated 2022-12-29 19:42:13 -0500

I want to stop this code if count_ is larger than 10. How can I do it? This is the publiser_member_function.cpp:

#include <chrono>
#include <memory>

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

using namespace std::chrono_literals;

/* This example creates a subclass of Node and uses std::bind() to register a
 * member function as a callback from the timer. */

class MinimalPublisher : public rclcpp::Node
{
public:
  MinimalPublisher()
  : Node("minimal_publisher"), count_(0)
  {
    publisher_ = this->create_publisher<std_msgs::msg::String>("topic", 10);
    timer_ = this->create_wall_timer(
      500ms, std::bind(&MinimalPublisher::timer_callback, this));
  }

private:
  void timer_callback()
  {
    auto message = std_msgs::msg::String();
    message.data = "Hello, world! " + std::to_string(count_++);
    RCLCPP_INFO(this->get_logger(), "Publishing: '%s'", message.data.c_str());
    publisher_->publish(message);
  }
  rclcpp::TimerBase::SharedPtr timer_;
  rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_;
  size_t count_;
};

int main(int argc, char * argv[])
{
  rclcpp::init(argc, argv);
  rclcpp::spin(std::make_shared<MinimalPublisher>());
  rclcpp::shutdown();
  return 0;
}
edit retag flag offensive close merge delete

Comments

This sounds like a general C++ question and not ROS. I suggest general C++ forums since general programming questions not encouraged here.

billy gravatar image billy  ( 2023-01-02 14:57:23 -0500 )edit

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-01-05 19:19:27 -0500

kacaroll gravatar image

add a getter function for the count_. Then, in main(), add a while loop that polls for getCount(). Break once it surpasses 10.

edit flag offensive delete link more

Question Tools

2 followers

Stats

Asked: 2022-12-29 19:40:34 -0500

Seen: 114 times

Last updated: Jan 05 '23