Write a simple subscriber in C + +

Source: Internet
Author: User

Open a terminal and go to the Beginner_tutorials package:

CD ~/catkin_ws/src/beginner_tutorials

Create file src/listener.cpp:

Vim Src/listener.cpp

Copy the following code to the file:

#include"Ros/ros.h"#include"std_msgs/string.h"/** * This tutorial demonstrates simple receipt of messages over the ROS system.*/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 You can use a different version of the Init () which takes remappings * directly, but for MOS  T command-line programs, passing ARGC and argv is the easiest * a-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. */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 (); return 0;}

Save exit.

Here's a look at the code explanation:

void chattercallback (const std_msgs::string::constptr& msg) {  ros_info ("  I heard: [%s]", msg->data.c_str ());}

This callback function will be called when a message arrives at the chatter topic.

Ros::subscriber sub = n.subscribe ("chatter", chattercallback);

Subscribe to Chatter topic, and Ros will call the chattercallback () function when a new message arrives. The second parameter is the length of the column, which buffers the received message, buffering 1000 messages, and after 1000, the incoming message will overwrite the previous one.

Nodehandle::subscribe () will return an object of type Ros::subscriber , and when the subscription object is destroyed, it will automatically be withdrawn from the chatter topic.

Ros::spin ();

Ros::spin () enters a loop that calls the message's callback function very quickly. Don't worry if it's nothing to do when it's not going to waste too much CPU.

When Ros::ok () returns false,Ros::spin () exits.

This means that when Ros::shutdown () is called, or CTRL + C is pressed, you can exit.

Here's a summary of the steps to write a Subscriber: (1) Initialize the ROS System (2) Subscribe to Chatter topic (3) Spin, wait for the message to arrive (4) When a message arrives, thechattercallback () function is called.

Let's look at how to build a node. We've previously used catkin_create_pkg to create package.xml and CMakeLists.txt (catalog:catkin_ws/src/beginner_tutorials/cmakelists.txt at this point, your CMakeLists.txt should look like this, including the previous changes, and the comment section can be removed:

2.8. 3 ) Project (beginner_tutorials) # # Find Catkin and any catkin packagesfind_package (catkin REQUIRED Components Roscpp Rospy std_msgs genmsg) # # Declare ROS messages and Servicesadd_message_files (DIRECTORY msg files num.msg) Add_service_ Files (DIRECTORY srv FILES addtwoints.srv) # # Generate added messages and Servicesgenerate_messages (DEPENDENCIES std_msgs ) # # Declare a catkin packagecatkin_package ()

Add the following lines of code to the end of the CMakeLists.txt. Eventually your CMakeLists.txt file looks like this:

 cmake_minimum_required (VERSION 2.8 .  ) project (beginner_tutorials) # # Find Catkin and any catkin packagesfind_package (Catkin REQUIRED Components roscpp rospy std_msgs genmsg) # # Declare ROS messages and servicesadd_message_files (Files NUM.M SG) add_service_files (Files addtwoints.srv) # Generate added messages and Servicesgenerate_messages (DEPENDENCIES std_ msgs) # # Declare a Catkin packagecatkin_package () # # Build talker and listenerinclude_directories (include ${catkin_ Include_dirs}) add_executable (talker src /talker.cpp) target_link_libraries ( Talker ${catkin_libraries}) add_dependencies (talker beginner_tutorials_generate_messages_cpp) add_executable ( Listener src /listener.cpp) target_link_libraries (Listener ${catkin_libraries }) add_dependencies (Listener beginner_tutorials_generate_messages_cpp)  

After the build, this will create two executables, talker and listener. They will be generated in the ~/catkin_ws/devel/lib/share/<package name> directory, which means that the building will be placed in the Devel directory, the original thing will remain in the src file.

Start building below and type in your workspace root directory:

Catkin_make

This allows us to complete the creation of the executable module of the Publisher and subscriber of the message on a topic.

Write a simple subscriber in C + +

Related Article

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.