ROS中节点在每次接收到消息之后都发布一条消息的反馈topic

#include "ros/ros.h"
#include "std_msgs/String.h"
#include 
ros::Publisher chatter_pub;
ros::Subscriber sub;
void callback()
{
    std_msgs::String msg;

    std::stringstream ss;
    msg.data = "test";

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

    chatter_pub.publish(msg);
}
void function(const std_msgs::StringPtr &msg)
{
		callback();
}

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

    ros::init(argc, argv, "talker");

	ros::NodeHandle n;
	
    chatter_pub = n.advertise("chatter", 1000);
	sub = n.subscribe("/test", 1, &function);

    ros::Rate loop_rate(10);


	ROS_INFO("Please send message!");
	
	ros::spin();
	
    return 0;
}


如果发布一条消息之后直接退出节点,则可以这样:

#include "ros/ros.h"
#include "std_msgs/String.h"

#include 


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

  ros::init(argc, argv, "talker");


  ros::NodeHandle n;


  ros::Publisher chatter_pub = n.advertise("chatter", 1000);

  ros::Rate loop_rate(10);

  int count = 0;

  while (count < 1)
  {

    std_msgs::String msg;

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

    ROS_INFO("%s", msg.data.c_str());
    if(chatter_pub.getNumSubscribers() == 1)
    {
    chatter_pub.publish(msg);
  
    count ++;
    
    ros::spinOnce();

    loop_rate.sleep();
    ++count;
  }
}

  return 0;
}





你可能感兴趣的:(※【ROS】)