|

ROS学习之订阅消息——Subscriber_代码分析

//详解版本:
//本代码文件名为:subscriber.cpp
 
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <iostream>
 
using namespace ros;
using namespace std;
 
//回调函数的形参为std_msgs::String 类型,也就是要处理_msgs::String类型的消息
void callBack(const std_msgs::String &msg){
    cout<<"I heard from topic_1: "<<msg.data.c_str()<<endl;
}
 
int main(int argc, char** argv){
 
    //在使用句柄之前必须初始化节点
    init(argc, argv, "subscriber_Node");
 
    NodeHandle n;
 
    //订阅名为“topic_m”的话题,收到话题后触发 callBack()函数,并将话题中的消息作为实参传给callBack()函数
    Subscriber sub = n.subscribe("topic_m", 1000, callBack);
 
    //在运行到spin()函数时,程序就不再往下执行了,此时程序会一直等待话题“message”,
    //一旦收到话题“message”,就触发callBack()函数, spin()后面的语句也就不再执行了。
    spin();
    return 0;
}
//简洁版本:
 
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <iostream>
 
using namespace ros;
using namespace std;
 
void callBack(const std_msgs::String &msg){
    cout<<"I heard from topic_m: "<<msg.data.c_str()<<endl;
}
 
int main(int argc, char** argv){
    init(argc, argv, "subscriber_Node");
    NodeHandle n;
    Subscriber sub = n.subscribe("topic_m", 1000, callBack);
    spin();
    return 0;
}

继上节ROS学习之发布消息——Publisher中的CMakeList.txt

cmake_minimum_required(VERSION 2.8.3)

project(my_package)

find_package(catkin REQUIRED COMPONENTS
  roscpp
  rospy
  std_msgs
)

catkin_package(
  INCLUDE_DIRS include
  LIBRARIES my_package
  CATKIN_DEPENDS roscpp rospy std_msgs
  DEPENDS system_lib
)

include_directories(
#  include
  ${catkin_INCLUDE_DIRS}
)

# talker_Node在ros中是独一无二的,不能和其它节点名字重复
add_executable(publisher_Node src/publisher.cpp)
target_link_libraries(publisher_Node ${catkin_LIBRARIES})

add_executable(subscriber_Node src/subscriber.cpp)
target_link_libraries(subscriber_Node ${catkin_LIBRARIES})

类似文章

发表回复