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

Revision history [back]

You instantiate a new publisher everytime your callback posCallback is called. There is a time gap between instantiating a publisher till a publish call to it actually publishes, as things are threaded behind the scenes. So what happens everytime your posCallback is called:

  • Publisher pub_twist gets instantiated
  • publish() is called on the instantiated pub_twist publisher at the end of your callback. The publisher is not set up correctly yet at that point in time, so nothing actually gets published.
  • pub_twist goes out of scope and it's destructor is called as it is a local variable of your posCallback.

What you can do is make the Publisher a global variable and use it. Minimal example:

#include <ros/ros.h>
[...]

ros::Publisher pub_twist;

[...]
    void posCallback(const geometry_msgs::Point& msg)
    {
        [...]
        pub_twist.publish(twist_msg);
    }

int main(int argc, char **argv)
{
    [...] 

    pub_twist= nh.advertise<geometry_msgs::Twist>("/cmd_vel", 1);

    ros::Subscriber sub = nh.subscribe("color_position", 100, posCallback);
    ros::spin();
}

You instantiate a new publisher everytime your callback posCallback is called. There is a time gap between instantiating a publisher till a publish call to it actually publishes, as things are threaded behind the scenes. So what happens everytime your posCallback is called:

  • Publisher pub_twist gets instantiated
  • publish() is called on the instantiated pub_twist publisher at the end of your callback. The publisher is not set up correctly yet at that point in time, so nothing actually gets published.
  • pub_twist goes out of scope and it's destructor is called as it is a local variable of your posCallback.

What you can do is make the Publisher a global variable and use it. Minimal example:

#include <ros/ros.h>
[...]

ros::Publisher pub_twist;

[...]
    void posCallback(const geometry_msgs::Point& msg)
    {
        [...]
        pub_twist.publish(twist_msg);
    }

int main(int argc, char **argv)
{
    [...] 

    pub_twist= nh.advertise<geometry_msgs::Twist>("/cmd_vel", 1);

    ros::Subscriber sub = nh.subscribe("color_position", 100, posCallback);
    ros::spin();
}