1.编写发布器

  • 初始化 ROS 系统
  • 在 ROS 网络内广播我们将要在 chatter 话题上发布 std_msgs/String 类型的消息

  • 以每秒 10 次的频率在 chatter 上发布消息

在 beginner_tutorials package 里创建 src/talker.cpp 文件:

#include "ros/ros.h"      //一个实用的头文件,它引用了 ROS 系统中大部分常用的头文件
#include "std_msgs/String.h" //引用了 std_msgs/String 消息, 它存放在 std_msgs package 里,是由 String.msg 文件自动生成的头文件。 #include <sstream> /**
* This tutorial demonstrates simple sending of messages over the ROS system.
*/
int main(int argc, char **argv)
{
/**
* The ros::init() function needs to see argc and argv so that it can perform
* any ROS arguments and name remapping that were provided at the command line. For programmatic
* remappings you can use a different version of init() which takes remappings
* directly, but for most command-line programs, passing argc and argv is the easiest
* way to do it. The third argument to init() is the name of the node.
*
* You must call one of the versions of ros::init() before using any other
* part of the ROS system.
*/
ros::init(argc, argv, "talker");  //初始化 ROS.可指定节点的名称。节点的名称必须唯一(名称内不能包含 / 等符号) /**
* NodeHandle is the main access point to communications with the ROS system.
* The first NodeHandle constructed will fully initialize this node, and the last
* NodeHandle destructed will close down the node.
*/
ros::NodeHandle n;  //为这个进程的节点创建一个句柄。
              //第一个创建的 NodeHandle 会为节点进行初始化,最后一个销毁的 NodeHandle 则会释放该节点所占用的所有资源
/**
* The advertise() function is how you tell ROS that you want to
* publish on a given topic name. This invokes a call to the ROS
* master node, which keeps a registry of who is publishing and who
* is subscribing. After this advertise() call is made, the master
* node will notify anyone who is trying to subscribe to this topic name,
* and they will in turn negotiate a peer-to-peer connection with this
* node. advertise() returns a Publisher object which allows you to
* publish messages on that topic through a call to publish(). Once
* all copies of the returned Publisher object are destroyed, the topic
* will be automatically unadvertised.
*
* The second parameter to advertise() is the size of the message queue
* used for publishing messages. If messages are published more quickly
* than we can send them, the number here specifies how many messages to
* buffer up before throwing some away.
*/
ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", );//告诉master 我们将要在 chatter(话题名) 上发布 std_msgs/String 消息类型的消息。
             //如果我们发布的消息的频率太高,缓冲区中的消息在大于 1000 个的时候就会开始丢弃先前发布的消息。
             //advertise返回一个 ros::Publisher 对象,它有两个作用: 1) 它有一个 publish() 成员函数可以让你在topic上发布消息; 2) 如果消息类型不对,它会拒绝发布。
  ros::Rate loop_rate();///**
* A count of how many messages we have sent. This is used to create
* a unique string for each message.
*/
int count = ;
while (ros::ok())      //ros::ok()
{
/**
* This is a message object. You stuff it with data, and then publish it.
*/
std_msgs::String msg; std::stringstream ss;
ss << "hello world " << count;
msg.data = ss.str(); ROS_INFO("%s", msg.data.c_str());//ROS_INFO 和其他类似的函数可以用来代替 printf/cout 等函数。 /**
* The publish() function is how you send messages. The parameter
* is the message object. The type of this object must agree with the type
* given as a template parameter to the advertise<>() call, as was done
* in the constructor above.
*/
chatter_pub.publish(msg);//向所有订阅 chatter 话题的节点发送消息。 ros::spinOnce();      //ros::spinOnce()这一语句,否则你的回调函数就永远也不会被调用 loop_rate.sleep();    //调用 ros::Rate 对象来休眠一段时间以使得发布频率为 10Hz。
++count;
} return ;
}

2.编写订阅器

  

  • 初始化ROS系统
  • 订阅 chatter 话题

  • 进入自循环,等待消息的到达
  • 当消息到达,调用 chatterCallback() 函数

在 beginner_tutorials package 目录下创建 src/listener.cpp 文件:

