Ask Your Question
2

publisher not publishing on topic

asked 2013-06-23 23:53:06 -0500

vivek rk gravatar image

updated 2013-06-24 00:00:43 -0500

prasanna.kumar gravatar image

im trying to publish a message on a topic once but it never publishes the data at all. This is the code in main

ros::init(argc, argv, "keeper_env");
   ros::NodeHandle n;
   ros::Publisher chatter_pub = n.advertise<std_msgs::Empty>("toggle_led", 1000);
   std_msgs::Empty msg;
   chatter_pub.publish(msg);

even putting it in a finite while loop dosent work

int i=0;
        ros::Rate rat(20);
    while(i<10)
    {   
        chatter_pub.publish(msg);
        ros::spinOnce();
        i++;
                rat.sleep();
    }

but if i put it in an infitite loop then it publishes the data.

while(ros::ok())
    {   
        chatter_pub.publish(msg);
        ros::spinOnce();

    }

If i put it in a if condition in that infinite loop then it still dosent publish. i dont want it to be called infintely. i just need it once. can someone please help me

int i=0;
while(ros::ok())
    {   

        if(i==0)
        {   
            printf("Doses it go iun here \n");
            chatter_pub.publish(msg);
            i++;
        }
        }
edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
7

answered 2013-06-24 03:11:53 -0500

dornhege gravatar image

@Philip is right. The publisher need some time to connect to the subscribers. Your finite loop is just to short for that. I'm not sure what you expect from you condition case in the infinite loop as that is never true.

The proper solution to your problem is to use pub.getNumSubscribers() and wait until that is > 0. Then publish.

edit flag offensive delete link more

Comments

Ah, thanks for the hint about getNumSubscribers! I wasn't aware of that :-)

Philip gravatar imagePhilip ( 2013-06-24 04:22:34 -0500 )edit

In case you run into this issue with rospy: The corresponding function is called get_num_connections().

aschaefer gravatar imageaschaefer ( 2018-12-05 16:52:06 -0500 )edit
3

answered 2013-06-24 02:09:48 -0500

Philip gravatar image

My first guess: you try to publish while the publisher is not fully set up. Can you try waiting for a second (e.g. using usleep(1000*1000)) between creating your publisher and sending the first message?

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2013-06-23 23:53:06 -0500

Seen: 5,489 times

Last updated: Jun 24 '13