ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

How can i subscribe to multiple topics when programming in C++

asked 2016-03-26 18:14:40 -0500

Knowledge gravatar image

updated 2016-03-27 06:06:01 -0500

Hi, I want to subscribe to multiple topics i am trying the following code but doesn't work. #include "ros/ros.h" #include <robot_position num.h="">

float vk; float v ; float va; float a;

void chatterCallback(const Robot_Position::Num::ConstPtr& msg1) {

    float v1 = msg1->v1;
    float vr = msg1->vr;

void chatterCallback2(const Robot_Position::Num::ConstPtr& msg2) {

    float a1 = msg2->a1;
float a2 = msg2->a2;

int main(int argc, char **argv) {

ros::init(argc, argv, "robot_position");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe<Robot_Position::Num>("Encoder_vel", 1000, chatterCallback);

ros::NodeHandle n;
ros::Subscriber sub = n.subscribe<Robot_Position::Num>("Accelerometer", 1000, chatterCallback2);

return 0;


edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2016-03-26 20:16:34 -0500

NEngelhard gravatar image

Please don't post code that doesn't even compile. You should call the ros::init only once and you need to use ros::spin() so that the program does not terminate immediately.

edit flag offensive delete link more


Please can you give an example how should i do this?

Knowledge gravatar image Knowledge  ( 2016-03-27 04:35:14 -0500 )edit

a) call ros::init once b) call ros::spin() after you set up the second subscriber

NEngelhard gravatar image NEngelhard  ( 2016-03-27 05:02:05 -0500 )edit

I edited the complete code i used. The following error is occuring. ros::Subscriber sub = n.subscribe<robot_position::num>("Encoder_vel", 1000, chatterCallback); make[3]: * [CMakeFiles/position_node.dir/src/position_node.cpp.o] Error 1 make[3]: Leaving directory `/home/saad/jade_workspace/sandbox

Knowledge gravatar image Knowledge  ( 2016-03-27 06:10:27 -0500 )edit

Follow the wiki example Writing the Subscriber Node and instead of one single callback write as many as you want.

Augusto Luis Ballardini gravatar image Augusto Luis Ballardini  ( 2016-03-27 06:15:13 -0500 )edit

You should probably start by learning C++ before your dive into ROS. You are not allowed to have several variables with the same name.

NEngelhard gravatar image NEngelhard  ( 2016-03-27 06:42:15 -0500 )edit

Question Tools

1 follower


Asked: 2016-03-26 18:14:40 -0500

Seen: 927 times

Last updated: Mar 27 '16