编写发布器节点
节点(Node) 是指 ROS 网络中可执行文件。接下来,我们将会创建一个发布器节点("talker"),它将不断的在 ROS 网络中广播消息。
切换到之前创建的 beginner_tutorials package 路径下:
cd ~/catkin_ws/src/beginner_tutorials
源代码
在 beginner_tutorials package 路径下创建一个src文件夹:
mkdir -p ~/catkin_ws/src/beginner_tutorials/src
这个文件夹将会用来放置 beginner_tutorials package 的所有源代码。
在 beginner_tutorials package 里创建 src/talker.cpp 文件,并将如下代码粘贴到文件内:https://raw.github.com/ros/ros_tutorials/groovy-evel/roscpp_tutorials/talker/talker.cppraw.github.com
27 #include "ros/ros.h"
28 #include "std_msgs/String.h"
29
30 #include
31
32 /**
33 * This tutorial demonstrates simple sending of messages over the ROS system.
34 */
35 int main(int argc, char **argv)
36 {
37 /**
38 * The ros::init() function needs to see argc and argv so that it can perform
39 * any ROS arguments and name remapping that were provided at the command line. For programmatic
40 * remappings you can use a different version of init() which takes remappings
41 * directly, but for most command-line programs, passing argc and argv is the easiest
42 * way to do it. The third argument to init() is the name of the node.
43 *
44 * You must call one of the versions of ros::init() before using any other
45 * part of the ROS system.
46 */
47 ros::init(argc, argv, "talker");
48
49 /**
50 * NodeHandle is the main access point to communications with the ROS system.
51 * The first NodeHandle constructed will fully initialize this node, and the last
52 * NodeHandle destructed will close down the node.
53 */
54 ros::NodeHandle n;
55
56 /**
57 * The advertise() function is how you tell ROS that you want to
58 * publish on a given topic name. This invokes a call to the ROS
59 * master node, which keeps a registry of who is publishing and who
60 * is subscribing. After this advertise() call is made, the master
61 * node will notify anyone who is trying to subscribe to this topic name,
62 * and they will in turn negotiate a peer-to-peer connection with this
63 * node. advertise() returns a Publisher object which allows you to
64 * publish messages on that topic through a call to publish(). Once
65 * all copies of the returned Publisher object are destroyed, the topic
66 * will be automatically unadvertised.
67 *
68 * The second parameter to advertise() is the size of the message queue
69 * used for publishing messages. If messages are published more quickly
70 * than we can send them, the number here specifies how many messages to
71