Publishers¶
Creating a Publisher Node¶
Basic steps:
Create a node.
Create a publisher object on a given topic.
Publish messages periodically (for example, using a timer).
Example Publisher (C++)¶
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
class MinimalPublisher : public rclcpp::Node
{
public:
MinimalPublisher()
: Node("minimal_publisher")
{
publisher_ = this->create_publisher<std_msgs::msg::String>("chatter", 10);
timer_ = this->create_wall_timer(
std::chrono::milliseconds(500),
std::bind(&MinimalPublisher::timer_callback, this));
}
private:
void timer_callback()
{
auto msg = std::make_unique<std_msgs::msg::String>();
msg->data = "Hello ROS 2";
RCLCPP_INFO(this->get_logger(), "Publishing: '%s'", msg->data.c_str());
publisher_->publish(std::move(msg));
}
rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_;
rclcpp::TimerBase::SharedPtr timer_;
};
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<MinimalPublisher>());
rclcpp::shutdown();
return 0;
}
Key Parameters¶
Topic name: “chatter” in this example.
Queue size:
10– affects buffering and QoS behavior.
Testing the Publisher¶
After building and sourcing:
ros2 run my_package minimal_publisher
ros2 topic echo /chatter