0. rqt_graph
显示当前所有节点的关系
1. Create Publisher
talker.cpp:
#include <sstream>
#include "ros/ros.h"
#include "std_msgs/String.h"
int main(int argc, char **argv) {
ros::init(argc, argv, "talker");
ros::NodeHandle n;
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 stringStream;
stringStream << "hello world" << count;
msg.data = stringStream.str();
chatter_pub.publish(msg);
ros::spinOnce();
loop_rate.sleep();
++count;
}
return 0;
}
2. Create Subscriber
listener.cpp:
#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;
ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);
ros::spin();
return 0;
}
3. Compile. 编辑CmakeLists.txt.
include_directories(include ${catkin_INCLUDE_DIRS})
add_executable(talker src/talker.cpp)
add_executable(listener src/listener.cpp)
add_dependencies(talker ${PROJECT_NAME}_generate_messages_cpp)
add_dependencies(listener ${PROJECT_NAME}_generate_messages_cpp)
target_link_libraries(talker ${catkin_LIBRARIES})
target_link_libraries(listener ${catkin_LIBRARIES})
使用 catkin_make
编译
4. Run Publisher and Subscriber
In Terminal 1:
source ./devel/setup.bash
roscore
In Terminal 2:
source ./devel/setup.bash
rosrun learning_communication talker
In Terminal 3:
source ./devel/setup.bash
rosrun learning_communication listener
引用
内容整理自 《ROS 机器人开发实践》3.6 话题中的Publisher 与Subscriber.
Github Repo: https://github.com/huchunxu/ros_exploring.git
网友评论