1. 研究背景
本小节针对在ROS节点中需要订阅两个及两个以上的话题时,需要保持对这两个话题数据的同步,且需要同时接收数据一起处理然后当做参数传入到另一个函数中。 研究背景:realsenseT265 和 realsense D435 都有IMU数据,但是这两个传感器都将imu的数据拆开进行发布了,区分了线加速度和角加速,而在有一些场合我们需要合并使用。
2. 详细代码如下:
#include <message_filters/subscriber.h>
#include <message_filters/synchronizer.h>
#include <message_filters/sync_policies/approximate_time.h>
#include <boost/thread/thread.hpp>
using namespace message_filters
;
void imu_callback(const sensor_msgs
::ImuConstPtr
&imu_msg_accel
, const sensor_msgs
::ImuConstPtr
&imu_msg_gyro
)
{
double t
= imu_msg_accel
->header
.stamp
.toSec();
double dx
= imu_msg_accel
->linear_acceleration
.x
;
double dy
= imu_msg_accel
->linear_acceleration
.y
;
double dz
= imu_msg_accel
->linear_acceleration
.z
;
double rx
= imu_msg_gyro
->angular_velocity
.x
;
double ry
= imu_msg_gyro
->angular_velocity
.y
;
double rz
= imu_msg_gyro
->angular_velocity
.z
;
Vector3d
gyr(rx
, ry
, rz
);
Vector3d
acc(dx
, dy
, dz
);
}
int main(int argc
, char** argv
)
{
message_filters
::Subscriber
<sensor_msgs
::Imu
> sub_imu_accel(n
,IMU_TOPIC_ACCEL
,2000,ros
::TransportHints().tcpNoDelay());
message_filters
::Subscriber
<sensor_msgs
::Imu
> sub_imu_gyro(n
,IMU_TOPIC_GYRO
,2000,ros
::TransportHints().tcpNoDelay());
typedef sync_policies
::ApproximateTime
<sensor_msgs
::Imu
, sensor_msgs
::Imu
> syncPolicy
;
Synchronizer
<syncPolicy
> sync(syncPolicy(10), sub_imu_accel
, sub_imu_gyro
);
sync
.registerCallback(boost
::bind(&imu_callback
, _1
, _2
));
ros
::spin();
return 0;
}
3. CMakeLists.txt 和 packages.xml添加如下ROS包:
find_package(catkin REQUIRED COMPONENTS
....
image_transport
....
)
<build_depend
>image_transport
</build_depend
>
<exec_depend
>image_transport
</exec_depend
>