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

Using a function in callback ?

asked 2018-04-20 04:48:41 -0500

aks gravatar image

updated 2018-04-20 05:41:03 -0500

NEngelhard gravatar image

I am trying to understand the ROS concepts and the next step would be to try and integrate ROS with an own tool. For this, I am trying to write a simple function addition and analyze the effects.

I have a talker which increments the value of a. Now I have a listener, which listens to this incremented value of a, everytime callback function is called and then use a function, lets say a + b, where b would be constant lets say 5. So everytime this a+b is called in the listener, it should publish it on the console by saying Updated Sum : a (Incremented in every step) + 5 = x (also updated accordingly). The console could be published either in the listener or in the talker.

  1. At first I thought of calling the additon function in the main() of the listener but this doesnt work as ithe variable msg (getting updated through callback is not in the scope of main.
  2. Then I thought of directly calling addition(a,b) in the callback but somehow i cannot update the function as msg is a constant pointer and i cannot change its value. Here is the code for the listener :

     void chatterCallback(const std_msgs::Float32::ConstPtr& msg)   {
     msg->data =  msg->data + 5 ;
     ROS_INFO("Updated Sum: [%f]",msg->data) ;    
     int main(int argc, char **argv)    {
     ros::init(argc, argv, "listener");
     ros::NodeHandle n;
     ros::Subscriber sub = n.subscribe("sum", 1000, chatterCallback);
    // ROS_INFO("I heard: [%f]", ;
    // = addition(, 5);
     return 0;    

Is there a better way to do this ?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2018-04-20 07:53:49 -0500

Thomas D gravatar image

You need a local variable in your callback. Change it to:

float sum = msg->data + 5;
ROS_INFO("Updated Sum: [%f]", sum);
edit flag offensive delete link more


Worked ! Thanks. But is it a good practise to implement own functions in the callback funciton ?

aks gravatar image aks  ( 2018-04-20 09:39:19 -0500 )edit

You _have to_ implement your own details in the callback functions. Best practices for how to organize the callback functions and the level of abstraction for how the data is handled varies based on what the node is trying to accomplish. What you have is fine for a simple node.

Thomas D gravatar image Thomas D  ( 2018-04-20 12:07:47 -0500 )edit

Question Tools

1 follower


Asked: 2018-04-20 04:48:41 -0500

Seen: 314 times

Last updated: Apr 20 '18