1. 程式人生 > >ROS學習之訂閱訊息——Subscriber_程式碼分析

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;
}
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})