mag_calibration.cpp 9.4 KB
Newer Older
1
2
/****************************************************************************
 *
3
 *   Copyright (c) 2013-2015 PX4 Development Team. All rights reserved.
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/**
35
 * @file mag_calibration.cpp
36
 *
37
38
39
40
41
42
 * Magnetometer calibration routine
 */

#include "mag_calibration.h"
#include "commander_helper.h"
#include "calibration_routines.h"
43
#include "calibration_messages.h"
44
45
46
47
48
49
50
51
52
53
54
55
56
57

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <poll.h>
#include <math.h>
#include <fcntl.h>
#include <drivers/drv_hrt.h>
#include <uORB/topics/sensor_combined.h>
#include <drivers/drv_mag.h>
#include <mavlink/mavlink_log.h>
#include <systemlib/param/param.h>
#include <systemlib/err.h>

58
59
60
61
62
/* oddly, ERROR is not defined for c++ */
#ifdef ERROR
# undef ERROR
#endif
static const int ERROR = -1;
63

64
65
static const char *sensor_name = "mag";

66
67
int calibrate_instance(int mavlink_fd, unsigned s, unsigned device_id);

68
int do_mag_calibration(int mavlink_fd)
69
{
70
	const unsigned max_mags = 3;
71

72
	int32_t device_id[max_mags];
73
	mavlink_and_console_log_info(mavlink_fd, CAL_STARTED_MSG, sensor_name);
74
	sleep(1);
75

76
77
	struct mag_scale mscale_null[max_mags] = {
	{
78
79
80
81
82
83
		0.0f,
		1.0f,
		0.0f,
		1.0f,
		0.0f,
		1.0f,
84
85
	}
	} ;
86

87
	int res = ERROR;
88

89
	char str[30];
hauptmech's avatar
hauptmech committed
90

91
	unsigned calibrated_ok = 0;
hauptmech's avatar
hauptmech committed
92

93
	for (unsigned s = 0; s < max_mags; s++) {
94

95
96
97
		/* erase old calibration */
		(void)sprintf(str, "%s%u", MAG_BASE_DEVICE_PATH, s);
		int fd = open(str, O_RDONLY);
98

99
100
101
102
		if (fd < 0) {
			continue;
		}

103
		mavlink_and_console_log_info(mavlink_fd, "Calibrating magnetometer #%u..", s);
104
105
		sleep(3);

106
107
108
109
110
111
		device_id[s] = ioctl(fd, DEVIOCGDEVICEID, 0);

		/* ensure all scale fields are initialized tha same as the first struct */
		(void)memcpy(&mscale_null[s], &mscale_null[0], sizeof(mscale_null[0]));

		res = ioctl(fd, MAGIOCSSCALE, (long unsigned int)&mscale_null[s]);
112

113
		if (res != OK) {
114
			mavlink_and_console_log_critical(mavlink_fd, CAL_FAILED_RESET_CAL_MSG);
115
116
117
118
119
120
121
		}

		if (res == OK) {
			/* calibrate range */
			res = ioctl(fd, MAGIOCCALIBRATE, fd);

			if (res != OK) {
122
				mavlink_and_console_log_info(mavlink_fd, "Skipped scale calibration");
123
124
125
126
127
128
129
130
131
				/* this is non-fatal - mark it accordingly */
				res = OK;
			}
		}

		close(fd);

		if (res == OK) {
			res = calibrate_instance(mavlink_fd, s, device_id[s]);
132
133
134
135
136
137
138
139

			if (res == OK) {
				calibrated_ok++;
			}
		}
	}

	if (calibrated_ok) {
Lorenz Meier's avatar
Lorenz Meier committed
140
141
142

		mavlink_and_console_log_info(mavlink_fd, CAL_PROGRESS_MSG, sensor_name, 100);
		usleep(100000);
143
		mavlink_and_console_log_info(mavlink_fd, CAL_DONE_MSG, sensor_name);
144
145
146
147
148
149

		/* auto-save to EEPROM */
		res = param_save_default();

		if (res != OK) {
			mavlink_and_console_log_critical(mavlink_fd, CAL_FAILED_SAVE_PARAMS_MSG);
150
		}
151
152
	} else {
		mavlink_and_console_log_critical(mavlink_fd, CAL_FAILED_MSG, sensor_name);
153
	}
154

155
156
157
158
159
160
	return res;
}

