ros subscribe callback is not working

asked 2021-08-11 03:31:46 -0500

lleejk96 gravatar image

updated 2021-08-11 10:19:56 -0500

tryan gravatar image

Hey all, I'm trying to get a simple subscriber in roscpp working. I have my node subscribe to a topic with a callback called global_position_cb. The callback bring current gps postion that it was called. However, when I subscribe to the topic, the callback function does not do anything. I checked rostopic list and see the message getting published so why wouldn't my callback function working ? Below is the main part of my code, thank you so much!

cpp code:

#include <ros/ros.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/Twist.h>
#include <mavros_msgs/CommandBool.h>
#include <mavros_msgs/CommandTOL.h>
#include <mavros_msgs/SetMode.h>
#include <mavros_msgs/State.h>
#include <sensor_msgs/Range.h>
#include <sensor_msgs/NavSatFix.h>
#include <std_srvs/Empty.h>
#include <std_msgs/Empty.h>
#include <mavros_msgs/WaypointClear.h>
#include <mavros_msgs/WaypointPush.h>
#include <mavros_msgs/CommandHome.h>
#include <mavros_msgs/GlobalPositionTarget.h>
#include "darknet_ros_msgs/BoundingBoxes.h"
#include "darknet_ros_msgs/BoundingBox.h"
#include "darknet_ros_msgs/CheckForObjectsAction.h"

sensor_msgs::NavSatFix global_position;
bool gps_position_received = false;

void globalPosition_cb(const sensor_msgs::NavSatFix::ConstPtr& msg) {
    global_position = msg;
    gps_position_received = true;

int main(int argc, char **argv)
    ros::init(argc, argv, "offb_node");
    ros::NodeHandle nh;
    ros::NodeHandle waypoint_node;

    ros::Subscriber global_pos_sub = nh.subscribe<sensor_msgs::NavSatFix>
            ("mavros/global_position/global", 10, globalPosition_cb);

    // wait for FCU connection
    while(ros::ok() && !gps_position_received){
    ROS_INFO("Current GPS position sent: [%f %f %f]\n", global_position.latitude, global_position.longitude, global_position.altitude); 

    return 0;
edit retag flag offensive close merge delete



rostopic list won't tell you if a message is published, just that the topic is registered. Does rostopic echo /mavros/global_position/global print the expected message(s)? Also, does rosrun rqt_graph rqt_graph show that your subscriber is connected to the publisher via the correct topic?

tryan gravatar image tryan  ( 2021-08-11 10:24:16 -0500 )edit

This might be a silly question, but are you sure that your node is running? You can run a rosnode list to verify this. And if it is running, can you also run rosnode info <name> and verify that all inputs and outputs are registered properly?

Akhil Kurup gravatar image Akhil Kurup  ( 2021-08-11 12:05:16 -0500 )edit

You call rate.sleep(), but where do you initialise rate?

ijnek gravatar image ijnek  ( 2021-08-11 17:00:39 -0500 )edit