ROS Study Notes 6- Write a Simple Message Publisher and Subscriber (C++)

Reference: http://wiki.ros.org/cn/ROS/Tutorials/WritingPublisherSubscriber%28c%2B%2B%29

1 Write a publisher node
vim ~/catkin_ws/src/beginner_tutorials/src/talker.cpp
The content of talker.cpp is as follows:
1 #include "ros/ros.h"
  2
  3 /* This refers to the std_msgs/String message, which is stored in the std_msgs package and is a header file automatically generated by the String.msg file */
  4 #include "std_msgs/String.h"
  5
  6 #include <sstream>
  7
  8 int main(int argc, char **argv)
  9 {
 10 /* Initialize ROS to specify the name of the node - during operation, the name of the node must be unique */
 11     ros::init(argc, argv, "talker");
 12 /* Create a handle to this process's node. The first NodeHandle created will initialize the node, and the last NodeHandle destroyed will release all resources occupied by the node. */
 13     ros::NodeHandle n;
 14 /* Tell the master that we are going to publish a message of type std_msgs/String on chatter (topic name). In this way, the master will tell all nodes that have subscribed to the chatter topic that there will be data publishing. The second parameter is the size of the publish sequence. If we publish too frequently > , the buffer will start discarding previously published messages when there are more than 1000 messages.
 15 NodeHandle::advertise() returns a ros::Publisher object, which has two functions: 1) It has a publish() member function that can
    Let you publish messages on the topic; 2) If the message type is wrong, it will refuse to publish. */
 16     ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter",1000);
 17
 18 /* The ros::Rate object allows you to specify the frequency of self-looping. It tracks the elapse of time since the last call to Rate::sleep(), and stops
    sleep until one frequency period.
 19 In this example, we let it run at 10Hz. */
 20     ros::Rate loop_rate(10);
 21
 22     int count  = 0;
 23 /* roscpp will generate a SIGINT handle by default, which handles the Ctrl-C keyboard operation - making ros::ok() return false.
 24 ros::ok() returns false if one of the following conditions occurs:
 25 SIGINT is triggered (Ctrl-C)
 26 kicked out of the ROS network by another node with the same name
 27 ros::shutdown() is called by another part of the program
 28 All ros::NodeHandles in the node have been destroyed
 29 Once ros::ok() returns false, all ROS calls will be invalidated. */
 30     while(ros::ok())
 31     {
 32 /* Use the standard String message, which has only one data member "data" */
 33         std_msgs::String msg;
 34
 35         std::stringstream  ss;
 36         ss << "hello world" << count;
 37         msg.data = ss.str();
 38 /* ROS_INFO and other similar functions can be used instead of printf/cout etc. */
 39         ROS_INFO("%s",msg.data.c_str());
 40 /* Here, we send a message to all nodes subscribed to the chatter topic */
 41         chatter_pub.publish(msg);
 42 /* It's not necessary to call ros::spinOnce() in this example, because we don't accept callbacks. However, if your program contains other > callback functions, it is better to add the statement ros::spinOnce() here, otherwise your callback function will never be called. */
 43         ros::spinOnce();
 44 /* This statement is to call the ros::Rate object to sleep for a period of time so that the publishing frequency is 10Hz. */
 45         loop_rate.sleep();
 46         ++count;
 47     }
 48     return 0;
 49 }
 50
2 Write a subscriber node
vim ~/catkin_ws/src/beginner_tutorials/src/listener.cpp
The content of listener.cpp is as follows :
  1 #include "ros/ros.h"
  2 #include "std_msgs/String.h"
  3
  4 /* This is a callback function that will be called when a chatter topic is received */
  5 void chatterCallback(const std_msgs::String::ConstPtr& msg)
  6 {
  7     ROS_INFO("I heard: [%s]", msg->data.c_str());
  8 }
  9
 10
 11 int main(int argc, char **argv)
 12 {
 13     ros::init(argc, argv, "listener");
 14
 15     ros::NodeHandle n;
 16
 17 /* Tell the master that we want to subscribe to messages on the chatter topic. When a message is published to this topic, ROS will call the chatterCallback() function. The second parameter is the queue size, in case we are not processing messages fast enough, when the buffer reaches 1000 messages, and then a new message arrives > will start discarding previously received messages. NodeHandle::subscribe() returns a ros::Subscriber object, you must keep it active until you don't
    Would like to subscribe to this message again. When this object is destroyed, it will automatically unsubscribe from chatter topic messages. */
 18     ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);
 19 /* ros::spin() enters the self-loop and can call the message callback function as fast as possible. If no message arrives, it won't take a lot of CPU, so > don't worry. Once ros::ok() returns false, ros::spin() immediately jumps out of the self-loop. It's possible that ros::shutdown() was called, or
    Either the user pressed Ctrl-C, causing the master to tell the node to stop running. It is also possible that the node was shut down artificially. */
 20     ros::spin();
 21
 22     return 0;
 23 }
 24


3 Compile the node
Modify the CMakeLists.txt file
   1 cmake_minimum_required(VERSION 2.8.3)
   2 project(beginner_tutorials)
   3
   4 ## Find catkin and any catkin packages
   5 find_package(catkin REQUIRED COMPONENTS roscpp rospy std_msgs genmsg)
   6
   7 ## Declare ROS messages and services
   8 add_message_files(FILES Num.msg)
   9 add_service_files(FILES AddTwoInts.srv)
  10
  11 ## Generate added messages and services
  12 generate_messages(DEPENDENCIES std_msgs)
  13
  14 ## Declare a catkin package
  15 catkin_package()
  16
  17 ## Build talker and listener
  18 include_directories(include ${catkin_INCLUDE_DIRS})
  19
  20 add_executable(talker src/talker.cpp)
  21 target_link_libraries(talker ${catkin_LIBRARIES})
  22 add_dependencies(talker beginner_tutorials_generate_messages_cpp)
  23
  24 add_executable(listener src/listener.cpp)
  25 target_link_libraries(listener ${catkin_LIBRARIES})
  26 add_dependencies(listener beginner_tutorials_generate_messages_cpp)
Now run catkin_make
catkin_make

4 Test the message publisher and subscriber

rosrun beginner_tutorials talker

The following print information can be seen:

rosrun beginner_tutorials listener
The following print information can be seen:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325974048&siteId=291194637