talker文件内容如下:
#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); ros::Rate loop_rate(10); int count=0; while (ros::ok()) { std_msgs::String msg; std::stringstream ss; ss << "hello ros~!" << count; msg.data = ss.str(); ROS_INFO("%s",msg.data.c_str()); chatter_pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); ++count; } return 0; } /*ros::ok() 返回false的几种情况: SIGINT收到(Ctrl-C)信号 另一个同名节点启动,会先中止之前的同名节点 ros::shutdown()被调用 所有的ros::NodeHandles被销毁 */listener文件内容如下:
#include "ros/ros.h" #include "std_msgs/String.h" void chatterCallback(const std_msgs::String::ConstPtr& msg) { ROS_INFO("I heard: [%s]", msg->data.c_str()); } int main(int argc, char **argv) { ros::init(argc, argv, "listener"); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("chatter", 1000,chatterCallback); ros::spin(); return 0; }