Ask Your Question
0

subscribe and publish - doesn't work properly

asked 2013-09-10 11:59:05 -0500

Ros451 gravatar image

updated 2013-09-10 12:00:02 -0500

Hi,

I've written a small program which subscribes the topic "joy" from the joy_node (joystick) then it should process the date and publish it on a new topic "sub_dynamixel". Well but it doesn't, the code compiles but no published data available.

#include <sensor_msgs/Joy.h>
#include "ros/ros.h"
#include "std_msgs/String.h"
#include "message/message_back.h"

#include <sstream>

#include <stdio.h>
#include <iostream>




void chatterCallback(const sensor_msgs::Joy::ConstPtr &joy)
{ 
  float position;
  int position_move;  

  ros::NodeHandle r;
  ros::Publisher chatter_pub = r.advertise<message::message_back>("sub_dynamixel", 1000);
  message::message_back msg; 
  position = joy->axes[0];


 if(position>0)
 {
 position_move=position*512;
 position_move+=512;
 }
 else if(position<0)
 position_move=512-(position*(-1)*512);
 else if(position==0)
 position_move=512;


 msg.position_move = position_move;      
 chatter_pub.publish(msg); 
}




int main(int argc, char **argv)
{
ros::init(argc, argv, "dynamixel_teleoperation");
ros::NodeHandle n;

ros::Subscriber sub = n.subscribe("joy", 1000, chatterCallback);
ros::spin();


return 0;
}
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2013-09-10 12:17:26 -0500

Bill Smart gravatar image

chatter_pub is being destroyed at the end of the function, before the message gets out. You should always create publishers at a more global scope, either as a global variable, or by wrapping your implementation up in a class, and having the chatter_pub as a member variable.

Similar problem to this question, although it was about a subscriber, not a publisher.

edit flag offensive delete link more

Comments

Thank you!

Ros451 gravatar image Ros451  ( 2013-09-10 12:39:16 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2013-09-10 11:59:05 -0500

Seen: 166 times

Last updated: Sep 10 '13