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

Where should I indeed place my "ros::spin()"?

asked 2018-10-15 10:57:45 -0600

Epsilon_cm gravatar image

I am a freshman for ROS, and I find a interesting (for me) thing: I wrote a node, for example, let's call it my_node.cpp, it looks like this:

//in my_node.cpp
ros::init(argc, argv, "my_node");
ros::NodeHandle nh("");
ros::NodeHandle nh_local("~");
MyNode my_node(nh, nh_local);
ros::spin();

And in the construct function of MyNode, it looks like this:

MyNode (ros::Nodehandle nh, ros:Nodehandle nh_local)
{ 
message_filters::Subscriber<Image> image1_sub(nh, "image1", 1);
message_filters::Subscriber<Image> image2_sub(nh, "image2", 1); 
typedef sync_policies::ApproximateTime<Image, Image> MySyncPolicy;
// ApproximateTime takes a queue size as its constructor argument, hence MySyncPolicy(10)
Synchronizer<MySyncPolicy> sync(MySyncPolicy(10), image1_sub, image2_sub);
sync.registerCallback(boost::bind(&callback, _1, _2));
}

In fact it just looks like the tutorial of ros wiki about message filter. The fact is, my callback function had never been called.When I add "ros::spin()" in the construct function, however, it works. The issue is, I had wrote the construction like this before:

MyNode (ros::Nodehandle nh, ros:Nodehandle nh_local)
{ 
     auto my_sub_ = nh.subscribe("topic", 10, &mycallback, this);
}

And there was no "ros::spin()" in the construct function but there was one in my_node.cpp's main().And it works too. So where should I indeed place my ros::spin()?

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
2

answered 2018-10-15 11:27:05 -0600

I would always put a call to spin outside of your constructor. Imagine someone needs to implement your class in his own code, as soon as he calls the constructor the code after constructor won't be executed. I think I've never seen anyone doing spin in the class itself, unless there was a function called loop() that was doing the processing.

edit flag offensive delete link more

Comments

I agree with you.The fact is,if i place the spin() outside my constructor, then the message_filters::Synchronizer's callback won't be called.That's strange.

Epsilon_cm gravatar image Epsilon_cm  ( 2018-10-16 05:59:20 -0600 )edit

Try making the subscribers private members of the class (e.g. defined in the header file) and only assign to them in the constructor. I think they might be optimized out and as soon as the constructor is called they are disposed.

msadowski gravatar image msadowski  ( 2018-10-16 06:22:23 -0600 )edit

That's my fault, and i tried what you said, it worked.Thanks :)

Epsilon_cm gravatar image Epsilon_cm  ( 2018-10-16 06:51:20 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2018-10-15 10:57:45 -0600

Seen: 364 times

Last updated: Oct 15 '18