ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

Use subscriber callback to modify class attributes

asked 2023-07-30 18:10:56 -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{
       geometry_msgs::Vector3 position;
       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);
  std::cout << "connection end" << std::endl;
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 close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2023-07-31 09:13:42 -0500

bluegiraffe-sc gravatar image


The code you posted should print 0 one time (right before calling ros::spin()). The main is then "stuck" (find a better description of how spin works in the docs) at the spin line, your callback is executed on message arrival and the value is correctly stored in the class attribute. This is confirmed by the fact that the last print returns the value you are expecting.

What behavior did you expect instead?

edit flag offensive delete link more


Hi, so this is the problem with print statement right? If so, should I put subscriber in the class constructor instead? Is there any way I could check the class attributes with continuous changes on message arrival? Since I also try to put to publisher in the spin loop and when I echo it, the values are still all zeros.

Junjie_Gao gravatar image Junjie_Gao  ( 2023-07-31 13:21:14 -0500 )edit

Can you edit the question adding this alternative solution?

bluegiraffe-sc gravatar image bluegiraffe-sc  ( 2023-08-01 02:48:31 -0500 )edit

Question Tools


Asked: 2023-07-30 18:10:56 -0500

Seen: 78 times

Last updated: Jul 31 '23