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:
Use following code in IamSub.cpp file:
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::Subscriber sub = n.subscribe(“message”, 1000, chatterCallback);
Then save the file. And open the CMakeLists.txt in my_ex1 folder using following commands:
Add following line to the last line of the CMakeLists.txt file:
Now you have one additional line for CMakeLists.txt in my_ex1 folder. It should be seen like following:
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.
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.