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

Can I define publishers in a function and then I can call that function in main() file? Can I really?

asked 2013-08-29 01:40:05 -0600

this post is marked as community wiki

This post is a wiki. Anyone with karma >75 is welcome to improve it.

I just wanted to ask whether I can define my publisher in a function and then call the function in a main() file like the following code sniplet exhibits:

static void myfunct(stream* str, strble *conv, unsigned char *buff, int n){
ros::NodeHandle nh;
ros::Publisher pub_navigation_msg = nh.advertise<rtklib::Navigation>("nav_topic", 10);

rtklib::Navigation navmsg;
navmsg.time= conv->time;

pub_navigation_msg.publish(navmsg);
}


int main(int argc, char** argv){

    ros::Rate r(1); 
    while (ros::ok()){
      myfunct();
    }   
ros::spinOnce();
}
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2013-08-29 01:56:23 -0600

dornhege gravatar image

Yes, you can, in principle. However, your code won't work.

I'm not sure which of several problems you want us to ignore, but to at least address the major concerns regarding publishers: You need to create a publisher just once, but once it is created you need to make sure that the publisher stays somewhere and isn't destroyed.

edit flag offensive delete link more

Comments

I have edited the above code. Do you think it will work like this. Because I also defined by Nodehandler inside the function. I thought we can only define nodehandler and publisher inside a main file.

Gudjohnson gravatar image Gudjohnson  ( 2013-08-29 02:02:58 -0600 )edit

The problem is that you are always recreating a new publisher and the old one gets destroyed before you leave the function. When you publish to you newly created one it will very likely not have build up a connection yet.

dornhege gravatar image dornhege  ( 2013-08-29 02:39:38 -0600 )edit

It is no problem to create a publisher in a function, just do it once before your main loop, make sure that it doesn't get destroyed and not re-create a new one over and over in a loop.

dornhege gravatar image dornhege  ( 2013-08-29 02:39:43 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2013-08-29 01:40:05 -0600

Seen: 223 times

Last updated: Aug 29 '13