我正在做一个关于ROS的程序,其中发布者是订阅者的回调函数,并且一切顺利,除了我看不到数据打印位置的东西。
我写的代码如下所示:
#include <ros/ros.h>
#include <std_msgs/Int16.h>
class pubsub
{
private:
ros::NodeHandle nh;
ros::Publisher pub;
ros::Subscriber sub;
public:
void callback(const std_msgs::Int16::ConstPtr& msg)
{
ROS_INFO("I heard this data: [%d]", msg->data);
std_msgs::Int16 msg2;
msg2.data = msg->data;
ROS_INFO_STREAM(" I got some data");
pub.publish(msg2);
}
pubsub()
{
pub = nh.advertise<std_msgs::Int16>("just",100);
sub = nh.subscribe<std_msgs::Int16>("just",100,&pubsub::callback,this);
}
};
int main(int argc, char **argv){
ros::init(argc,argv,"node");
pubsub ps;
ros::spin();
return 0;
}
程序正在正确编译。执行时,仅等待数据并且不向终端提供任何输出。
命令 rostopic echo / just 即使在运行代码后输入整数也没有显示任何内容。
我哪里出错?
答案 0 :(得分:2)
回调,因为发布者在回调中。 事实上,你不会发布任何东西。请从main或构造函数发布初始消息,然后您将获得您期望的消息循环。
答案 1 :(得分:2)
就像在nayab的回答中已经描述过的那样,如果收到消息,则会发布消息。由于未发送此主题的消息,因此您永远不会发送消息。您需要在其他地方发布消息以接收它。因此,只需向pub
课程添加pubsub
等新方法即可。在main
循环内部,例如ros::rate
,频率为10 Hz。别忘了添加ros::spinOnce()
以允许回调处理。以下是改进的代码:
#include <ros/ros.h>
#include <std_msgs/Int16.h>
class pubsub
{
private:
ros::NodeHandle nh;
ros::Publisher pub;
ros::Subscriber sub;
public:
void callback(const std_msgs::Int16::ConstPtr& msg)
{
ROS_INFO("I heard this data: [%d]", msg->data);
}
void pub(int number)
{
std_msgs::Int16 msg;
msg.data = number;
ROS_INFO_STREAM("Publishing data");
pub.publish(msg);
}
pubsub()
{
pub = nh.advertise<std_msgs::Int16>("just",100);
sub = nh.subscribe<std_msgs::Int16>("just",100,&pubsub::callback,this);
}
};
int main(int argc, char **argv)
{
ros::init(argc,argv,"node");
pubsub ps;
ros::Rate r(10);
int number = 0;
while (ros::ok())
{
ps.pub(number++);
ros::spinOnce();
r.sleep();
}
return 0;
}
答案 2 :(得分:0)
#include <ros/ros.h>
#include <std_msgs/Int16.h>
class pubsub
{
private:
ros::NodeHandle nh;
ros::Publisher pub;
ros::Subscriber sub;
public:
void callback(const std_msgs::Int16::ConstPtr& msg)
{
ROS_INFO("I heard this data: [%d]", msg->data);
}
void pub(int number)
{
std_msgs::Int16 msg;
msg.data = number;
ROS_INFO_STREAM("Publishing data");
pub.publish(msg);
}
pubsub()
{
pub = nh.advertise<std_msgs::Int16>("just",100);
sub = nh.subscribe<std_msgs::Int16>("just",100,&pubsub::callback,this);
}
};
int main(int argc, char **argv)
{
ros::init(argc,argv,"node");
pubsub ps;
ros::Rate r(10);
int number = 0;
while (ros::ok())
{
ps.pub(number++);
ros::spinOnce();
r.sleep();
}
return 0;`ahah sala...`enter code here`
}