#include "ros/ros.h"
#include "std_msgs/String.h" /**
* This tutorial demonstrates simple receipt of messages over the ROS system.
*/
void chatterCallback(const std_msgs::String::ConstPtr& msg)//是一个回调函数,当接收到 chatter 话题的时候就会被调用。
{
ROS_INFO("I heard: [%s]", msg->data.c_str());
} int main(int argc, char **argv)
{
/**
* The ros::init() function needs to see argc and argv so that it can perform
* any ROS arguments and name remapping that were provided at the command line. For programmatic
* remappings you can use a different version of init() which takes remappings
* directly, but for most command-line programs, passing argc and argv is the easiest
* way to do it. The third argument to init() is the name of the node.
*
* You must call one of the versions of ros::init() before using any other
* part of the ROS system.
*/
ros::init(argc, argv, "listener"); /**
* NodeHandle is the main access point to communications with the ROS system.
* The first NodeHandle constructed will fully initialize this node, and the last
* NodeHandle destructed will close down the node.
*/
ros::NodeHandle n; /**
* The subscribe() call is how you tell ROS that you want to receive messages
* on a given topic. This invokes a call to the ROS
* master node, which keeps a registry of who is publishing and who
* is subscribing. Messages are passed to a callback function, here
* called chatterCallback. subscribe() returns a Subscriber object that you
* must hold on to until you want to unsubscribe. When all copies of the Subscriber
* object go out of scope, this callback will automatically be unsubscribed from
* this topic.
*
* The second parameter to the subscribe() function is the size of the message
* queue. If messages are arriving faster than they are being processed, this
* is the number of messages that will be buffered up before beginning to throw
* away the oldest ones.
*/
ros::Subscriber sub = n.subscribe("chatter", , chatterCallback);
//告诉 master 我们要订阅 chatter 话题上的消息。当有消息发布到这个话题时,ROS 就会调用 chatterCallback() 函数。第二个参数是队列大小,以防我们处理消息的速度不够快,当缓存达到 1000 条消息后,再有新的消息到来就将开始丢弃先前接收的消息。

/** * ros::spin() will enter a loop, pumping callbacks. With this version, all * callbacks will be called from within this thread (the main one). ros::spin() * will exit when Ctrl-C is pressed, or the node is shutdown by the master. */ 
ros::spin();//ros::spin() 进入自循环,可以尽可能快的调用消息回调函数。 return ;
}

3.编译

cmake_minimum_required(VERSION 2.8.)
project(beginner_tutorials) ## Find catkin and any catkin packages
find_package(catkin REQUIRED COMPONENTS roscpp rospy std_msgs genmsg) ## Declare ROS messages and services
add_message_files(DIRECTORY msg FILES Num.msg)
add_service_files(DIRECTORY srv FILES AddTwoInts.srv) ## Generate added messages and services
generate_messages(DEPENDENCIES std_msgs) ## Declare a catkin package
catkin_package(

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)

  • 1-2会生成两个可执行文件, talker 和 listener, 默认存储到 devel space 目录下,具体在~/catkin_ws/devel/lib/<package name> 中.
  • 3.如果在 *Groovy* 版本下,你可以使用下边的这个变量来添加对所有必须的文件依赖:
add_dependencies(talker ${catkin_EXPORTED_TARGETS})
  • 4.运行 catkin_make

4.测试结果:

5.问题:

1.当你在package.xml中,添加完run_depend后,编译出错,显示The manifest must not cotain the following  tags:run_depend。

原因:软件包格式分两种,第一种的四种依赖关系分别是:

<buildtool_depend>

<build_depend>

<run_depend>

<test_depend>

第二种的依赖关系变成:

<buildtool_depend>

<build_depend>

<build_export_depend>

<exec_depend>

<test_depend>

<doc_depend>

解决:当你run_depend出错时,有可能是你的软件包格式是第二种,所以要把run_depend改成exec_depend

2.invoking "make cmake_check_build_system" failed

仔细检查:

cmake_minimum_required(VERSION 2.8.)
project(beginner_tutorials) ## Find catkin and any catkin packages
find_package(catkin REQUIRED COMPONENTS roscpp rospy std_msgs genmsg) ## Declare ROS messages and services
add_message_files(DIRECTORY msg FILES Num.msg)
add_service_files(DIRECTORY srv FILES AddTwoInts.srv) ## Generate added messages and services
generate_messages(DEPENDENCIES std_msgs) ## Declare a catkin package
catkin_package()  #尤其要注意,里面为空否则报上面的错

