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

How to display the function of latch? [closed]

asked 2017-04-05 22:38:21 -0600

fengxi gravatar image

updated 2017-04-06 00:37:31 -0600

ahendrix gravatar image

I want to show the function of latch in publisher. According to the description of the latch: "When a connection is latched, the last message published is saved and automatically sent to any future subscribers that connect." So I write a small program to show the function of latch. Below is my code, I just did a modification slightly according to the ROS tutorials.

#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>
int main(int argc, char **argv)
{
    ros::init(argc, argv, "talker");

    ros::NodeHandle n;

    ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000, true);

    ros::Rate loop_rate(100);

    int count = 0;
    while(chatter_pub.getNumSubscribers() == 0)
        loop_rate.sleep();


    std_msgs::String msg;
    std::stringstream ss;
    ss << "hello world " << count;
    msg.data = ss.str();

    ROS_INFO("%s", msg.data.c_str());

    chatter_pub.publish(msg);
}

But when I run the subscribers, it doesn't show me the last message published.

Do you know why?

edit retag flag offensive reopen merge delete

Closed for the following reason the question is answered, right answer was accepted by NEngelhard
close date 2017-04-06 09:57:32.230618

1 Answer

Sort by » oldest newest most voted
2

answered 2017-04-06 01:36:09 -0600

NEngelhard gravatar image

Your program terminates after your call to publish. This means that the message is probably not even send once as .publish does not block until the message was serialized and transmitted. Add a ros::spin(); afterwards to keep your program running.

edit flag offensive delete link more

Comments

Yes, you are right. When I add ros::spin(), everything is worked as I expected. Thank you very much.

fengxi gravatar image fengxi  ( 2017-04-06 02:32:04 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2017-04-05 22:38:21 -0600

Seen: 489 times

Last updated: Apr 06 '17