ros callback 回调机制 & 订阅队列长度

实验程序:

talker.cc 

#include <std_msgs/Int32.h>
#include <ros/ros.h>

int main(int argc, char **argv) {
    ros::init(argc, argv, "talker");
    ros::NodeHandle nh;
    std_msgs::Int32 data;
    data.data = 0;
 
    ros::Publisher pub = nh.advertise<std_msgs::Int32>("alan_topic", 1);
    ros::Rate loop_rate(1.0); // 1hz
    while (ros::ok()) {
        data.data++;
        pub.publish(data);
        std::cout << std::setprecision(12) << "[" << ros::Time::now().toSec() << "] publish " << data.data << std::endl;
        loop_rate.sleep();
    }
    return 0;
}

listener.cc

#include <ros/ros.h>
#include <std_msgs/Int32.h>

void alan_callback(const std_msgs::Int32& data){
    std::cout << std::setprecision(12) << "[" << ros::Time::now().toSec() << "] process " << data.data << " short time" << std::endl;
    std::cout << std::setprecision(12) << "[" << ros::Time::now().toSec() << "] process " << data.data << " long time" << std::endl;
    return;
}

int main(int argc, char ** argv) {
    ros::init(argc, argv, "listener");
    ros::NodeHandle nh;
    ros::Subscriber sub = nh.subscribe("alan_topic", 1, alan_callback);
    ros::spin();
    return 0;
}

实时 


listener.cc

#include <unistd.h>
#include <ros/ros.h>
#include <std_msgs/Int32.h>

void alan_callback(const std_msgs::Int32& data){
    std::cout << std::setprecision(12) << "[" << ros::Time::now().toSec() << "] process " << data.data << " short time" << std::endl;
    std::cout << std::setprecision(12) << "[" << ros::Time::now().toSec() << "] process " << data.data << " long time" << std::endl;
    sleep(5); // 5秒
    return;
}

int main(int argc, char ** argv) {
    ros::init(argc, argv, "listener");
    ros::NodeHandle nh;
    ros::Subscriber sub = nh.subscribe("alan_topic", 1, alan_callback);
    ros::spin();
    return 0;
}

回调函数处理时间长导致数据丢失(队列长度为1ÿ

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值