use subscriber callback to modify class attribute [closed]

asked 2023-07-31 00:20:53 -0500

Junjie_Gao gravatar image

Hi, I am new to ROS, and I am encountering a weird issue currently. Any help would be greatly appreciate. I use a subscriber to receive message from mavros and hope to get values from subscriber callback that used to modify private class variables. Here is my code:

class Listener{
    private:
       geometry_msgs::Vector3 position;
    public:
       void Listen_From_MAVROS_Callback(const mavros_msgs::DRONESENSOR::ConstPtr& dronesensor);
       void Print_Variables();
}
void Listener::Listen_From_MAVROS_Callback(const mavros_msgs::DRONESENSOR::ConstPtr& dronesensor)
{
      position.x = (dronesensor -> position)[0];
 }
void Listener::Print_Variables() {
     std::cout << "x position: " << position.x << std::endl;
}
int main(int argc, char **argv){
    ros::init(argc, argv, "GeoCtrlListener");
   ros::NodeHandle n;
   Listener listener;
   ros::Subscriber Sub_From_Mavros = n.subscribe("/mavros/odroid/odroid_input", 1, 
   &Listener::Listen_From_MAVROS_Callback, &listener);
  listener.Print_Variables();
   ros::spin();
  std::cout << "connection end" << std::endl;
 listener.Print_Variables();
return 0
}

For the code above when I run it, the print statement before spin() all returns 0, meaning no attibutes is modified. However, when I press ctrl c and end the connection, the console returns the correct value. I am so confused whether my object listener is correctly mofidied or not. I need to store the data from callback function and makes some manipulation and then publish back to another topic. Ayn suggestions? Thank you so much

edit retag flag offensive reopen merge delete

Closed for the following reason duplicate question by Junjie_Gao
close date 2023-07-31 13:22:50.807267

Comments

This is a duplicate of your own question, please close this one.

bluegiraffe-sc gravatar image bluegiraffe-sc  ( 2023-07-31 09:16:14 -0500 )edit