📜  c++ ros publisher - C++ (1)

📅  最后修改于: 2023-12-03 15:29:49.868000             🧑  作者: Mango

C++ ROS Publisher

Introduction

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.

Prerequisites

Before we begin, make sure you have the following:

  • A working ROS installation
  • Basic knowledge of C++
Steps
  1. 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.

  2. Create a new file called publisher.cpp inside the src directory of pub_node. This file will contain the code for our publisher node.

  3. Open publisher.cpp and include the necessary headers:

    #include <ros/ros.h>
    #include <std_msgs/String.h>
    
  4. 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.

  5. 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.

  6. 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.

  7. Save and close the file.

  8. Build the package: navigate to the root of your ROS workspace directory and run the command catkin_make.

  9. Source the setup file: run the command source devel/setup.bash to set up the environment variables for the package.

  10. Start the ROS master: run the command roscore.

  11. Open a new terminal and run the publisher node: run the command rosrun pub_node publisher_node.

  12. You should see the message "Hello, world!" printed in the terminal every 0.1 seconds (10 Hz).

Conclusion

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.