首先,我们必须知道一个东西,简单的说那就是
ros::spin(); //让ros一直调用回调函数,ros::spin以下的代码无效
ros::spinOnce(); //让ros调用回调函数的同时还可以继续执行以下的代码
所以在这里,我们就必须使用ros::spinOnce()来调用接收消息的回调函数才行。
这里我给大家看一个关于监听ros上的find_object_2d的节点的代码:
#include "ros/ros.h"
#include "std_msgs/String.h"
#include "std_msgs/Bool.h"
#include <find_object_2d/ObjectsStamped.h>
#include <message_filters/subscriber.h>
#include <seat/identify.h> //这个是我的包msg文件
int n = 0;
int acount = 0;
int bcount = 0;
int ccount = 0;
seat::identify identifymsg;
void object_detectedCallback(const std_msgs::Float32MultiArrayConstPtr &msg)
{
......
......
//此处代码忽略
}
int main(int argc,char **argv)
{
ros::init(argc,argv,"seat_detected");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("objects",1,object_detectedCallback);
message_filters::Subscriber<find_object_2d::ObjectsStamped> objectsSub;
ros::Publisher identify_pub = n.advertise<seat::identify>("helloworld",1000);//锁定helloworld这个topic准备发布消息
objectsSub.subscribe(n, "objectsStamped", 1);
ros::Rate loop_rate(10);
while(ros::ok())
{
identify_pub.publish(identifymsg);//向刚才锁定的helloworld这个topic发布消息
ros::spinOnce();//这句就是同时发布节点和订阅节点的关键了
loop_rate.sleep();
}
return 0;
}
这里说一下,
发布节点和订阅节点的msg文件一定要一样哦,但是可以是各自包内的msg文件。
即假设现在有两个包
一个包叫A,一个包叫B
A中的msg文件夹有个hello.msg,里面有
string a
bool b
B中的msg文件夹也有个hello.msg,里面有
string a
bool b
那么这两个包之间并不需要建立什么依赖关系哦,可以直接向对方接受信息和发布信息。