Ros学习——C++发布器publisher和订阅器subscriber的更多相关文章

  1. Ros学习——Python发布器publisher和订阅器subscriber

    1.编写发布器 初始化 ROS 系统 在 ROS 网络内广播我们将要在 chatter 话题上发布 std_msgs/String 类型的消息 以每秒 10 次的频率在 chatter 上发布消息 在 ...

  2. ROS学习笔记10-写一个简单的订阅者和发布者(C++版本)

    本文档来源于:http://wiki.ros.org/ROS/Tutorials/WritingPublisherSubscriber%28c%2B%2B%29 写发布者节点如前所述,节点是连接到RO ...

  3. ROS学习(七)—— 理解ROS Topic

    一.准备工作 1.打开roscore roscore 2.turtlesim 打开一个turtulesim节点 rosrun turtlesim turtlesim_node 3.turtle key ...

  4. ROS学习(十二)—— 编写简单的消息发布器和订阅器(C++)

    一.创建发布器节点 1 节点功能: 不断的在ROS网络中广播消息 2 创建节点 (1)打开工作空间目录 cd ~/catkin_ws/src/beginner_tutorials 创建一个发布器节点( ...

  5. ROS 消息发布器和订阅器Publisher, Subscriber

    博客参考:https://www.2cto.com/kf/201705/639776.html 1.编写发布器节点节点(Node) 是指 ROS 网络中可执行文件.接下来,将会创建一个发布器节点(“t ...

  6. SLAM+语音机器人DIY系列:(二)ROS入门——5.编写简单的消息发布器和订阅器

    摘要 ROS机器人操作系统在机器人应用领域很流行,依托代码开源和模块间协作等特性,给机器人开发者带来了很大的方便.我们的机器人“miiboo”中的大部分程序也采用ROS进行开发,所以本文就重点对ROS ...

  7. ROS:消息发布器和订阅器(c++)

    学习资料主要源自http://wiki.ros.org/ROS/Tutorials/WritingPublisherSubscriber%28c%2B%2B%29 $ roscd beginner_t ...

  8. ROS笔记——创建简单的主题发布节点和主题订阅节点

    在安装好ROS后,接着学习如何创建节点和节点之间的通信方式,以一个简单的主题发布节点和主题订阅节点说明. 节点是连接ROS网络等可执行文件,是实现某些功能的软件包,也是一个主要计算执行的进程. 一.创 ...

  9. [转]RoboWare Studio的使用和发布器/订阅器的编写与测试

    原文地址:https://blog.csdn.net/han_l/article/details/77772352,转载主要方便随时查阅,如有版权要求,请及时联系. 开始ROS学习之前,先按照官网教程 ...

随机推荐

  1. web自动化:元素定位(二)

    一. 实例 如何定位到下图第二个"抢投标",有一种方法是利用xpath定位 //a[@href="/loan/loan_detail/Id/7190.html" ...

  2. Java面试题下

    这部分主要是开源Java EE框架方面的内容,包括hibernate.MyBatis.spring.Spring MVC等,由于Struts 2已经是明日黄花,在这里就不讨论Struts 2的面试题, ...

  3. swagger 在apache CXF 中的使用——JAX-RS Swagger2Feature

    The CXF Swagger2Feature allows you to generate Swagger 2.0 documents from JAX-RS service endpoints w ...

  4. Eclipse集成c与c++

    1.eclipse 开普勒版本 2.安装mingw 3.配置环境变量mingw的 path 加入;C:\MinGW\bin 4.eclipse 中的市场搜索 CDT

  5. python reload(sys)找不到,name 'reload' is not defined

    在操作数据库的时候遇到这个问题,为什么会出现这种原因?查询如下: python在安装时,默认的编码是ascii,当程序中出现非ascii编码时,python的处理常常会报这样的错UnicodeDeco ...

  6. Chrome MarkDown Preview Plus

    /************************************************************************** * Chrome MarkDown Previe ...

  7. 普通方法实现——远程方法调用RMI代码演示

    1.spring_RMI01_server服务端 package com.wisezone.service; import java.rmi.Remote; import java.rmi.Remot ...

  8. nodejs 不同请求获取前端传的参数

    get方法 参数在req.query中获取 router.get('/', function(req, res, next) { console.log("reqquery:",r ...

  9. xftp连接不上阿里云服务器

    打开xftp默认是使用FTP协议,要连接到云服务器,需要将协议改为SFTP 连接成功

  10. (转)通过WMI获取网卡MAC地址、硬盘序列号、主板序列号、CPU ID、BIOS序列号

    最近由于项目的需要,需要在程序中获取机器的硬盘序列号和MAC地址等信息,在C#下,可以很容易的获得这些信息,但是在C++程序中感觉比较麻烦.经过百度,发现很多大虾都是通过WMI来获取这些硬件信息的,网 ...