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

publisher and rosinit

asked 2011-09-28 07:50:40 -0600

kang gravatar image

Hi,

I have a small coding problem while writing publisher. Usually I write publisher inside main function in my code:

pub.publish(data);

after initialize ros, create nodhandle, and define publisher. Similar like this tutorial).

Now, I trying to publish not in my main function. But this could not work since the ros initialization and nodeHandle etc are in main function. And if I write the nodehandle in my one of my subfunction, the nodehandle will also directly off after the subfunction being called.

I was thinking if the rosinit could be initialized before the main function, but still have found the way.

Let me now if someone have suggestion. Thx

Cheers, Kang

edit retag flag offensive close merge delete

3 Answers

Sort by ยป oldest newest most voted
3

answered 2011-09-28 11:28:45 -0600

KoenBuys gravatar image

You want the publisher to be declared as a global object. You create the node handle in your start up routine/constructor and initialise the publisher from that.

 //globally defined
 ros::Publisher pub_;

 //in your constructor
 int main(int argc, char** argv){
 ...
 pub_ = nh_.advertise<PointCloud> ("points2", 1);
 ...
 }
edit flag offensive delete link more
5

answered 2011-09-29 19:24:47 -0600

If you don't like global variables, you can also pass the publisher by reference to a function:

void worker (ros::Publisher& pub)
{
  //...
}

int main (int argc, char** argv)
{
  //...
  ros::NodeHandle nh;
  ros::Publisher pub = nh.advertise<PointCloud>("points2", 1);
  //...
  worker(pub);
  //...
}
edit flag offensive delete link more
3

answered 2011-09-28 08:07:31 -0600

Make the node handle a global or class variable so you can reference it from anywhere. You can declare the node handle, without initializing it, then do the initialization in your main function.

edit flag offensive delete link more

Comments

the nodeHandle can be set globlally? I think I have tried that one, but I'll check again soon.
kang gravatar image kang  ( 2011-09-28 08:09:05 -0600 )edit
creating nodeHandle before ros initialization is not allowed. But, I made it work by defining variable in a class.
kang gravatar image kang  ( 2011-09-28 19:26:12 -0600 )edit

Question Tools

Stats

Asked: 2011-09-28 07:50:40 -0600

Seen: 4,144 times

Last updated: Sep 29 '11