Ros Learning (12)-writing a simple message publisher and Subscriber (C + +)

Source: Internet
Author: User
Tags message queue

First, create a publisher node

1 Node Features:

Constantly broadcasting messages in the ROS network

2 Creating nodes

(1) Open Workspace directory

CD ~/catkin_ws/src/beginner_tutorials

(2) Create SRC folder

Mkdir-p ~/CATKIN_WS/SRC/BEGINNER_TUTORIALS/SRC

(3) Create the Talkler.cpp file and attach the code

#include"Ros/ros.h"              //Ros/ros.h is a useful header file that references most of the commonly used header files in the Ros system, which makes programming easy. #include"std_msgs/string.h"      //this refers to the std_msgs/string message, which is stored in the STD_MSGS package and is a header file that is automatically generated by the String.msg file. //for a more detailed message definition, refer to the MSG page.#include<sstream>/** * This tutorial demonstrates simple sending of messages over the ROS system.*/intMainintargcChar**argv) {  /** * The Ros::init () function needs to see ARGC and argv so, it can perform * any Ros arguments and name Remapp   ing that were provided at the command line. * For programmatic remappings your can use a different version of Init () which takes * remappings directly  command-line programs, passing ARGC and argv is * The easiest-to-do it.   The third argument to Init () is the name of the node.   * * Must call one of the versions of Ros::init () before using any other * part of the ROS system. */Ros::init (argc, argv,"Talker");// Initialize Ros.                                     It allows Ros to name remap through the command line-this is not the point at the moment. //again, we specify the name of our node here-must be unique.   /** * Nodehandle is the main access point to communications with the ROS system.  * The first nodehandle constructed would fully initialize this node, and the last * Nodehandle destructed would close down    The node. Create a handle for the node of this process.    The first created Nodehandle initializes the node, and the last one destroys all resources used by the node. */ros::nodehandle N; /** * The Advertise () function is what you tell ROS, you want to * publish on a given to Pic Name. This invokes a call to the ROS * Master node, which keeps a registry of who are publishing and who * is subscribing.    After this advertise () call was made, the master * node would notify anyone who was trying to subscribe to this topic name,  * And they'll in turn negotiate a peer-to-peer connection with this * node.   Advertise () returns a Publisher object which allows you to * publish messages on the topic through a call to publish ().   Once * All copies of the returned Publisher object is destroyed, the topic * would be automatically unadvertised.  * * The second parameter to advertise () are the size of the message queue * used for publishing messages. IF messages is published more quickly * than we can send them, the number here specifies what many messages to * Buffe   R up before throwing some away. */   /*1. Tell master we are going to post a std_msgs/string message on chatter topic.     This way, Master will tell all the nodes that have subscribed to chatter topic and will have data published. 2, the second parameter is the size of the publication sequence.      In such a case, if we publish the message too fast, the message in the buffer will start discarding the previously published message when it is greater than 1000.                                                                      3, Nodehandle::advertise () returns a Ros::P ublisher object, it has two functions: 1) It has a publish () member function that allows you to post messages on topic;   2) If the message type is not correct, it rejects the publication. */Ros::P ublisher chatter_pub= N.advertise<std_msgs::string> ("Chatter", +); //the Ros::rate object allows you to specify the frequency of the self-loop. It tracks the elapsed time since the last call to Rate::sleep () and sleeps until a frequency period. Ros::rate Loop_rate (Ten); /** * A Count of how many messages we have sent.   This is used to create * a unique string for each message. */  intCount =0; /*Roscpp will install a SIGINT handle by default, which handles CTRL-C keyboard operations-making Ros::ok () return false. Ros::ok () returns False if one of the following conditions occurs: 1) SIGINT received (CTRL-C) 2) was kicked out of the ROS network by another node of the same name 3) Ros::shutdow N () Called by another part of the program 4) all ros::nodehandles have been destroyed.*/   while(Ros::ok ()) {/** * This is a message object.     You stuff it with data, and then publish it. */    //we broadcast messages in the ROS network using a ' message adaptive ' class produced by the msg file files. Now we are using the standard string message, which has only one data member, "". Of course you can also publish more complex message types. std_msgs::string msg;    Std::stringstream SS; SS<<"Hello World"<<count; Msg.data=Ss.str (); Ros_info ("%s", Msg.data.c_str ()); /** * The Publish () function is what you send messages. The parameter * is the message object. The type of this object must agree with the type * given as a template parameter to the advertise<> () call, as W     As done * in the constructor above. */chatter_pub.publish (msg); //Now we've sent a message to all the nodes connected to chatter topicros::spinonce (); //in this example, it is not always important to call Ros::spinonce (), because we do not accept callbacks. //However, if you want to expand the program without calling Ros::spinonce (), your callback function will never be called. Therefore, it is better to add this statement here. Loop_rate.sleep (); //This statement calls the Ros::rate object to sleep for a period of time so that the release frequency is 10hz. ++count; }  return 0;}

