ros中c++publihser创建流程

Publisher创建流程

1. 初始化ROS,创建节点

ros::init(argc, argv, nodeName);
ros::NodeHandle node;

2. 通过Node 创建发布者

const ros::Publisher &publisher = node.advertise<std_msgs::String>(topicName, 1000);

:::tip

第一个参数为topic名称

第二个参数为tipic中消息队列最多的数量。

:::

3. 定期发布消息

int index = 0;
ros::Rate rate(1);
while (ros::ok()) {
    std_msgs::String msg;
    msg.data = "hello pub " + to_string(index);
   
    publisher.publish(msg);
    
    cout << msg.data << endl;
    
    rate.sleep();
    index++;
} 

完整的示例代码

#include "ros/ros.h"
#include <iostream>
#include "std_msgs/String.h"

using namespace std;

int main(int argc, char **argv) {

    string nodeName = "cpppublisher";
    string topicName = "cpptopic";

    //初始化ros节点
    ros::init(argc, argv, nodeName);
    ros::NodeHandle node;

    //通过节点创建publisher
    const ros::Publisher &publisher = node.advertise<std_msgs::String>(topicName, 1000);

    //按照一定周期,发布消息
    int index = 0;
    ros::Rate rate(1);
    while (ros::ok()) {
        std_msgs::String msg;

        msg.data = "hello pub " + to_string(index);
        publisher.publish(msg);

        cout << msg.data << endl;

        rate.sleep();
        index++;
    }
    return 0;
}

调试发布者

调试Publisher主要是查看是否有发送数据,也就是提供一个订阅的调试工具。ROS提供了命令行工具和图形化工具进行调试。

1. 通过rostopic工具进行调试

查看所有的主题

rostopic list

打印主题所发布的信息

rostopic echo cpptopic

2. 通过rqt_topic工具进行调试

通过命令启动rqt_topic工具

rosrun rqt_topic rqt_topic

选中要调试的主题

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容