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

Revision history [back]

The second example you provided is the correct way to go in ROS2.

I'm not sure about what do you mean with

I want to be able to control when a Node is made

However you can easily replicate the same behavior of the first example also using the second, more correct, structure.

class MinimalPublisher : public rclcpp::Node {

public:

    MinimalPublisher() : Node("minimal_publisher")
    {
         RCLCPP_INFO(this->get_logger(), "Node created!!");
    } 

    void add_publisher()
    {
        _publisher = this->create_publisher<std_msgs::msg::String>("my_topic");
    }

private:

    rclcpp::Publisher<std_msgs::msg::String>::SharedPtr _publisher;

}

The second example you provided is the correct way to go in ROS2.

I'm not sure about what do you mean with

I want to be able to control when a Node is made

However you can easily replicate the same behavior of the first example also using the second, more correct, structure.

class MinimalPublisher : public rclcpp::Node {

public:

    MinimalPublisher() : Node("minimal_publisher")
    {
         RCLCPP_INFO(this->get_logger(), "Node created!!");
    } 

    void add_publisher()
    {
        _publisher = this->create_publisher<std_msgs::msg::String>("my_topic");
    }

private:

    rclcpp::Publisher<std_msgs::msg::String>::SharedPtr _publisher;

}

Then, just call the add_publisher method when you want to create your publisher.

The second example you provided is the correct way to go in ROS2.

I'm not sure about what do you mean with

I want to be able to control when a Node is made

However you can easily replicate the same behavior of the first example also using the second, more correct, structure.

class MinimalPublisher : public rclcpp::Node {

public:

    MinimalPublisher() : Node("minimal_publisher")
    {
         RCLCPP_INFO(this->get_logger(), "Node created!!");
    } 

    void add_publisher()
    {
        _publisher = this->create_publisher<std_msgs::msg::String>("my_topic");
    }

private:

    rclcpp::Publisher<std_msgs::msg::String>::SharedPtr _publisher;

}

Then, just create an object of type MinimalPublisher when you need it and call the add_publisher method when you want to create your publisher.

the publisher. Similarly you will have a method for publishing messages or you may want to set a rclcpp::Timer