0
$\begingroup$

Rosanswers logo

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]",msg.data) ;
    //  msg.data = addition(msg.data, 5);
    
     ros::spin();
     return 0;    
    }
    

Is there a better way to do this ?


Originally posted by aks on ROS Answers with karma: 667 on 2018-04-20

Post score: 0

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

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

float sum = msg->data + 5;
ROS_INFO("Updated Sum: [%f]", sum);

Originally posted by Thomas D with karma: 4347 on 2018-04-20

This answer was ACCEPTED on the original site

Post score: 2


Original comments

Comment by aks on 2018-04-20:
Worked ! Thanks. But is it a good practise to implement own functions in the callback funciton ?

Comment by Thomas D on 2018-04-20:
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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.