Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Your code is undefined behaviour:

  geometry_msgs::PoseStamped msg;

msg contains random values (depending on whatever was previously in ram)

  msg.pose.position.x += 2;

msg.pose.position.x is now random+2 !! If you are lucky, and your msg always gets instantiated somewhere where previously a zero was, your msg.pose.position.x is at least always 2 (and not random+2). But it does not increment (I guess that'd be your intention).

If you wish to do that define msg in global space, initialize at beginning of main and than increment in your loop like this:

#include <ros/ros.h>
#include "geometry_msgs/PoseStamped.h"
#include "geometry_msgs/Pose.h"
// publisher handles
ros::Publisher goal_pub;
geometry_msgs::PoseStamped msg;

void publish_goal()
{ 
  msg.pose.position.x += 2; 

  goal_pub.publish(msg);
}

int main(int argc, char** argv) 
{

  msg.header.frame_id = "base_link";
  msg.pose.position.x = 2; 
  msg.pose.position.y = 20; 
  msg.pose.position.z = 50;   
  msg.pose.orientation.w = 0; 
  msg.pose.orientation.x = -2.0; 
  msg.pose.orientation.y = 0; 
  msg.pose.orientation.z = 0;  

    ros::init(argc, argv, "move_sphere");
    ros::NodeHandle nh;
    ros::Rate loop_rate(100);
    goal_pub = nh.advertise<geometry_msgs::PoseStamped>("pose", 1);
    while (ros::ok()) 
    {
      publish_goal();
      ros::spinOnce();
      loop_rate.sleep();
    }
}

Your code is undefined behaviour:always publishes the same pos:

  geometry_msgs::PoseStamped msg;

msg contains random values (depending on whatever was previously in ram)default values( all zeros, false for bool )

  msg.pose.position.x += 2;

msg.pose.position.x is now random+2 !! If you are lucky, and your msg always gets instantiated somewhere where previously a zero was, your msg.pose.position.x is at least always 2 (and not random+2). But it (always) 0+2, i. e. 2.!! It does not increment (I guess that'd be your intention).

If you wish to do that define msg in global space, initialize at beginning of main and than increment in your loop like this:

#include <ros/ros.h>
#include "geometry_msgs/PoseStamped.h"
#include "geometry_msgs/Pose.h"
// publisher handles
ros::Publisher goal_pub;
geometry_msgs::PoseStamped msg;

void publish_goal()
{ 
  msg.pose.position.x += 2; 

  goal_pub.publish(msg);
}

int main(int argc, char** argv) 
{

  msg.header.frame_id = "base_link";
  msg.pose.position.x = 2; 
  msg.pose.position.y = 20; 
  msg.pose.position.z = 50;   
  msg.pose.orientation.w = 0; 
  msg.pose.orientation.x = -2.0; 
  msg.pose.orientation.y = 0; 
  msg.pose.orientation.z = 0;  

    ros::init(argc, argv, "move_sphere");
    ros::NodeHandle nh;
    ros::Rate loop_rate(100);
    goal_pub = nh.advertise<geometry_msgs::PoseStamped>("pose", 1);
    while (ros::ok()) 
    {
      publish_goal();
      ros::spinOnce();
      loop_rate.sleep();
    }
}