ROS基础学习笔记(四):发布者订阅者简单练习

在之前的功能包的基础上,移动到功能包中的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命令

呐,你看,这就搞定啦

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值