在之前的功能包的基础上,移动到功能包中的src文件夹下编辑发布者文件
vim TheTalker.cpp
#include <sstream>
#include "ros/ros.h"
#include "std_msgs/String.h"
int main(int argc , char ** argv)
{
ros::init( argc , argv , "talker");
/*
named node "talker" and initialize it
*/
ros::NodeHandle nh;
/*
get a node handle to operate the package
*/
ros::Publisher Sender = nh.advertise<std_msgs::String>( "Sender" , 1000 );
/*
named a Sender to be Publisher and give
it node handle , the length of queue is
100 , if too long then quit
*/
ros::Rate loop_rate(10);
/*
wait for 10 hz each times,equals 100ms
*/
int count = 0;
while( ros::ok )
{
std_msgs::String msg;
std::stringstream ss;
ss << "This is " << count << "time sends" << "Hello World by sender" ;
msg.data = ss.str();
ROS_INFO( "Send Succeed %d" , count );
Sender.publish(msg);
ros::spinOnce();
loop_rate.sleep();
count++;
}
return 0;
}
编辑订阅者文件
vim TheListener.cpp
#include "ros/ros.h"
#include "std_msgs/String.h"
void SenderCallback( const std_msgs::String::ConstPtr& msg )
{
/*
When Sender sending a message , this founction will do something
*/
ROS_INFO( " Receive : [%s] " , msg->data.c_str() );
}
int main( int argc , char ** argv )
{
ros::init( argc , argv , "Receiver" );
/*
named node "Receiver" and initialize it
*/
ros::NodeHandle nh;
/*
get a node handle to operate the package
*/
ros::Subscriber rec = nh.subscribe( "Sender" , 1000 , SenderCallback );
/*
named a rec to be Subscriber and give
it node handle , the length of queue is
1000 , if too long then quit
*/
ros::spin();
/*
if there are no message , just wait .
*/
return 0;
}
~
之后使用 cd ~/catkin_ws 和 catkin_make 进行编译或者使用之前定义的cm命令。
再新开一个终端窗口运行roscore命令
呐,你看,这就搞定啦