Second, write the Subscriber node

In the src file, continue to write the Listener.cpp file, and attach the code

#include"Ros/ros.h"#include"std_msgs/string.h"/** * This tutorial demonstrates simple receipt of messages over the ROS system. * This is a callback function that will be called when the message arrives at Chatter topic. The message is transmitted in the form of a boost shared_ptr pointer, which means you can store it without having to copy the data*/voidChattercallback (Conststd_msgs::string::constptr&msg) {Ros_info ("I heard: [%s]", msg->data.c_str ());}intMainintargcChar**argv) {  /** * The Ros::init () function needs to see ARGC and argv so, it can perform * any Ros arguments and name Remapp   ing that were provided at the command line. * For programmatic remappings your can use a different version of Init () which takes * remappings directly  command-line programs, passing ARGC and argv is * The easiest-to-do it.   The third argument to Init () is the name of the node.   * * Must call one of the versions of Ros::init () before using any other * part of the ROS system. */Ros::init (argc, argv,"Listener"); /** * Nodehandle is the main access point to communications with the ROS system.  * The first nodehandle constructed would fully initialize this node, and the last * Nodehandle destructed would close down   The node. */ros::nodehandle N; /** * The subscribe () call is a-you-tell ROS, want to receive messages * on a given topic.  This invokes a call to the ROS * Master node, which keeps a registry of who are publishing and who * is subscribing.  Messages is passed to a callback function, here * called Chattercallback.  Subscribe () Returns a Subscriber object that you * must hold on to until you want to unsubscribe. When all copies of the Subscriber * object go out of scope, this callback would automatically be unsubscribed from * th   Is topic.  * * The second parameter to the subscribe () function is the size of the message * queue.  If messages is arriving faster than they was being processed, this * is the number of the messages that would be buffered up   Before beginning to throw * away the oldest ones. */   //Tell master we want to subscribe to the messages on chatter topic.   When a message arrives at topic, Ros invokes the Chattercallback () function. //The second parameter is the queue size, in case we are not processing the message fast enough, after 1000 messages are cached, a new message arrives and the previously received message will start discarding. //Nodehandle::subscribe () returns the Ros::subscriber object, you must keep it active until you no longer want to subscribe to the message.    When this object is destroyed, it will automatically unsubscribe from the message. //there are various nodehandle::subscribe () functions that allow you to specify member functions of a class, even any data type that a Boost.function object can invoke. Roscpp Overview provides more detailed information. Ros::subscriber Sub= N.subscribe ("Chatter", +, Chattercallback); /** * Ros::spin () would enter a loop, pumping callbacks.  With this version, all * callbacks'll is called from within this thread (the main one).   Ros::spin () * Would exit when CTRL-C was pressed, or the node is shutdown by the master. */  //Ros::spin () enters the self-loop and can call the message callback function as quickly as possible.  If no message arrives, it won't take up a lot of CPU, so don't worry. //once Ros::ok () returns to False,ros::spin (), it jumps out of the loop immediately. //1) It is possible that Ros::shutdown () is called,//2) or the user pressed the ctrl-c, so that master tells the node to shutdown. It is also possible that the node has been artificially closed. Ros::spin (); return 0;}

Ros Learning (12)-writing a simple message publisher and Subscriber (C + +)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.