0
$\begingroup$

Rosanswers logo

Hi. This is probably an insignificant problem, but I just can't see it.

I used the publisher/subscriber tutorial to make communication in my own program. The publisher publish well in a topic, and the subscriber is subscribe to it, or 'rostopic info' says so, but the callback function does not even start. Whatever I have inside (a variable change, a ROS_INFO, etc.), nothing seems to happen.

This is my code (without the lines of my own program, which are not important):

Publisher:

#include <ros/ros.h>
#include "std_msgs/String.h"
#include <sstream>
#include <iostream>

int main(int argc, char** argv){
  ros::init(argc, argv, "gesture");

  ros::NodeHandle nh;

  std_msgs::String msg;

  ros::Publisher chatter_pub = nh.advertise<std_msgs::String>("chatter", 10);


  ros::Rate rate(10.0);

  while (nh.ok()){
   
    msg.data = "hello world";
    chatter_pub.publish(msg);


    ros::spinOnce();

    rate.sleep();
  }
  return 0;
};

Subscriber:

#include <ros/ros.h>
#include <ros/console.h>
#include <std_msgs/String.h>
#include <iostream>
#include <sstream>

int message=0;

void cb(const std_msgs::String::ConstPtr& msg)
{
  ROS_INFO_STREAM("callback");
  message=1;

}


int main(int argc, char** argv){
  ros::init(argc, argv, "turtle_tf_listener");

ros::NodeHandle n;

  ros::Rate rate(10.0);
  while (node.ok()){
  
 ros::Subscriber sub = n.subscribe ("/chatter", 10, cb);

 ROS_INFO_STREAM(message);
    rate.sleep();
  }

  ros::spinOnce();
  return 0;
};

Everything else from the program works, and it executes well, it is just the callback function wich seems not to run.

Thanks in advance for the answers.


Originally posted by alexjs on ROS Answers with karma: 3 on 2014-11-18

Post score: 0

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

The ros::spinOnce(), where the callback is actually called, is not in your main while loop! Further the subscriber should be set up only once before the while loop. Should be like:

int main(int argc, char** argv){
  ros::init(argc, argv, "turtle_tf_listener");

ros::NodeHandle n;

 ros::Subscriber sub = n.subscribe ("/chatter", 10, cb);

  ros::Rate rate(10.0);
  while (node.ok()){


 ROS_INFO_STREAM(message);
    ros::spinOnce(); // this is where the magic happens!!
    rate.sleep();
  }

  return 0;

};


Originally posted by Wolf with karma: 7555 on 2014-11-18

This answer was ACCEPTED on the original site

Post score: 3


Original comments

Comment by alexjs on 2014-11-20:
Thank yo so much, that was the problem!

Comment by nemesis on 2015-08-07:
@Wolf - I am facing a similar problem but I the above recommendation still doesn't work for me. Could you have a look? http://answers.ros.org/question/214749/subscriber-callback-function-not-called-when-trying-to-capture-data-using-kinect/

$\endgroup$

Your Answer

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