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

Revision history [back]

The code for the subscriber is not meaningful: you're just posting the callback, while the problem probably resides in the main loop.

For example while you clearly use ros.rate in the publisher, why would you use usleep in the subscriber? Use ros.rate there as well. And be sure to run the subscriber faster than the publisher, at least twice that.

That said it seems you're running both the publisher and the subscriber from the same process. That is bound to give you problems unless you interleave perfectly.

What this means is that whenever you ask ROS to do work for you (send, receive, set parameters, whatever), ROS will take an arbitrary amount of time to do the work, possibly requiring multiple calls to ros.spinOnce() to obtain the required results.

So in your case where you want to both send and receive from the same process, you better have the main loop run faster than the tasks subloops. This entails designing your code to publish at a sub-rate of the main loop.

For example you could run your main loop at 50Hz and publish at 5Hz by decimating with an if

int decimator = 0;
while(n.ok())
{
    if ((decimator % 10) == 0)
    {
        //do stuff like publishing
        decimator = 0;
    }
    decimator++;

    //rest of the main loop
}

This way you'd be sure to give roscomm enough time to process the various messages. Theoretically since you're using the same publisher to send more than one message in the same time-slice (you call ros.spinOnce() only once for every two messages) it is possible that only the last one is latched inside your process, thus your subscriber receives only one message because of the fact that you don't allow servicing to happen.

Always remember to run your servicing routines (ros.spinOnce() in this case) faster than the services using them.