IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> C++知识库 -> ROS Noetic入门笔记(六)使用C++编写简单的Publisher与Suscriber -> 正文阅读

[C++知识库]ROS Noetic入门笔记(六)使用C++编写简单的Publisher与Suscriber

1.创建Publisher

(1) 在功能包下创建src目录

  • 使用roscd跳转到beginner_tutorials功能包目录
$ roscd beginner_tutorials
  • 使用mkdir命令创建src目录
$ mkdir -p src

(2) 在src目录下创建talker.cpp 文件并粘贴以下代码

#include "ros/ros.h"
#include "std_msgs/String.h"

#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");

  /**
   * 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 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", 1000);

  ros::Rate loop_rate(10);

  /**
   * A count of how many messages we have sent. This is used to create
   * a unique string for each message.
   */
  int count = 0;
  while (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());

    /**
     * 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);

    ros::spinOnce();

    loop_rate.sleep();
    ++count;
  }


  return 0;
}

创建talker.cpp
talker.cpp

(3) talker.cpp代码解释

#include "ros/ros.h"

ros/ros.h 包含了大部分ROS中通用的头文件

#include "std_msgs/String.h"

这个包含了消息类型的头文件,该头文件根据String.msg的消息结构定义自动生成

ros::init(argc, argv, "talker");

初始化ROS节点,这允许ROS进行命名重映射,节点名称在运行的ROS中必须是唯一的

ros::NodeHandle n;

创建节点句柄,开始创建的节点句柄会进行节点初始化,而最后一个销毁的将清除节点正在使用的所有资源

ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);

告诉ROS Master我们将会发布以chatter为话题的Sring类型消息,第二个参数表示消息发布队列的大小,当消息发布过快时,ROS会自动删除队列中最早入队的消息,保持不超过1000条的缓冲

ros::Rate loop_rate(10);

设置调用Rate::sleep()时的等待时间,调用Rate::sleep()时ROS节点会根据此处设置的频率休眠相应的时间,这里我们设置为10Hz,即延时100ms

int count = 0;
  while (ros::ok())
  {

进入节点主循环,正常情况下一直在循环中运行,发生异常ros::ok()就会返回false并跳出循环
异常情况主要包括以下4种:

  • 收到 SIGINT信号 (Ctrl-C)
  • 被另外一个同名节点踢掉线
  • 程序的其他部分调用了ros::shutdown()
  • 所有ros::NodeHandles 句柄被销毁

一旦ros::ok()返回 false,所有 ROS 调用都会失败

std_msgs::String msg;

std::stringstream ss;
ss << "hello world " << count;
msg.data = ss.str();

初始化即将发布的消息,ROS中定义了很多通用的消息类型,这里我们使用了最为简单的String消息类型,它只有一个成员“data”

chatter_pub.publish(msg);

发布消息给所有订阅该话题的节点

ROS_INFO("%s", msg.data.c_str());

ROS_INFO类似于printf/cout,用来打印日志信息

ros::spinOnce();

ros::spinOnce()用来处理节点订阅话题的所有回调函数,在这里并不需要,因为这个程序我们没有订阅任何消息

loop_rate.sleep();

现在按之前设置的10Hz休眠时间休眠100ms然后才进行下一次的循环

流程简要梳理如下:

  • 初始化ROS节点
  • 向ROS Master注册节点信息,包括发布的话题名和话题中的消息类型
  • 按照设定的频率循环发布消息

2.创建Suscriber

(1) 在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)
{
  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", 1000, chatterCallback);

  /**
   * 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();

  return 0;
}

(3) listener.cpp代码解释

这里我们省略上边在talker.cpp中已经讲过的部分

void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
  ROS_INFO("I heard: [%s]", msg->data.c_str());
}

有消息到达时会调用的回调函数

ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);

订阅消息,有新消息到达时,ROS会调用chatterCallback回调函数,第一个参数是消息话题,第二个参数是接收消息队列的大小,当新消息到达时如果超出1000条就会自动丢掉最早的数据

ros::spin();

节点进入循环状态,当有消息到达时,会尽快调用回调函数完成处理,ros::spin()在ros::ok()返回false时退出

流程简要梳理如下:

  • 初始化ROS节点
  • 订阅需要的话题
  • 循环等待消息到达,有新消息到达时进入回调函数进行处理
  • 在回调函数中完成消息的处理

3.编译功能包

编辑 CMakeLists.txt 文件

cmake_minimum_required(VERSION 2.8.3)
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(FILES Num.msg)
add_service_files(FILES AddTwoInts.srv)

## Generate added messages and services
generate_messages(DEPENDENCIES std_msgs)

## Declare a catkin package
catkin_package()

## Build talker and listener
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)

修改完成后,回到工作空间的根目录下开始编译

$ cd ~/catkin_ws
$ catkin_make

编译生成的2个可执行文件如下,默认在~/catkin_ws/devel/lib/beginner_tutorials文件夹下
~/catkin_ws/devel/lib/
上一篇:ROS Noetic入门笔记(五)创建ROS话题消息(msg)和服务数据(srv)

  C++知识库 最新文章
【C++】友元、嵌套类、异常、RTTI、类型转换
通讯录的思路与实现(C语言)
C++PrimerPlus 第七章 函数-C++的编程模块(
Problem C: 算法9-9~9-12:平衡二叉树的基本
MSVC C++ UTF-8编程
C++进阶 多态原理
简单string类c++实现
我的年度总结
【C语言】以深厚地基筑伟岸高楼-基础篇(六
c语言常见错误合集
上一篇文章      下一篇文章      查看所有文章
加:2021-08-09 10:03:37  更:2021-08-09 10:05:39 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/9 18:06:43-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码