本例程节点放在ros_learning
功能包src文件夹下,新建ros_learning
功能包(如果已创建则跳过):
$ cs
$ catkin_create_pkg ros_learning std_msgs rospy roscpp
$ cm
话题程序编写
创建发布者(Publier)
talker_c.cpp1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| #include "ros/ros.h" #include "std_msgs/String.h" #include <sstream>
int main(int argc, char **argv) { ros::init(argc, argv, "talker_c"); ros::NodeHandle n;
ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter_c", 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();
ROS_INFO("%s", msg.data.c_str()); chatter_pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); ++count; }
return 0; }
|
创建订阅者(Subscriber)
listener_c.cpp1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| #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_c"); ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("chatter_c", 1000, chatterCallback); ros::spin(); return 0; }
|
添加配置
方法一:可执行文件添加到CMakeLists.txt末尾位置
CMakeLists.txt1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| add_executable(talker_c src/talker_c.cpp ) add_dependencies(talker_c ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) target_link_libraries(talker_c ${catkin_LIBRARIES} )
add_executable(listener_c src/listener_c.cpp ) add_dependencies(listener_c ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) target_link_libraries(listener_c ${catkin_LIBRARIES} )
|
方法二:使用Roboware软件自动创建
右键src文件夹选择新建cpp源文件
,然后输入文件名(如listener_c.cpp),再选择加入新的可执行文件中
。可到CMakeLists.txt文件中查看创建结果。
(图)Roboware软件自动创建
程序运行
$ cm
$ roscore
- 打开新终端,运行订阅者,此时发布者还没发送消息:再运行发布者节点:
$ rosrun ros_learning listener_c
$ rosrun ros_learning talker_c
(图)节点运行
$ rqt_graph
(图)查看节点关系