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

11 篇文章 19 订阅

ROS Noetic入门笔记(一)在ubuntu20.04中安装ROS Noetic并简单测试
ROS Noetic入门笔记(二)ROS Noetic创建工作空间和功能包
ROS Noetic入门笔记(三)ROS Noetic中的常用命令及工具
ROS Noetic入门笔记(四)使用rqt_console和roslaunch
ROS Noetic入门笔记(五)创建ROS话题消息(msg)和服务数据(srv
ROS Noetic入门笔记(六)使用C++编写简单的Publisher与Suscriber
ROS Noetic入门笔记(七)使用Python编写简单的Publisher与Suscriber
ROS Noetic入门笔记(八)运行Publisher与Suscriber
ROS Noetic入门笔记(九)使用C++编写简单的Server与Client
ROS Noetic入门笔记(十)使用Python编写简单的Server与Client
ROS Noetic入门笔记(十一)使用rosbag实现数据记录与回放

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)
下一篇:ROS Noetic入门笔记(七)使用Python编写简单的Publisher与Suscriber

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值