How to properly update class members with class callback function?

asked 2021-09-08 21:13:00 -0500

ModernNoob gravatar image

I am using the subscriber node to receive some information from a topic and saving it within a class member. This my is main main.cpp

int main(int argc, char **argv){
    ros::init(argc, argv, "navigation", ros::init_options::AnonymousName);
    ros::NodeHandle nh; 
    Localization gps(nh);
    ROS_INFO("Lat: %f Long: %f", gps.latitude, gps.longitude);
    ros::spin()
}

My header file:

class Localization{
public:
    double latitude, longitude;
    ros::NodeHandle nh;  
    ros::Subscriber sub = nh.subscribe("/mavros/global_position/global", 1, &Localization::receiver, this);

void Localization::receiver(const sensor_msgs::NavSatFixConstPtr& fix){
    // Checks if GPS is enable and usable
    if (fix->status.status == sensor_msgs::NavSatStatus::STATUS_NO_FIX) {
        ROS_INFO("No fix.");
        return;
    }

    // Stores the current latitude and longitude
    latitude = fix->latitude;
    longitude = fix->longitude;
    }
};

I ran the main.cpp and not only does it print once, it gives the wrong coordinates. When I put ROS_INFO("Lat: %f Long: %f", gps.latitude, gps.longitude); within the callback function, it actually give back the correct answer. I think the first time is that ros::spin() was not called yet so the information was not updated, but when it is called it, the std::cout code no longer is running and I can't simply put it inside a while(ros::ok()) either. So I figure that if I want to have another function that uses double latitude, longitude; continuously run throughout the entirely of the program, I will have to place it within the callback function for it to take any significant effect. Is there a different way to go about this?

edit retag flag offensive close merge delete

Comments

abhishek47 gravatar image abhishek47  ( 2021-09-08 23:44:30 -0500 )edit