Lab 1.3: First example in ROS using C++ – Create a ROS Node that “subscribes” data


This lab is to write your own script in c++ to implement the ROS node which subscribes the data published from lab 1.3.

Create a ROS Node that Subscribes Data

First create .cpp files in package named IamSub.cpp using following commands:

roscd my_ex1/src

gedit IamSub.cpp

Use following code in IamSub.cpp file:

#include “ros/ros.h”
#include “std_msgs/String.h”
void chatterCallback(const std_msgs::String::ConstPtr& msg)
ROS_INFO(“I heard: [%s]”, msg->data.c_str());
int main(int argc, char **argv)
ros::init(argc, argv, “IamSub”);
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe(“message”, 1000, chatterCallback);
return 0;

Then save the file. And open the CMakeLists.txt in my_ex1 folder using following commands:

roscd my_ex1

gedit CMakeLists.txt

Add following line to the last line of the CMakeLists.txt file:

rosbuild_add_executable(IamSub src/IamSub.cpp)

Now you have one additional line for CMakeLists.txt in my_ex1 folder. It should be seen like following:

rosbuild_add_executable(IamPub src/IamPub.cpp)
rosbuild_add_executable(IamSub src/IamSub.cpp)

The above command lines means that the rosmake will compile two executables. Save the CMakeLists.txt, then type following command in the terminal to compile and create the node in bin folder.

rosmake my_ex1

If every thing goes well, you will see something like:

[ rosmake ] Results:
[ rosmake ] Built 25 packages with 0 failures.
[ rosmake ] Summary output to directory
[ rosmake ] /home/stevas/.ros/rosmake/rosmake_output-20150810-155408

If it shows 0 failures, it means the compiling is succeed. You can now execute the node you just create.

Assume you have run the roscore and IamPub node, you can use following command if you forget how to do it:


Open a new terminal:

rosrun my_ex1 IamPub

Now open one more new terminal and run the IamSub node using following command:

rosrun my_ex1 IamSub

Then if everything goes well, you will see following response in the terminal:

[ INFO] [1439197864.052438861]: I heard: [ I am the pub node ]
[ INFO] [1439197864.151676298]: I heard: [ I am the pub node ]
[ INFO] [1439197864.251674456]: I heard: [ I am the pub node ]

The above message means that the IamPub node is publishing the topic called message, the content inside is  “I am the pub node”. And IamSub node is subscribing the topic (message) from the IamPub node.