Ask Your Question
0

Subscriber function not being called?

asked 2015-11-01 06:14:25 -0500

Ameer Hamza Khan gravatar image

updated 2015-11-01 06:16:08 -0500

Here is my code

#include <iostream>
#include "ros/ros.h"
#include "std_msgs/Empty.h"
#include "std_msgs/Int32.h"
#include "std_msgs/Float32.h"
#include "geometry_msgs/Twist.h"
#include "ardrone_autonomy/Navdata.h"

#include "std_msgs/String.h"
#include <sstream>

int     state = 1, y = 1;//, battery, rotX, rotY, rotZ;

void callBack(const ardrone_autonomy::Navdata::ConstPtr& data) {
    state = data->state;
    y = 2;
}

int main(int argc, char **argv)
{
ros::init(argc, argv, "ardrone_fly");

ros::NodeHandle ardrone;

ros::NodeHandle output("output");
ros::Publisher pub_t = ardrone.advertise<std_msgs::Empty>("/ardrone/takeoff",1000);
ros::Publisher pub_l = ardrone.advertise<std_msgs::Empty>("/ardrone/land",1000);
ros::Publisher pub_f = ardrone.advertise<geometry_msgs::Twist>("/cmd_vel",1000);
ros::Publisher pub_s = ardrone.advertise<std_msgs::String>("state",1000);

ros::Subscriber sub = ardrone.subscribe<ardrone_autonomy::Navdata>("/ardrone/navdata",1,callBack);

std_msgs::Empty emp;
int x;

ros::Rate loop_rate(50);

std::stringstream ss;
std_msgs::String state_s;

while(ros::ok()) {
    //ROS_INFO("state: %d  ",state);

    ss << "State is: " << state << " y: " << y;// << " Battery is: " << battery;
    state_s.data = ss.str();

    pub_s.publish(state_s);

    if(state==2) {
        pub_t.publish(emp);
    }
    else
        pub_f.publish(msg);

    loop_rate.sleep();
}

pub_l.publish(emp);

ros::spin();

return 0;
 }

When i run this code, the callBack function is not being called, although rostopic echo /ardrone/navdata is showing that data is received. What is going wrong?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2015-11-01 09:36:55 -0500

For the callback to be called, ros::spin() or ros::spinOnce() have to be called (for the simple single threaded case). In your code, this is missing from your while(ros::ok()) loop. The spin() call only gets called when you abort your program (as soon as ros::ok() returns false).

See Callbacks and Spinning. You're basically looking at the second option and should call execute ros::spinOnce inside your loop, for instance like this:

while(ros::ok()) {
    ros::spinOnce();

    //ROS_INFO("state: %d  ",state);

    ss << "State is: " << state << " y: " << y;// << " Battery is: " << battery;
    state_s.data = ss.str();

    pub_s.publish(state_s);

    if(state==2) {
        pub_t.publish(emp);
    }
    else
        pub_f.publish(msg);

    loop_rate.sleep();
}
edit flag offensive delete link more

Your Answer

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

Add Answer

Question Tools

2 followers

Stats

Asked: 2015-11-01 06:14:25 -0500

Seen: 750 times

Last updated: Nov 01 '15