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

Revision history [back]

click to hide/show revision 1
initial version

What you can do is create a global variable to store the data in. For example

#include "ros/ros.h"
#include "std_msgs/String.h"

std_msgs::String str_var; // global variable

void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
  str_var.data = msg->data; // save the data in the callback
  ROS_INFO("I heard: [%s]", msg->data.c_str());
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "listener");

  ros::NodeHandle n;

  ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);

  //here I want access to the message from chatterCallback

  ros::spin();

  return 0;
}

Ideally, you'd create a class for this and save the data to a class variable instead of a global one.

Note that I haven't compiled the code so there may be some errors, but the main idea is there.