0
$\begingroup$

Rosanswers logo

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;
 va=(v1+vr)/2;}

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

    float a1 = msg2->a1;
float a2 = msg2->a2;
a=(a1+a2)/2;}

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);
ros::spin();

return 0;

}


Originally posted by Knowledge on ROS Answers with karma: 31 on 2016-03-26

Post score: 0

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

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.


Originally posted by NEngelhard with karma: 3519 on 2016-03-26

This answer was ACCEPTED on the original site

Post score: 2


Original comments

Comment by Knowledge on 2016-03-27:
Please can you give an example how should i do this?

Comment by NEngelhard on 2016-03-27:
a) call ros::init once b) call ros::spin() after you set up the second subscriber

Comment by Knowledge on 2016-03-27:
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

Comment by Augusto Luis Ballardini on 2016-03-27:
Follow the wiki example Writing the Subscriber Node and instead of one single callback write as many as you want.

Comment by NEngelhard on 2016-03-27:
You should probably start by learning C++ before your dive into ROS. You are not allowed to have several variables with the same name.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.