int calibrate_instance(int mavlink_fd, unsigned s, unsigned device_id)
{
	/* 45 seconds */
161
	uint64_t calibration_interval = 25 * 1000 * 1000;
162
163
164
165

	/* maximum 500 values */
	const unsigned int calibration_maxcount = 240;
	unsigned int calibration_counter;
166

Lorenz Meier's avatar
Lorenz Meier committed
167
168
169
	float *x = NULL;
	float *y = NULL;
	float *z = NULL;
170

171
	char str[30];
172
	int res = OK;
173
174
	
	/* allocate memory */
175
	mavlink_and_console_log_info(mavlink_fd, CAL_PROGRESS_MSG, sensor_name, 20);
176

177
178
179
	x = reinterpret_cast<float *>(malloc(sizeof(float) * calibration_maxcount));
	y = reinterpret_cast<float *>(malloc(sizeof(float) * calibration_maxcount));
	z = reinterpret_cast<float *>(malloc(sizeof(float) * calibration_maxcount));
180

181
	if (x == NULL || y == NULL || z == NULL) {
182
		mavlink_and_console_log_critical(mavlink_fd, "ERROR: out of memory");
183

184
185
186
187
		/* clean up */
		if (x != NULL) {
			free(x);
		}
188

189
190
191
		if (y != NULL) {
			free(y);
		}
192

193
194
		if (z != NULL) {
			free(z);
195
		}
196

197
198
		res = ERROR;
		return res;
199
200
	}

201
	if (res == OK) {
202
		int sub_mag = orb_subscribe_multi(ORB_ID(sensor_mag), s);
Lorenz Meier's avatar
Lorenz Meier committed
203

204
		if (sub_mag < 0) {
205
			mavlink_and_console_log_critical(mavlink_fd, "No mag found, abort");
206
207
208
209
210
211
			res = ERROR;
		}  else {
			struct mag_report mag;

			/* limit update rate to get equally spaced measurements over time (in ms) */
			orb_set_interval(sub_mag, (calibration_interval / 1000) / calibration_maxcount);
Lorenz Meier's avatar
Lorenz Meier committed
212

213
214
215
			/* calibrate offsets */
			uint64_t calibration_deadline = hrt_absolute_time() + calibration_interval;
			unsigned poll_errcount = 0;
216

217
			mavlink_and_console_log_info(mavlink_fd, "Turn on all sides: front/back,left/right,up/down");
218

219
			calibration_counter = 0U;
Lorenz Meier's avatar
Lorenz Meier committed
220

221
222
			while (hrt_absolute_time() < calibration_deadline &&
			       calibration_counter < calibration_maxcount) {
223

224
225
226
227
				/* wait blocking for new data */
				struct pollfd fds[1];
				fds[0].fd = sub_mag;
				fds[0].events = POLLIN;
228

229
				int poll_ret = poll(fds, 1, 1000);
230

231
				if (poll_ret > 0) {
232
					orb_copy(ORB_ID(sensor_mag), sub_mag, &mag);
233

234
235
236
					x[calibration_counter] = mag.x;
					y[calibration_counter] = mag.y;
					z[calibration_counter] = mag.z;
237

238
					calibration_counter++;
239

240
					if (calibration_counter % (calibration_maxcount / 20) == 0) {
241
						mavlink_and_console_log_info(mavlink_fd, CAL_PROGRESS_MSG, sensor_name, 20 + (calibration_counter * 50) / calibration_maxcount);
242
243
244
245
					}

				} else {
					poll_errcount++;
246
				}
247

248
				if (poll_errcount > 1000) {
249
					mavlink_and_console_log_critical(mavlink_fd, CAL_FAILED_SENSOR_MSG);
250
251
252
					res = ERROR;
					break;
				}
253
			}
254

255
			close(sub_mag);
256
257
258
259
260
261
262
263
		}
	}

	float sphere_x;
	float sphere_y;
	float sphere_z;
	float sphere_radius;

264
	if (res == OK && calibration_counter > (calibration_maxcount / 2)) {
Lorenz Meier's avatar
Lorenz Meier committed
265

266
		/* sphere fit */
267
		mavlink_and_console_log_info(mavlink_fd, CAL_PROGRESS_MSG, sensor_name, 70);
268
		sphere_fit_least_squares(x, y, z, calibration_counter, 100, 0.0f, &sphere_x, &sphere_y, &sphere_z, &sphere_radius);
269
		mavlink_and_console_log_info(mavlink_fd, CAL_PROGRESS_MSG, sensor_name, 80);
270

271
		if (!isfinite(sphere_x) || !isfinite(sphere_y) || !isfinite(sphere_z)) {
272
			mavlink_and_console_log_critical(mavlink_fd, "ERROR: NaN in sphere fit");
273
274
275
			res = ERROR;
		}
	}
276

277
	if (x != NULL) {
278
		free(x);
279
	}
280

281
	if (y != NULL) {
282
		free(y);
283
	}
284

285
	if (z != NULL) {
286
		free(z);
287
	}
288

289
290
291
	if (res == OK) {
		/* apply calibration and set parameters */
		struct mag_scale mscale;
292
293
		(void)sprintf(str, "%s%u", MAG_BASE_DEVICE_PATH, s);
		int fd = open(str, 0);
294
		res = ioctl(fd, MAGIOCGSCALE, (long unsigned int)&mscale);
295

296
		if (res != OK) {
297
			mavlink_and_console_log_critical(mavlink_fd, "ERROR: failed to get current calibration");
298
		}
299

300
301
302
303
		if (res == OK) {
			mscale.x_offset = sphere_x;
			mscale.y_offset = sphere_y;
			mscale.z_offset = sphere_z;
304

305
			res = ioctl(fd, MAGIOCSSCALE, (long unsigned int)&mscale);
306

307
			if (res != OK) {
308
				mavlink_and_console_log_critical(mavlink_fd, CAL_FAILED_APPLY_CAL_MSG);
309
			}
310
311
		}

312
		close(fd);
313

314
		if (res == OK) {
315

316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
			bool failed = false;
			/* set parameters */
			(void)sprintf(str, "CAL_MAG%u_ID", s);
			failed |= (OK != param_set(param_find(str), &(device_id)));
			(void)sprintf(str, "CAL_MAG%u_XOFF", s);
			failed |= (OK != param_set(param_find(str), &(mscale.x_offset)));
			(void)sprintf(str, "CAL_MAG%u_YOFF", s);
			failed |= (OK != param_set(param_find(str), &(mscale.y_offset)));
			(void)sprintf(str, "CAL_MAG%u_ZOFF", s);
			failed |= (OK != param_set(param_find(str), &(mscale.z_offset)));
			(void)sprintf(str, "CAL_MAG%u_XSCALE", s);
			failed |= (OK != param_set(param_find(str), &(mscale.x_scale)));
			(void)sprintf(str, "CAL_MAG%u_YSCALE", s);
			failed |= (OK != param_set(param_find(str), &(mscale.y_scale)));
			(void)sprintf(str, "CAL_MAG%u_ZSCALE", s);
			failed |= (OK != param_set(param_find(str), &(mscale.z_scale)));

			if (failed) {
334
				res = ERROR;
335
				mavlink_and_console_log_critical(mavlink_fd, CAL_FAILED_SET_PARAMS_MSG);
336
			}
337

338
			mavlink_and_console_log_info(mavlink_fd, CAL_PROGRESS_MSG, sensor_name, 90);
339
340
		}

341
		mavlink_and_console_log_info(mavlink_fd, "mag off: x:%.2f y:%.2f z:%.2f Ga", (double)mscale.x_offset,
342
				 (double)mscale.y_offset, (double)mscale.z_offset);
343
		mavlink_and_console_log_info(mavlink_fd, "mag scale: x:%.2f y:%.2f z:%.2f", (double)mscale.x_scale,
344
				 (double)mscale.y_scale, (double)mscale.z_scale);
345
	}
Lorenz Meier's avatar
Lorenz Meier committed
346
347

	return res;
348
}