學(xué)習(xí)資料主要源自http://wiki./ROS/Tutorials/WritingPublisherSubscriber%28c%2B%2B%29 $ roscd beginner_tutorials/ $ mkdir -p src $ cd src $ gedit talker.cpp 1. 編寫(xiě)發(fā)布器節(jié)點(diǎn) talker #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"); // 為進(jìn)程的節(jié)點(diǎn)創(chuàng)建一個(gè)句柄,,第一個(gè)創(chuàng)建的NodeHandle初始化節(jié)點(diǎn) ros::NodeHandle n; // 告訴主機(jī)要在chatter topic上發(fā)布一個(gè)std_msgs消息 // 主機(jī)會(huì)訂閱所有chatter topic節(jié)點(diǎn),參數(shù)表示發(fā)布隊(duì)列的大?。ㄏ冗M(jìn)先出) ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000); ros::Rate loop_rate(10); // 自循環(huán)頻率 int count = 0; while (ros::ok()) { std_msgs::String msg; std::stringstream ss; ss << "hello world " << count; msg.data = ss.str(); // 輸出,,用來(lái)替代prinf/cout ROS_INFO("%s", msg.data.c_str()); chatter_pub.publish(msg); ros::spinOnce(); // 休眠,來(lái)使發(fā)布頻率為10Hz loop_rate.sleep(); ++count; } return 0;} 實(shí)現(xiàn)功能: (1) 初始化ROS系統(tǒng) (2) 在chatter topic上發(fā)布std_msgs/String消息 (3) 以每秒10次頻率發(fā)布消息 2. 編寫(xiě)訂閱器節(jié)點(diǎn) #include "ros/ros.h"#include "std_msgs/String.h"// 回調(diào)函數(shù)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(); // 自循環(huán) return 0;} 實(shí)現(xiàn)功能: (1) 初始化ROS系統(tǒng) (2) 訂閱chatter topic消息 (3) 進(jìn)入自循環(huán),,等待消息到達(dá) (4) 消息到達(dá),,調(diào)用chatterCallback()函數(shù) 3. src/<package_name> /CMakeLists.txt cmake_minimum_required(VERSION 2.8.3)project(beginner_tutorials)## Find catkin and any catkin packagesfind_package(catkin REQUIRED COMPONENTS roscpp rospy std_msgs message_generation )## Declare ROS messages and servicesadd_message_files( FILES Num.msg)add_service_files( FILES AddTwoInts.srv)## Declare a catkin packagecatkin_package( CATKIN_DEPENDS message_runtime)## Build talker and listenerinclude_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 很有可能是工作空間初始化的問(wèn)題。 參考 http://wiki./ROS/Tutorials 轉(zhuǎn)載請(qǐng)注明http://www.cnblogs.com/lizhongpingchn/p/5543013.html |
|