imu_compass.cpp
Go to the documentation of this file.
1 /*
2 imu_compass.cpp
3 Authors: Prasenjit (pmukherj@clearpathrobotics.com)
4 Copyright (c) 2013, Clearpath Robotics, Inc., All rights reserved.
5 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
6 following conditions are met:
7  * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
8  disclaimer.
9  * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
10  disclaimer in the documentation and/or other materials provided with the distribution.
11  * Neither the name of Clearpath Robotics nor the names of its contributors may be used to endorse or promote products
12  derived from this software without specific prior written permission.
13 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
14 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
15 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
16 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
17 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
18 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
19 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
20 
21 Description:
22 CPP file for IMU Compass Class that combines gyroscope and magnetometer data to get a clean estimate of yaw.
23 */
24 
26 
27 double magn(tf::Vector3 a) {
28  return sqrt(a.x()*a.x() + a.y()*a.y() + a.z()*a.z());
29 }
30 
32  node_(n), curr_imu_reading_(new sensor_msgs::Imu()) {
33  // Acquire Parameters
34  ros::param::param("~mag_bias/x", mag_zero_x_, 0.0);
35  ros::param::param("~mag_bias/y", mag_zero_y_, 0.0);
36  ros::param::param("~mag_bias/z", mag_zero_z_, 0.0);
37 
38 
39  ROS_INFO("Using magnetometer bias (x,y):%f,%f", mag_zero_x_, mag_zero_y_);
40 
41  ros::param::param("~compass/sensor_timeout", sensor_timeout_, 0.5);
42  ros::param::param("~compass/yaw_meas_variance", yaw_meas_variance_, 10.0);
43  ros::param::param("~compass/gyro_meas_variance", heading_prediction_variance_, 0.01);
44  ROS_INFO("Using variance %f", yaw_meas_variance_);
45 
46  ros::param::param("~compass/mag_declination", mag_declination_, 0.0);
47  ROS_INFO("Using magnetic declination %f (%f degrees)", mag_declination_, mag_declination_ * 180 / M_PI);
48 
49  // Setup Subscribers
50  imu_sub_ = node_.subscribe("imu/data", 1000, &IMUCompass::imuCallback, this);
51  mag_sub_ = node_.subscribe("imu/mag", 1000, &IMUCompass::magCallback, this);
52  decl_sub_ = node_.subscribe("imu/declination", 1000, &IMUCompass::declCallback, this);
53  imu_pub_ = node_.advertise<sensor_msgs::Imu>("imu/data_compass", 1);
54  compass_pub_ = node_.advertise<std_msgs::Float32>("imu/compass_heading", 1);
55  mag_pub_ = node_.advertise<geometry_msgs::Vector3Stamped>("imu/mag_calib", 1);
56 
57  raw_compass_pub_ = node_.advertise<std_msgs::Float32>("imu/raw_compass_heading", 1);
58 
59  first_mag_reading_ = false;
60  first_gyro_reading_ = false;
61  gyro_update_complete_ = false;
64 
65  ROS_INFO("Compass Estimator Started");
66 }
67 
70  ROS_WARN("Waiting for IMU data, no gyroscope data available)");
71  if (!first_mag_reading_)
72  ROS_WARN("Waiting for mag data, no magnetometer data available, Filter not initialized");
73 
75  // gyro data is coming in too slowly
76  ROS_WARN("Gyroscope data being receieved too slow or not at all");
77  first_gyro_reading_ = false;
78  }
79 
81  // gyro data is coming in too slowly
82  ROS_WARN("Magnetometer data being receieved too slow or not at all");
83  filter_initialized_ = false;
84  first_mag_reading_ = false;
85  }
86 }
87 
88 void IMUCompass::imuCallback(const sensor_msgs::ImuPtr data) {
89  // Transform Data and get the yaw direction
90  geometry_msgs::Vector3 gyro_vector;
91  geometry_msgs::Vector3 gyro_vector_transformed;
92  gyro_vector = data->angular_velocity;
93 
95  first_gyro_reading_ = true;
96 
99  tf::StampedTransform transform;
100 
101  try {
102  listener_.lookupTransform("base_link", data->header.frame_id, ros::Time(0), transform);
103  } catch (tf::TransformException &ex) {
104  ROS_WARN("Missed transform between base_link and %s", data->header.frame_id.c_str());
105  return;
106  }
107 
108  tf::Vector3 orig_bt;
109  tf::Matrix3x3 transform_mat(transform.getRotation());
110  tf::vector3MsgToTF(gyro_vector, orig_bt);
111  tf::vector3TFToMsg(orig_bt * transform_mat, gyro_vector_transformed);
112  double yaw_gyro_reading = gyro_vector_transformed.z;
113 
114  // Run Motion Update
115  if (filter_initialized_) {
116  heading_prediction_ = curr_heading_ + yaw_gyro_reading * dt; // xp = A*x + B*u
118 
119  if (heading_prediction_ > 3.14159)
120  heading_prediction_ -= 2 * 3.14159;
121  else if(heading_prediction_ < -3.14159)
122  heading_prediction_ += 2 * 3.14159;
123  gyro_update_complete_ = true;
124  }
125  curr_imu_reading_ = data;
126 }
127 
128 void IMUCompass::declCallback(const std_msgs::Float32& data) {
129  mag_declination_ = data.data;
130  ROS_INFO("Using magnetic declination %f (%f degrees)", mag_declination_, mag_declination_ * 180 / M_PI);
131 }
132 
133 void IMUCompass::magCallback(const geometry_msgs::Vector3StampedConstPtr& data) {
134  geometry_msgs::Vector3 imu_mag = data->vector;
135  geometry_msgs::Vector3 imu_mag_transformed;
136 
137  // Check for nans and bail
138  if ( std::isnan(data->vector.x) ||
139  std::isnan(data->vector.y) ||
140  std::isnan(data->vector.z) ) {
141  return;
142  }
143 
144  imu_mag.x = data->vector.x;
145  imu_mag.y = data->vector.y;
146  imu_mag.z = data->vector.z;
147 
149  tf::StampedTransform transform;
150  try {
151  listener_.lookupTransform("base_link", data->header.frame_id, ros::Time(0), transform);
152  } catch (tf::TransformException &ex) {
153  ROS_WARN("Missed transform between base_link and %s", data->header.frame_id.c_str());
154  return;
155  }
156 
157  tf::Vector3 orig_bt;
158  tf::Matrix3x3 transform_mat(transform.getRotation());
159  tf::vector3MsgToTF(imu_mag, orig_bt);
160  tf::vector3TFToMsg(orig_bt * transform_mat, imu_mag_transformed);
161 
162  // Compensate for hard iron
163  double mag_x = imu_mag_transformed.x - mag_zero_x_;
164  double mag_y = imu_mag_transformed.y - mag_zero_y_;
165  double mag_z = imu_mag_transformed.z; // calibration is purely 2D
166 
167  // Normalize vector
168  tf::Vector3 calib_mag(mag_x, mag_y, mag_z);
169  calib_mag = calib_mag / magn(calib_mag);
170  mag_x = calib_mag.x();
171  mag_y = calib_mag.y();
172  mag_z = calib_mag.z();
173 
174  geometry_msgs::Vector3Stamped calibrated_mag;
175  calibrated_mag.header.stamp = ros::Time::now();
176  calibrated_mag.header.frame_id = "imu_link";
177 
178  calibrated_mag.vector.x = calib_mag.x();
179  calibrated_mag.vector.y = calib_mag.y();
180  calibrated_mag.vector.z = calib_mag.z();
181 
182  mag_pub_.publish(calibrated_mag);
183 
184  tf::Quaternion q;
185  tf::quaternionMsgToTF(curr_imu_reading_->orientation, q);
186  tf::Transform curr_imu_meas;
187  curr_imu_meas = tf::Transform(q, tf::Vector3(0, 0, 0));
188  curr_imu_meas = curr_imu_meas * transform;
189  tf::Quaternion orig (transform.getRotation());
190 
191  // Till Compensation
192  tf::Matrix3x3 temp(curr_imu_meas.getRotation());
193 
194  double c_r, c_p, c_y;
195  temp.getRPY(c_r, c_p, c_y);
196  double cos_pitch = cos(c_p);
197  double sin_pitch = sin(c_p);
198  double cos_roll = cos(c_r);
199  double sin_roll = sin(c_r);
200  double t_mag_x = mag_x * cos_pitch + mag_z * sin_pitch;
201  double t_mag_y = mag_x * sin_roll * sin_pitch + mag_y * cos_roll - mag_z * sin_roll * cos_pitch;
202  double head_x = t_mag_x;
203  double head_y = t_mag_y;
204 
205  // Retrieve magnetometer heading
206  double heading_meas = atan2(head_x, head_y);
207 
208  // If this is the first magnetometer reading, initialize filter
209  if (!first_mag_reading_) {
210  // Initialize filter
211  initFilter(heading_meas);
212  first_mag_reading_ = true;
213  return;
214  }
215  // If gyro update (motion update) is complete, run measurement update and publish imu data
216  if (gyro_update_complete_) {
217  // K = Sp*C'*inv(C*Sp*C' + Q)
219  double innovation = heading_meas - heading_prediction_;
220  if (abs(innovation) > M_PI) // large change, signifies a wraparound. kalman filters don't like discontinuities like wraparounds, handle seperately.
221  curr_heading_ = heading_meas;
222  else
223  curr_heading_ = heading_prediction_ + kalman_gain * (innovation); // mu = mup + K*(y-C*mup)
224 
225  curr_heading_variance_ = (1 - kalman_gain) * heading_variance_prediction_; // S = (1-K*C)*Sp
226 
227  std_msgs::Float32 raw_heading_float;
228  raw_heading_float.data = heading_meas;
229  raw_compass_pub_.publish(raw_heading_float);
230 
231  repackageImuPublish(transform);
232  gyro_update_complete_ = false;
233  }
234 }
235 
237  // Get Current IMU reading and Compass heading
238  tf::Quaternion imu_reading;
239  tf::quaternionMsgToTF(curr_imu_reading_->orientation, imu_reading);
240  double compass_heading = curr_heading_ - mag_declination_;
241 
242  // Transform curr_imu_reading to base_link
243  tf::Transform o_imu_reading;
244  o_imu_reading = tf::Transform(imu_reading, tf::Vector3(0, 0, 0));
245  o_imu_reading = o_imu_reading * transform;
246  imu_reading = o_imu_reading.getRotation();
247 
248  // Acquire Quaternion that is the difference between the two readings
249  tf::Quaternion compass_yaw = tf::createQuaternionFromRPY(0.0, 0.0, compass_heading);
250  tf::Quaternion diff_yaw = tf::createQuaternionFromRPY(0.0, 0.0, compass_heading - tf::getYaw(imu_reading));
251 
252  // Transform the imu reading by the difference
253  tf::Quaternion new_quaternion = diff_yaw * imu_reading;
254 
255  // Transform the imu reading back into imu_link
256  sensor_msgs::Imu publish_imu;
257  o_imu_reading = tf::Transform(new_quaternion, tf::Vector3(0, 0, 0));
258  o_imu_reading = o_imu_reading * (transform.inverse());
259  tf::quaternionTFToMsg(o_imu_reading.getRotation(), curr_imu_reading_->orientation);
260 
261  // Publish all data
262  std_msgs::Float32 curr_heading_float;
263  curr_heading_float.data = compass_heading;
264  compass_pub_.publish(curr_heading_float);
266 }
267 
268 void IMUCompass::initFilter(double heading_meas) {
269  curr_heading_ = heading_meas;
270  curr_heading_variance_ = 1; // not very sure
271  filter_initialized_ = true;
272  ROS_INFO("Magnetometer data received. Compass estimator initialized");
273 }
274 
275 int main(int argc, char **argv) {
276  ros::init(argc, argv, "imu_compass");
277  ros::NodeHandle node;
278  IMUCompass imu_heading_estimator(node);
279  ros::spin();
280  return 0;
281 }
double heading_variance_prediction_
Definition: imu_compass.h:74
ros::Publisher raw_compass_pub_
Definition: imu_compass.h:44
double mag_zero_z_
Definition: imu_compass.h:62
static tf::Quaternion createQuaternionFromRPY(double roll, double pitch, double yaw)
bool param(const std::string &param_name, T &param_val, const T &default_val)
double magn(tf::Vector3 a)
Definition: imu_compass.cpp:27
void publish(const boost::shared_ptr< M > &message) const
Subscriber subscribe(const std::string &topic, uint32_t queue_size, void(T::*fp)(M), T *obj, const TransportHints &transport_hints=TransportHints())
void declCallback(const std_msgs::Float32 &data)
ros::Timer debug_timer_
Definition: imu_compass.h:47
static double getYaw(const Quaternion &bt_q)
bool gyro_update_complete_
Definition: imu_compass.h:60
ROSCPP_DECL void init(int &argc, char **argv, const std::string &name, uint32_t options=0)
ros::Publisher mag_pub_
Definition: imu_compass.h:42
static void vector3TFToMsg(const Vector3 &bt_v, geometry_msgs::Vector3 &msg_v)
int main(int argc, char **argv)
#define ROS_WARN(...)
ROSCPP_DECL void spin(Spinner &spinner)
ros::Subscriber mag_sub_
Definition: imu_compass.h:39
double curr_heading_variance_
Definition: imu_compass.h:69
double heading_prediction_
Definition: imu_compass.h:73
TFSIMD_FORCE_INLINE const tfScalar & x() const
double mag_declination_
Definition: imu_compass.h:76
bool first_mag_reading_
Definition: imu_compass.h:57
void debugCallback(const ros::TimerEvent &)
Definition: imu_compass.cpp:68
void imuCallback(sensor_msgs::ImuPtr data)
Definition: imu_compass.cpp:88
static void vector3MsgToTF(const geometry_msgs::Vector3 &msg_v, Vector3 &bt_v)
TFSIMD_FORCE_INLINE const tfScalar & z() const
sensor_msgs::ImuPtr curr_imu_reading_
Definition: imu_compass.h:64
double mag_zero_x_
Definition: imu_compass.h:62
static void quaternionMsgToTF(const geometry_msgs::Quaternion &msg, Quaternion &bt)
void getRPY(tfScalar &roll, tfScalar &pitch, tfScalar &yaw, unsigned int solution_number=1) const
#define ROS_INFO(...)
ros::Publisher compass_pub_
Definition: imu_compass.h:43
static void quaternionTFToMsg(const Quaternion &bt, geometry_msgs::Quaternion &msg)
double mag_zero_y_
Definition: imu_compass.h:62
TFSIMD_FORCE_INLINE const tfScalar & y() const
Timer createTimer(Rate r, Handler h, Obj o, bool oneshot=false, bool autostart=true) const
ros::Subscriber imu_sub_
Definition: imu_compass.h:38
Publisher advertise(const std::string &topic, uint32_t queue_size, bool latch=false)
tf::TransformListener listener_
Definition: imu_compass.h:46
bool filter_initialized_
Definition: imu_compass.h:59
double yaw_meas_variance_
Definition: imu_compass.h:81
void lookupTransform(const std::string &target_frame, const std::string &source_frame, const ros::Time &time, StampedTransform &transform) const
ros::NodeHandle node_
Definition: imu_compass.h:37
bool first_gyro_reading_
Definition: imu_compass.h:58
void repackageImuPublish(tf::StampedTransform)
IMUCompass(ros::NodeHandle &n)
Definition: imu_compass.cpp:31
Quaternion getRotation() const
double last_measurement_update_time_
Definition: imu_compass.h:78
void initFilter(double heading_meas)
static Time now()
double last_motion_update_time_
Definition: imu_compass.h:77
double sensor_timeout_
Definition: imu_compass.h:70
void magCallback(const geometry_msgs::Vector3StampedConstPtr &data)
double heading_prediction_variance_
Definition: imu_compass.h:75
double curr_heading_
Definition: imu_compass.h:68
ros::Publisher imu_pub_
Definition: imu_compass.h:41
ros::Subscriber decl_sub_
Definition: imu_compass.h:40


imu_compass
Author(s):
autogenerated on Mon Jun 10 2019 13:35:52