CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
Ardupilot

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: Ardupilot/ardupilot
Path: blob/master/libraries/AP_Compass/AP_Compass_HMC5843.cpp
Views: 1798
1
/*
2
This program is free software: you can redistribute it and/or modify
3
it under the terms of the GNU General Public License as published by
4
the Free Software Foundation, either version 3 of the License, or
5
(at your option) any later version.
6
7
This program is distributed in the hope that it will be useful,
8
but WITHOUT ANY WARRANTY; without even the implied warranty of
9
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
GNU General Public License for more details.
11
12
You should have received a copy of the GNU General Public License
13
along with this program. If not, see <http://www.gnu.org/licenses/>.
14
*/
15
16
/*
17
* AP_Compass_HMC5843.cpp - Arduino Library for HMC5843 I2C magnetometer
18
* Code by Jordi Muñoz and Jose Julio. DIYDrones.com
19
*
20
* Sensor is connected to I2C port
21
* Sensor is initialized in Continuos mode (10Hz)
22
*
23
*/
24
#include "AP_Compass_HMC5843.h"
25
26
#if AP_COMPASS_HMC5843_ENABLED
27
28
#include <assert.h>
29
#include <utility>
30
#include <stdio.h>
31
32
#include <AP_Math/AP_Math.h>
33
#include <AP_HAL/utility/sparse-endian.h>
34
#include <AP_HAL/AP_HAL.h>
35
#include <AP_InertialSensor/AP_InertialSensor.h>
36
#include <AP_InertialSensor/AuxiliaryBus.h>
37
38
extern const AP_HAL::HAL& hal;
39
40
/*
41
* Default address: 0x1E
42
*/
43
44
#define HMC5843_REG_CONFIG_A 0x00
45
// Valid sample averaging for 5883L
46
#define HMC5843_SAMPLE_AVERAGING_1 (0x00 << 5)
47
#define HMC5843_SAMPLE_AVERAGING_2 (0x01 << 5)
48
#define HMC5843_SAMPLE_AVERAGING_4 (0x02 << 5)
49
#define HMC5843_SAMPLE_AVERAGING_8 (0x03 << 5)
50
51
#define HMC5843_CONF_TEMP_ENABLE (0x80)
52
53
// Valid data output rates for 5883L
54
#define HMC5843_OSR_0_75HZ (0x00 << 2)
55
#define HMC5843_OSR_1_5HZ (0x01 << 2)
56
#define HMC5843_OSR_3HZ (0x02 << 2)
57
#define HMC5843_OSR_7_5HZ (0x03 << 2)
58
#define HMC5843_OSR_15HZ (0x04 << 2)
59
#define HMC5843_OSR_30HZ (0x05 << 2)
60
#define HMC5843_OSR_75HZ (0x06 << 2)
61
// Sensor operation modes
62
#define HMC5843_OPMODE_NORMAL 0x00
63
#define HMC5843_OPMODE_POSITIVE_BIAS 0x01
64
#define HMC5843_OPMODE_NEGATIVE_BIAS 0x02
65
#define HMC5843_OPMODE_MASK 0x03
66
67
#define HMC5843_REG_CONFIG_B 0x01
68
#define HMC5883L_GAIN_0_88_GA (0x00 << 5)
69
#define HMC5883L_GAIN_1_30_GA (0x01 << 5)
70
#define HMC5883L_GAIN_1_90_GA (0x02 << 5)
71
#define HMC5883L_GAIN_2_50_GA (0x03 << 5)
72
#define HMC5883L_GAIN_4_00_GA (0x04 << 5)
73
#define HMC5883L_GAIN_4_70_GA (0x05 << 5)
74
#define HMC5883L_GAIN_5_60_GA (0x06 << 5)
75
#define HMC5883L_GAIN_8_10_GA (0x07 << 5)
76
77
#define HMC5843_GAIN_0_70_GA (0x00 << 5)
78
#define HMC5843_GAIN_1_00_GA (0x01 << 5)
79
#define HMC5843_GAIN_1_50_GA (0x02 << 5)
80
#define HMC5843_GAIN_2_00_GA (0x03 << 5)
81
#define HMC5843_GAIN_3_20_GA (0x04 << 5)
82
#define HMC5843_GAIN_3_80_GA (0x05 << 5)
83
#define HMC5843_GAIN_4_50_GA (0x06 << 5)
84
#define HMC5843_GAIN_6_50_GA (0x07 << 5)
85
86
#define HMC5843_REG_MODE 0x02
87
#define HMC5843_MODE_CONTINUOUS 0x00
88
#define HMC5843_MODE_SINGLE 0x01
89
90
#define HMC5843_REG_DATA_OUTPUT_X_MSB 0x03
91
92
#define HMC5843_REG_ID_A 0x0A
93
94
95
AP_Compass_HMC5843::AP_Compass_HMC5843(AP_HMC5843_BusDriver *bus,
96
bool force_external, enum Rotation rotation)
97
: _bus(bus)
98
, _rotation(rotation)
99
, _force_external(force_external)
100
{
101
}
102
103
AP_Compass_HMC5843::~AP_Compass_HMC5843()
104
{
105
delete _bus;
106
}
107
108
AP_Compass_Backend *AP_Compass_HMC5843::probe(AP_HAL::OwnPtr<AP_HAL::Device> dev,
109
bool force_external,
110
enum Rotation rotation)
111
{
112
if (!dev) {
113
return nullptr;
114
}
115
AP_HMC5843_BusDriver *bus = NEW_NOTHROW AP_HMC5843_BusDriver_HALDevice(std::move(dev));
116
if (!bus) {
117
return nullptr;
118
}
119
120
AP_Compass_HMC5843 *sensor = NEW_NOTHROW AP_Compass_HMC5843(bus, force_external, rotation);
121
if (!sensor || !sensor->init()) {
122
delete sensor;
123
return nullptr;
124
}
125
126
return sensor;
127
}
128
129
#if AP_INERTIALSENSOR_ENABLED
130
AP_Compass_Backend *AP_Compass_HMC5843::probe_mpu6000(enum Rotation rotation)
131
{
132
AP_InertialSensor &ins = *AP_InertialSensor::get_singleton();
133
134
AP_HMC5843_BusDriver *bus =
135
NEW_NOTHROW AP_HMC5843_BusDriver_Auxiliary(ins, HAL_INS_MPU60XX_SPI,
136
HAL_COMPASS_HMC5843_I2C_ADDR);
137
if (!bus) {
138
return nullptr;
139
}
140
141
AP_Compass_HMC5843 *sensor = NEW_NOTHROW AP_Compass_HMC5843(bus, false, rotation);
142
if (!sensor || !sensor->init()) {
143
delete sensor;
144
return nullptr;
145
}
146
147
return sensor;
148
}
149
#endif
150
151
bool AP_Compass_HMC5843::init()
152
{
153
AP_HAL::Semaphore *bus_sem = _bus->get_semaphore();
154
155
if (!bus_sem) {
156
DEV_PRINTF("HMC5843: Unable to get bus semaphore\n");
157
return false;
158
}
159
bus_sem->take_blocking();
160
161
// high retries for init
162
_bus->set_retries(10);
163
164
if (!_bus->configure()) {
165
DEV_PRINTF("HMC5843: Could not configure the bus\n");
166
goto errout;
167
}
168
169
if (!_check_whoami()) {
170
goto errout;
171
}
172
173
if (!_calibrate()) {
174
DEV_PRINTF("HMC5843: Could not calibrate sensor\n");
175
goto errout;
176
}
177
178
if (!_setup_sampling_mode()) {
179
goto errout;
180
}
181
182
if (!_bus->start_measurements()) {
183
DEV_PRINTF("HMC5843: Could not start measurements on bus\n");
184
goto errout;
185
}
186
187
_initialised = true;
188
189
// lower retries for run
190
_bus->set_retries(3);
191
192
bus_sem->give();
193
194
// perform an initial read
195
read();
196
197
//register compass instance
198
_bus->set_device_type(DEVTYPE_HMC5883);
199
if (!register_compass(_bus->get_bus_id(), _compass_instance)) {
200
return false;
201
}
202
set_dev_id(_compass_instance, _bus->get_bus_id());
203
204
set_rotation(_compass_instance, _rotation);
205
206
if (_force_external) {
207
set_external(_compass_instance, true);
208
}
209
210
// read from sensor at 75Hz
211
_bus->register_periodic_callback(13333,
212
FUNCTOR_BIND_MEMBER(&AP_Compass_HMC5843::_timer, void));
213
214
DEV_PRINTF("HMC5843 found on bus 0x%x\n", (unsigned)_bus->get_bus_id());
215
216
return true;
217
218
errout:
219
bus_sem->give();
220
return false;
221
}
222
223
/*
224
* take a reading from the magnetometer
225
*
226
* bus semaphore has been taken already by HAL
227
*/
228
void AP_Compass_HMC5843::_timer()
229
{
230
bool result = _read_sample();
231
232
// always ask for a new sample
233
_take_sample();
234
235
if (!result) {
236
return;
237
}
238
239
// get raw_field - sensor frame, uncorrected
240
Vector3f raw_field = Vector3f(_mag_x, _mag_y, _mag_z);
241
raw_field *= _gain_scale;
242
243
// rotate to the desired orientation
244
if (is_external(_compass_instance)) {
245
raw_field.rotate(ROTATION_YAW_90);
246
}
247
248
// We expect to do reads at 10Hz, and we get new data at most 75Hz, so we
249
// don't expect to accumulate more than 8 before a read; let's make it
250
// 14 to give more room for the initialization phase
251
accumulate_sample(raw_field, _compass_instance, 14);
252
}
253
254
/*
255
* Take accumulated reads from the magnetometer or try to read once if no
256
* valid data
257
*
258
* bus semaphore must not be locked
259
*/
260
void AP_Compass_HMC5843::read()
261
{
262
if (!_initialised) {
263
// someone has tried to enable a compass for the first time
264
// mid-flight .... we can't do that yet (especially as we won't
265
// have the right orientation!)
266
return;
267
}
268
269
drain_accumulated_samples(_compass_instance, &_scaling);
270
}
271
272
bool AP_Compass_HMC5843::_setup_sampling_mode()
273
{
274
_gain_scale = (1.0f / 1090) * 1000;
275
if (!_bus->register_write(HMC5843_REG_CONFIG_A,
276
HMC5843_CONF_TEMP_ENABLE |
277
HMC5843_OSR_75HZ |
278
HMC5843_SAMPLE_AVERAGING_1) ||
279
!_bus->register_write(HMC5843_REG_CONFIG_B,
280
HMC5883L_GAIN_1_30_GA) ||
281
!_bus->register_write(HMC5843_REG_MODE,
282
HMC5843_MODE_SINGLE)) {
283
return false;
284
}
285
return true;
286
}
287
288
/*
289
* Read Sensor data - bus semaphore must be taken
290
*/
291
bool AP_Compass_HMC5843::_read_sample()
292
{
293
struct PACKED {
294
be16_t rx;
295
be16_t ry;
296
be16_t rz;
297
} val;
298
int16_t rx, ry, rz;
299
300
if (!_bus->block_read(HMC5843_REG_DATA_OUTPUT_X_MSB, (uint8_t *) &val, sizeof(val))){
301
return false;
302
}
303
304
rx = be16toh(val.rx);
305
ry = be16toh(val.rz);
306
rz = be16toh(val.ry);
307
308
if (rx == -4096 || ry == -4096 || rz == -4096) {
309
// no valid data available
310
return false;
311
}
312
313
_mag_x = -rx;
314
_mag_y = ry;
315
_mag_z = -rz;
316
317
return true;
318
}
319
320
321
/*
322
ask for a new oneshot sample
323
*/
324
void AP_Compass_HMC5843::_take_sample()
325
{
326
_bus->register_write(HMC5843_REG_MODE,
327
HMC5843_MODE_SINGLE);
328
}
329
330
bool AP_Compass_HMC5843::_check_whoami()
331
{
332
uint8_t id[3];
333
if (!_bus->block_read(HMC5843_REG_ID_A, id, 3)) {
334
// can't talk on bus
335
return false;
336
}
337
if (memcmp(id, "H43", 3) != 0) {
338
// not a HMC5x83 device
339
return false;
340
}
341
342
return true;
343
}
344
345
bool AP_Compass_HMC5843::_calibrate()
346
{
347
uint8_t calibration_gain;
348
int numAttempts = 0, good_count = 0;
349
bool success = false;
350
351
calibration_gain = HMC5883L_GAIN_2_50_GA;
352
353
/*
354
* the expected values are based on observation of real sensors
355
*/
356
float expected[3] = { 1.16*600, 1.08*600, 1.16*600 };
357
358
uint8_t base_config = HMC5843_OSR_15HZ;
359
uint8_t num_samples = 0;
360
361
while (success == 0 && numAttempts < 25 && good_count < 5) {
362
numAttempts++;
363
364
// force positiveBias (compass should return 715 for all channels)
365
if (!_bus->register_write(HMC5843_REG_CONFIG_A,
366
base_config | HMC5843_OPMODE_POSITIVE_BIAS)) {
367
// compass not responding on the bus
368
continue;
369
}
370
371
hal.scheduler->delay(50);
372
373
// set gains
374
if (!_bus->register_write(HMC5843_REG_CONFIG_B, calibration_gain) ||
375
!_bus->register_write(HMC5843_REG_MODE, HMC5843_MODE_SINGLE)) {
376
continue;
377
}
378
379
// read values from the compass
380
hal.scheduler->delay(50);
381
if (!_read_sample()) {
382
// we didn't read valid values
383
continue;
384
}
385
386
num_samples++;
387
388
float cal[3];
389
390
// hal.console->printf("mag %d %d %d\n", _mag_x, _mag_y, _mag_z);
391
392
cal[0] = fabsf(expected[0] / _mag_x);
393
cal[1] = fabsf(expected[1] / _mag_y);
394
cal[2] = fabsf(expected[2] / _mag_z);
395
396
// hal.console->printf("cal=%.2f %.2f %.2f\n", cal[0], cal[1], cal[2]);
397
398
// we throw away the first two samples as the compass may
399
// still be changing its state from the application of the
400
// strap excitation. After that we accept values in a
401
// reasonable range
402
if (numAttempts <= 2) {
403
continue;
404
}
405
406
#define IS_CALIBRATION_VALUE_VALID(val) (val > 0.7f && val < 1.35f)
407
408
if (IS_CALIBRATION_VALUE_VALID(cal[0]) &&
409
IS_CALIBRATION_VALUE_VALID(cal[1]) &&
410
IS_CALIBRATION_VALUE_VALID(cal[2])) {
411
// hal.console->printf("car=%.2f %.2f %.2f good\n", cal[0], cal[1], cal[2]);
412
good_count++;
413
414
_scaling[0] += cal[0];
415
_scaling[1] += cal[1];
416
_scaling[2] += cal[2];
417
}
418
419
#undef IS_CALIBRATION_VALUE_VALID
420
421
#if 0
422
/* useful for debugging */
423
hal.console->printf("MagX: %d MagY: %d MagZ: %d\n", (int)_mag_x, (int)_mag_y, (int)_mag_z);
424
hal.console->printf("CalX: %.2f CalY: %.2f CalZ: %.2f\n", cal[0], cal[1], cal[2]);
425
#endif
426
}
427
428
_bus->register_write(HMC5843_REG_CONFIG_A, base_config);
429
430
if (good_count >= 5) {
431
_scaling[0] = _scaling[0] / good_count;
432
_scaling[1] = _scaling[1] / good_count;
433
_scaling[2] = _scaling[2] / good_count;
434
success = true;
435
} else {
436
/* best guess */
437
_scaling[0] = 1.0;
438
_scaling[1] = 1.0;
439
_scaling[2] = 1.0;
440
if (num_samples > 5) {
441
// a sensor can be broken for calibration but still
442
// otherwise workable, accept it if we are reading samples
443
success = true;
444
}
445
}
446
447
#if 0
448
printf("scaling: %.2f %.2f %.2f\n",
449
_scaling[0], _scaling[1], _scaling[2]);
450
#endif
451
452
return success;
453
}
454
455
/* AP_HAL::Device implementation of the HMC5843 */
456
AP_HMC5843_BusDriver_HALDevice::AP_HMC5843_BusDriver_HALDevice(AP_HAL::OwnPtr<AP_HAL::Device> dev)
457
: _dev(std::move(dev))
458
{
459
// set read and auto-increment flags on SPI
460
if (_dev->bus_type() == AP_HAL::Device::BUS_TYPE_SPI) {
461
_dev->set_read_flag(0xC0);
462
}
463
}
464
465
bool AP_HMC5843_BusDriver_HALDevice::block_read(uint8_t reg, uint8_t *buf, uint32_t size)
466
{
467
return _dev->read_registers(reg, buf, size);
468
}
469
470
bool AP_HMC5843_BusDriver_HALDevice::register_read(uint8_t reg, uint8_t *val)
471
{
472
return _dev->read_registers(reg, val, 1);
473
}
474
475
bool AP_HMC5843_BusDriver_HALDevice::register_write(uint8_t reg, uint8_t val)
476
{
477
return _dev->write_register(reg, val);
478
}
479
480
AP_HAL::Semaphore *AP_HMC5843_BusDriver_HALDevice::get_semaphore()
481
{
482
return _dev->get_semaphore();
483
}
484
485
AP_HAL::Device::PeriodicHandle AP_HMC5843_BusDriver_HALDevice::register_periodic_callback(uint32_t period_usec, AP_HAL::Device::PeriodicCb cb)
486
{
487
return _dev->register_periodic_callback(period_usec, cb);
488
}
489
490
491
#if AP_INERTIALSENSOR_ENABLED
492
/* HMC5843 on an auxiliary bus of IMU driver */
493
AP_HMC5843_BusDriver_Auxiliary::AP_HMC5843_BusDriver_Auxiliary(AP_InertialSensor &ins, uint8_t backend_id,
494
uint8_t addr)
495
{
496
/*
497
* Only initialize members. Fails are handled by configure or while
498
* getting the semaphore
499
*/
500
_bus = ins.get_auxiliary_bus(backend_id);
501
if (!_bus) {
502
return;
503
}
504
505
_slave = _bus->request_next_slave(addr);
506
}
507
508
AP_HMC5843_BusDriver_Auxiliary::~AP_HMC5843_BusDriver_Auxiliary()
509
{
510
/* After started it's owned by AuxiliaryBus */
511
if (!_started) {
512
delete _slave;
513
}
514
}
515
516
bool AP_HMC5843_BusDriver_Auxiliary::block_read(uint8_t reg, uint8_t *buf, uint32_t size)
517
{
518
if (_started) {
519
/*
520
* We can only read a block when reading the block of sample values -
521
* calling with any other value is a mistake
522
*/
523
if (reg != HMC5843_REG_DATA_OUTPUT_X_MSB) {
524
return false;
525
}
526
527
int n = _slave->read(buf);
528
return n == static_cast<int>(size);
529
}
530
531
int r = _slave->passthrough_read(reg, buf, size);
532
533
return r > 0 && static_cast<uint32_t>(r) == size;
534
}
535
536
bool AP_HMC5843_BusDriver_Auxiliary::register_read(uint8_t reg, uint8_t *val)
537
{
538
return _slave->passthrough_read(reg, val, 1) == 1;
539
}
540
541
bool AP_HMC5843_BusDriver_Auxiliary::register_write(uint8_t reg, uint8_t val)
542
{
543
return _slave->passthrough_write(reg, val) == 1;
544
}
545
546
AP_HAL::Semaphore *AP_HMC5843_BusDriver_Auxiliary::get_semaphore()
547
{
548
return _bus->get_semaphore();
549
}
550
551
552
bool AP_HMC5843_BusDriver_Auxiliary::configure()
553
{
554
if (!_bus || !_slave) {
555
return false;
556
}
557
return true;
558
}
559
560
bool AP_HMC5843_BusDriver_Auxiliary::start_measurements()
561
{
562
if (_bus->register_periodic_read(_slave, HMC5843_REG_DATA_OUTPUT_X_MSB, 6) < 0) {
563
return false;
564
}
565
566
_started = true;
567
568
return true;
569
}
570
571
AP_HAL::Device::PeriodicHandle AP_HMC5843_BusDriver_Auxiliary::register_periodic_callback(uint32_t period_usec, AP_HAL::Device::PeriodicCb cb)
572
{
573
return _bus->register_periodic_callback(period_usec, cb);
574
}
575
576
// set device type within a device class
577
void AP_HMC5843_BusDriver_Auxiliary::set_device_type(uint8_t devtype)
578
{
579
_bus->set_device_type(devtype);
580
}
581
582
// return 24 bit bus identifier
583
uint32_t AP_HMC5843_BusDriver_Auxiliary::get_bus_id(void) const
584
{
585
return _bus->get_bus_id();
586
}
587
#endif // AP_INERTIALSENSOR_ENABLED
588
589
#endif // AP_COMPASS_HMC5843_ENABLED
590
591