1.listener.cpp
#include "ros/ros.h" #include "std_msgs/String.h"
//回调函数,接收到话题后进入 void chatterCallback( const std_msgs::String::ConstPtr& msg ) { ROS_INFO( "heard:[%s]", msg->data.c_str() ); } int main( int argc, char** argv ) { ros::init(argc,argv,"listener"); //初始化一个名为listener的节点 ros::NodeHandle n; ros::Subscriber sub = n.subscribe("chatter",1000,chatterCallback); //订阅一个话题 ros::spin(); //节点进入循环状态 return 0; }
2.talker.cpp
#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); //设置循环的频率,10hz int count = 0; while (ros::ok()) { std_msgs::String msg; std::stringstream ss; ss << "helloworld" << count; msg.data = ss.str(); chatter_pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); ++count; } return 0; }
3.CMakeList.txt加入
add_executable(talker src/talker.cpp) target_link_libraries(talker ${catkin_LIBRARIES}) add_dependencies(talker ${PROJECT_NAME}_generate_messages_cpp) add_executable(listener src/listener.cpp) target_link_libraries(listener ${catkin_LIBRARIES}) add_dependencies(listener ${PROJECT_NAME}_generate_messages_cpp)