📅  最后修改于: 2023-12-03 15:29:49.868000             🧑  作者: Mango
In ROS (Robot Operating System), a publisher is a node that sends messages to a topic. Messages are a way for nodes to communicate with each other. In this tutorial, we will learn how to create a C++ ROS publisher node that publishes a string message to a topic.
Before we begin, make sure you have the following:
Create a new package: navigate to your ROS workspace directory and run the command catkin_create_pkg pub_node roscpp std_msgs
. This will create a new package called pub_node
with dependencies on roscpp
and std_msgs
.
Create a new file called publisher.cpp
inside the src
directory of pub_node
. This file will contain the code for our publisher node.
Open publisher.cpp
and include the necessary headers:
#include <ros/ros.h>
#include <std_msgs/String.h>
Declare the main function and create a ROS node handle:
int main(int argc, char **argv)
{
ros::init(argc, argv, "publisher_node");
ros::NodeHandle nh;
// code for the publisher node
return 0;
}
The ros::init()
function initializes the ROS system and the ros::NodeHandle
object provides a way to interface with the ROS system.
Create a publisher object that publishes messages of type std_msgs::String
:
ros::Publisher pub = nh.advertise<std_msgs::String>("chatter", 1000);
Here, the advertise()
function creates a publisher object that sends messages to the chatter
topic with a buffer size of 1000 messages.
Create a loop that publishes the message:
ros::Rate loop_rate(10);
while (ros::ok())
{
std_msgs::String msg;
msg.data = "Hello, world!";
pub.publish(msg);
ros::spinOnce();
loop_rate.sleep();
}
This loop publishes the message "Hello, world!"
to the chatter
topic at a rate of 10 Hz.
Save and close the file.
Build the package: navigate to the root of your ROS workspace directory and run the command catkin_make
.
Source the setup file: run the command source devel/setup.bash
to set up the environment variables for the package.
Start the ROS master: run the command roscore
.
Open a new terminal and run the publisher node: run the command rosrun pub_node publisher_node
.
You should see the message "Hello, world!"
printed in the terminal every 0.1 seconds (10 Hz).
In this tutorial, we learned how to create a C++ ROS publisher node that publishes a string message to a topic. We covered the necessary steps to create a ROS package, create a publisher object, and publish messages to the topic. With this knowledge, you can now build more complex ROS systems that involve multiple nodes communicating with each other.