Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Boost does not seem necessary in this case. You can simply declare theta1f, theta2f, and theta3f as properties of your class listener. Since you create a Listener object in main, you would then have access to its properties. Basically, whenever you have a callback function for messages, you will need to use a class to utilize the data from that callback somewhere else. Like this:

class Listener 
{
  public:
    double theta1f;
    double theta2f;
    double theta3f;

    void callback(const std_msgs::Float32MultiArray::ConstPtr& msg);
};

void Listener::callback(const std_msgs::Float32MultiArray::ConstPtr& msg) 
{
    theta1f = msg->data[0];
    theta2f = msg->data[1];
    theta3f = msg->data[2];
}

int main(int argc, char **argv) 
{
    ros::init(argc, argv, "node_joint");
    ros::NodeHandle nh;
    ros::Rate loop_rate(30); 
    Listener listener;
    ros::Subscriber sub = nh.subscribe<std_msgs::float32multiarray>("topic_subscribed", 1, &Listener::callback, &listener);
    while (ros::ok()) 
    {
        ROS_INFO("This is theta1f: %.2f", listener.theta1f);
        ROS_INFO("This is theta2f: %.2f", listener.theta2f);
        ROS_INFO("This is theta2f: %.2f", listener.theta2f);
    }
    loop_rate.sleep();
    ros::spin();
    return 0;
}

Also, in general it is discouraged to use global variables unless absolutely necessary.

Boost does not seem necessary in this case. You can simply declare theta1f, theta2f, and theta3f as properties of your class listener. Since you create a Listener object in main, you would then have access to its properties. Basically, whenever you have a callback function for messages, you will need to use a class to utilize the data from that callback somewhere else. Like this:

class Listener 
{
  public:
    double theta1f;
    double theta2f;
    double theta3f;

    void callback(const std_msgs::Float32MultiArray::ConstPtr& msg);
};

void Listener::callback(const std_msgs::Float32MultiArray::ConstPtr& msg) 
{
    theta1f = msg->data[0];
    theta2f = msg->data[1];
    theta3f = msg->data[2];
}

int main(int argc, char **argv) 
{
    ros::init(argc, argv, "node_joint");
    ros::NodeHandle nh;
    ros::Rate loop_rate(30); 
    Listener listener;
    ros::Subscriber sub = nh.subscribe<std_msgs::float32multiarray>("topic_subscribed", 1, &Listener::callback, &listener);
    while (ros::ok()) 
    {
        ros::spinOnce();
        ROS_INFO("This is theta1f: %.2f", listener.theta1f);
        ROS_INFO("This is theta2f: %.2f", listener.theta2f);
        ROS_INFO("This is theta2f: %.2f", listener.theta2f);
        loop_rate.sleep();
    }
    loop_rate.sleep();
    ros::spin();
     return 0;
}

Also, in general it is discouraged to use global variables unless absolutely necessary.