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

subscriber inside if-else/switch-case statements [closed]

asked 2014-08-11 09:16:41 -0500

PJ gravatar image

Hi there, I am new to ros and having a bit of problem when using subscribers. Here is some lines of my code and it is for leader following:

main(int argc, char **argv) {

ros::init(argc, argv, "mycontrol_1");

ros::NodeHandle n;

ros::Subscriber h_sub = n.subscribe("/uav1/sonar_height",1000,hcontrol);

switch (squad_leader_no){

case 1:

  {ros::Subscriber splitcmd_sub = n.subscribe("/uav1/split_cmd", 1000, getsplitcmd);

  break;}

case 2:

  {ros::Subscriber splitcmd_sub = n.subscribe("/uav2/split_cmd", 1000, getsplitcmd);

  break;}

case 3:

  {ros::Subscriber splitcmd_sub = n.subscribe("/uav3/split_cmd", 1000, getsplitcmd);

  break;}

case 4:

  {ros::Subscriber splitcmd_sub = n.subscribe("/uav4/split_cmd", 1000, getsplitcmd);

  break;}

}

// loop rate of 35Hz

ros::Rate cycle(35);

...

In above case, subscription fails. However, when I pull the subscriber out of the switch-case statement, it subscribes successfully. Could anybody explain this if know why, please? Thank you in advance.

edit retag flag offensive reopen merge delete

Closed for the following reason duplicate question by ahendrix
close date 2014-08-11 13:57:37.886602

Comments

This is a duplicate of http://answers.ros.org/question/18970... . Please do not ask duplicate questions.

ahendrix gravatar image ahendrix  ( 2014-08-11 13:57:33 -0500 )edit

1 Answer

Sort by ยป oldest newest most voted
1

answered 2014-08-11 13:47:50 -0500

Murilo F. M. gravatar image

Your problem has nothing to do with ROS, but rather C++. From your code, your subscription is not failing, but the object you're instantiating within each "case" statement is going out of scope straight after you instantiate the object.

Try the following: Add ros::Subscriber splitcmd_sub; just below ros::Subscriber h_sub = ... and then change your "case" statements to only have splitcmd_sub = n.subscribe(...);.

That will solve your problem. :-)

edit flag offensive delete link more

Comments

Thanks a lot, Murilo, but I have closed this question due to duplication. :)

PJ gravatar image PJ  ( 2014-08-14 14:04:13 -0500 )edit

Question Tools

Stats

Asked: 2014-08-11 09:16:41 -0500

Seen: 213 times

Last updated: Aug 11 '14