📅  最后修改于: 2023-12-03 15:34:44.749000             🧑  作者: Mango
In this tutorial, we will learn how to publish an integer message using ROS C++ API (roscpp
). We will use roscpp
to create a publisher node that sends integer messages to a topic.
We will start by creating a new ROS package called demo_package
. Open a terminal window and execute the following command:
$ cd ~/catkin_ws/src
$ catkin_create_pkg demo_package roscpp std_msgs
This command will create a new ROS package with the dependencies roscpp
and std_msgs
.
Execute the following commands in your terminal to build the package:
$ cd ~/catkin_ws
$ catkin_make
Create a new source file publisher_node.cpp
inside the src
directory of your package.
Include the necessary headers:
#include <ros/ros.h>
#include <std_msgs/Int32.h>
int main(int argc, char **argv)
{
// Initialize the ROS node
ros::init(argc, argv, "publisher_node");
ros::NodeHandle nh;
// ...
}
ros::Publisher pub = nh.advertise<std_msgs::Int32>("int_topic", 10);
This creates a publisher object pub
that publishes integer messages to the topic int_topic
.
ros::Rate loop_rate(1); // loop at 1 Hz
while (ros::ok()) { // run until the node is terminated
std_msgs::Int32 msg;
msg.data = 42;
pub.publish(msg); // publish the message
ros::spinOnce();
loop_rate.sleep();
}
This loop publishes integer messages with the value 42
at a rate of 1 Hz.
#include <ros/ros.h>
#include <std_msgs/Int32.h>
int main(int argc, char **argv)
{
// Initialize the ROS node
ros::init(argc, argv, "publisher_node");
ros::NodeHandle nh;
// Create a publisher that sends integer messages to "int_topic" topic
ros::Publisher pub = nh.advertise<std_msgs::Int32>("int_topic", 10);
// Loop at 1 Hz and publish integer messages with value 42
ros::Rate loop_rate(1);
while (ros::ok()) {
std_msgs::Int32 msg;
msg.data = 42;
pub.publish(msg);
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
Execute the following command in your terminal to run the node:
$ rosrun demo_package publisher_node
This should start the publisher node and publish integer messages to the topic int_topic
.
In this tutorial, we learned how to create a simple ROS publisher node that sends integer messages using roscpp
. We created a ROS package and wrote a simple publisher node that publishes messages to a topic. We also ran the node and confirmed that it correctly published messages to the topic.