學習資料主要源自http://wiki.ros.org/ROS/Tutorials/WritingPublisherSubscriber%28c%2B%2B%29html
$ roscd beginner_tutorials/c++
$ mkdir -p src函數
$ cd srcoop
$ gedit talker.cpp學習
1. 編寫發佈器節點 talkerui
#include "ros/ros.h" #include "std_msgs/String.h" #include <sstream> int main(int argc, char **argv) { //初始化ROS,名稱重映射(惟一),必須爲base name,不含/ ros::init(argc, argv, "talker"); // 爲進程的節點建立一個句柄,第一個建立的NodeHandle初始化節點 ros::NodeHandle n; // 告訴主機要在chatter topic上發佈一個std_msgs消息 // 主機會訂閱全部chatter topic節點,參數表示發佈隊列的大小(先進先出) ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000); ros::Rate loop_rate(10); // 自循環頻率 int count = 0; while (ros::ok()) { std_msgs::String msg; std::stringstream ss; ss << "hello world " << count; msg.data = ss.str(); // 輸出,用來替代prinf/cout ROS_INFO("%s", msg.data.c_str()); chatter_pub.publish(msg); ros::spinOnce(); // 休眠,來使發佈頻率爲10Hz loop_rate.sleep(); ++count; } return 0; }
實現功能:spa
(1) 初始化ROS系統code
(2) 在chatter topic上發佈std_msgs/String消息htm
(3) 以每秒10次頻率發佈消息blog
2. 編寫訂閱器節點
#include "ros/ros.h" #include "std_msgs/String.h" // 回調函數 void chatterCallback(const std_msgs::String::ConstPtr& msg) { ROS_INFO("I heard: [%s]", msg->data.c_str()); } int main(int argc, char **argv) { ros::init(argc, argv, "listener"); ros::NodeHandle n; // 告訴master須要訂閱chatter topic消息 ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback); ros::spin(); // 自循環 return 0; }
實現功能:
(1) 初始化ROS系統
(2) 訂閱chatter topic消息
(3) 進入自循環,等待消息到達
(4) 消息到達,調用chatterCallback()函數
3. src/<package_name> /CMakeLists.txt
cmake_minimum_required(VERSION 2.8.3) project(beginner_tutorials) ## Find catkin and any catkin packages find_package(catkin REQUIRED COMPONENTS roscpp rospy std_msgs message_generation ) ## Declare ROS messages and services add_message_files( FILES Num.msg ) add_service_files( FILES AddTwoInts.srv ) ## Declare a catkin package catkin_package( CATKIN_DEPENDS message_runtime ) ## Build talker and listener include_directories(include ${catkin_INCLUDE_DIRS} ) add_executable(talker src/talker.cpp) target_link_libraries(talker ${catkin_LIBRARIES}) add_dependencies(talker beginner_tutorials_generate_messages_cpp) add_executable(listener src/listener.cpp) target_link_libraries(listener ${catkin_LIBRARIES}) add_dependencies(listener beginner_tutorials_generate_messages_cpp)
$ rosrun rqt_graph rqt_graph 或直接rqt_graph
注:若是遇到Couldn't find executable named talker below */src/beginner_tutorials
頗有多是工做空間初始化的問題。
參考
http://wiki.ros.org/ROS/Tutorials