Publish message to a topic from Callback function
Hi Guys,
This question had been already asked, however I am looking for ways without using C++ classes.
Below is my problem statement.
#include "ros/ros.h"
#include "std_msgs/String.h"
void chatter_callback(const std_msgs::String::ConstPtr& msg)
{
ROS_INFO("Received the message : [%s]", msg->data.c_str());
// Here I need to convert this message other datatypes and publish it to topic "X"
// Can we have while(ros::ok()) here in this callback function
while(ros::ok())
{
chatter_pub.publish(new_msg);
}
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "listener_v1");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("chatter", 1000, chatter_callback);
ros::Publisher chatter_pub = n.advertise<other data type>("chatter", 1000);
ros::Rate loop_rate(10);
ros::spin();
return 0;
}
Also please note that Publisher is defined in main and being used in callback function. I am afraid this is not the right way to use it.
Kindly let me know if the question is not clear and needs more information.
Updating the code :
#include "ros/ros.h"
#include "std_msgs/String.h"
void chatter_callback(const std_msgs::String::ConstPtr& msg)
{
ROS_INFO("Received the message : [%d]", msg->data.c_str());
// Convert the msg to the datatype we wanted to
chatter_pub.publish(new_msg);
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "listener_v1");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("chatter", 1000, chatter_callback);
ros::Publisher chatter_pub = n.advertise<other data type>("chatter", 1000);
ros::Rate loop_rate(10);
while(ros::ok()
{
ros::spinOnce();
}
return 0;
}
Thank you, KK