-
Notifications
You must be signed in to change notification settings - Fork 68
/
MPU.cpp
2432 lines (2272 loc) · 89 KB
/
MPU.cpp
1
2
3
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// =========================================================================
// This library is placed under the MIT License
// Copyright 2017-2018 Natanael Josue Rabello. All rights reserved.
// For the license information refer to LICENSE file in root directory.
// =========================================================================
/**
* @file MPU.cpp
* Implement MPU class.
*/
#include "MPU.hpp"
#include <math.h>
#include <string.h>
#include "esp_err.h"
#include "freertos/FreeRTOS.h"
#include "freertos/portmacro.h"
#include "freertos/task.h"
#include "mpu/math.hpp"
#include "mpu/registers.hpp"
#include "mpu/types.hpp"
#include "sdkconfig.h"
static const char* TAG = CONFIG_MPU_CHIP_MODEL;
#include "mpu/log.hpp"
/*! MPU Driver namespace */
namespace mpud
{
/**
* @brief Initialize MPU device and set basic configurations.
* @details
* Init configuration:
* - Accel FSR: 4G
* - Gyro FSR: 500DPS
* - Sample rate: 100Hz
* - DLPF: 42Hz
* - INT pin: disabled
* - FIFO: disabled
* - Clock source: gyro PLL \n
* For MPU9150 and MPU9250:
* - Aux I2C Master: enabled, clock: 400KHz
* - Compass: enabled on Aux I2C's Slave 0 and Slave 1
*
* @note
* - A soft reset is performed first, which takes 100-200ms.
* - When using SPI, the primary I2C Slave module is disabled right away.
* */
esp_err_t MPU::initialize()
{
// reset device (wait a little to clear all registers)
if (MPU_ERR_CHECK(reset())) return err;
// wake-up the device (power on-reset state is asleep for some models)
if (MPU_ERR_CHECK(setSleep(false))) return err;
// disable MPU's I2C slave module when using SPI
#ifdef CONFIG_MPU_SPI
if (MPU_ERR_CHECK(writeBit(regs::USER_CTRL, regs::USERCTRL_I2C_IF_DIS_BIT, 1))) return err;
#endif
// set clock source to gyro PLL which is better than internal clock
if (MPU_ERR_CHECK(setClockSource(CLOCK_PLL))) return err;
#ifdef CONFIG_MPU6500
// MPU6500 / MPU9250 share 4kB of memory between the DMP and the FIFO. Since the
// first 3kB are needed by the DMP, we'll use the last 1kB for the FIFO.
if (MPU_ERR_CHECK(writeBits(regs::ACCEL_CONFIG2, regs::ACONFIG2_FIFO_SIZE_BIT, regs::ACONFIG2_FIFO_SIZE_LENGTH,
FIFO_SIZE_1K))) {
return err;
}
#endif
// set Full Scale range
if (MPU_ERR_CHECK(setGyroFullScale(GYRO_FS_500DPS))) return err;
if (MPU_ERR_CHECK(setAccelFullScale(ACCEL_FS_4G))) return err;
// set Digital Low Pass Filter to get smoother data
if (MPU_ERR_CHECK(setDigitalLowPassFilter(DLPF_42HZ))) return err;
// setup magnetometer
#ifdef CONFIG_MPU_AK89xx
if (MPU_ERR_CHECK(compassInit())) return err;
#ifdef CONFIG_MPU_AK8963
if (MPU_ERR_CHECK(compassSetSensitivity(MAG_SENSITIVITY_0_15_uT))) return err;
#endif
#endif
// set sample rate to 100Hz
if (MPU_ERR_CHECK(setSampleRate(100))) return err;
MPU_LOGI("Initialization complete");
return err;
}
/**
* @brief Reset internal registers and restore to default start-up state.
* @note
* - This function delays 100ms when using I2C and 200ms when using SPI.
* - It does not initialize the MPU again, just call initialize() instead.
* */
esp_err_t MPU::reset()
{
if (MPU_ERR_CHECK(writeBit(regs::PWR_MGMT1, regs::PWR1_DEVICE_RESET_BIT, 1))) return err;
vTaskDelay(100 / portTICK_PERIOD_MS);
#ifdef CONFIG_MPU_SPI
if (MPU_ERR_CHECK(resetSignalPath())) {
return err;
}
#endif
MPU_LOGI("Reset!");
return err;
}
/**
* @brief Enable / disable sleep mode
* @param enable enable value
* */
esp_err_t MPU::setSleep(bool enable)
{
return MPU_ERR_CHECK(writeBit(regs::PWR_MGMT1, regs::PWR1_SLEEP_BIT, (uint8_t) enable));
}
/**
* @brief Get current sleep state.
* @return
* - `true`: sleep enabled.
* - `false`: sleep disabled.
*/
bool MPU::getSleep()
{
MPU_ERR_CHECK(readBit(regs::PWR_MGMT1, regs::PWR1_SLEEP_BIT, buffer));
return buffer[0];
}
/**
* @brief Test connection with MPU.
* @details It reads the WHO_AM_IM register and check its value against the correct chip model.
* @return
* - `ESP_OK`: The MPU is connected and matchs the model.
* - `ESP_ERR_NOT_FOUND`: A device is connect, but does not match the chip selected in _menuconfig_.
* - May return other communication bus errors. e.g: `ESP_FAIL`, `ESP_ERR_TIMEOUT`.
* */
esp_err_t MPU::testConnection()
{
const uint8_t wai = whoAmI();
if (MPU_ERR_CHECK(lastError())) return err;
#if defined CONFIG_MPU6000 || defined CONFIG_MPU6050 || defined CONFIG_MPU9150
return (wai == 0x68) ? ESP_OK : ESP_ERR_NOT_FOUND;
#elif defined CONFIG_MPU9255
return (wai == 0x73) ? ESP_OK : ESP_ERR_NOT_FOUND;
#elif defined CONFIG_MPU9250
return (wai == 0x71) ? ESP_OK : ESP_ERR_NOT_FOUND;
#elif defined CONFIG_MPU6555
return (wai == 0x7C) ? ESP_OK : ESP_ERR_NOT_FOUND;
#elif defined CONFIG_MPU6500
return (wai == 0x70) ? ESP_OK : ESP_ERR_NOT_FOUND;
#endif
}
/**
* @brief Returns the value from WHO_AM_I register.
*/
uint8_t MPU::whoAmI()
{
MPU_ERR_CHECK(readByte(regs::WHO_AM_I, buffer));
return buffer[0];
}
/**
* @brief Set sample rate of data output.
*
* Sample rate controls sensor data output rate and FIFO sample rate.
* This is the update rate of sensor register. \n
* Formula: Sample Rate = Internal Output Rate / (1 + SMPLRT_DIV)
*
* @param rate 4Hz ~ 1KHz
* - For sample rate 8KHz: set digital low pass filter to DLPF_256HZ_NOLPF.
* - For sample rate 32KHZ [MPU6500 / MPU9250]: set fchoice to FCHOICE_0, see setFchoice().
*
* @note
* For MPU9150 & MPU9250:
* - When using compass, this function alters Aux I2C Master `sample_delay` property
* to adjust the compass sample rate. (also, `wait_for_es` property to adjust interrupt).
* - If sample rate lesser than 100 Hz, data-ready interrupt will wait for compass data.
* - If sample rate greater than 100 Hz, data-ready interrupt will not be delayed by the compass.
* */
esp_err_t MPU::setSampleRate(uint16_t rate)
{
// Check value range
if (rate < 4) {
MPU_LOGWMSG(msgs::INVALID_SAMPLE_RATE, " %d, minimum rate is 4", rate);
rate = 4;
}
else if (rate > 1000) {
MPU_LOGWMSG(msgs::INVALID_SAMPLE_RATE, " %d, maximum rate is 1000", rate);
rate = 1000;
}
#if CONFIG_MPU_LOG_LEVEL >= ESP_LOG_WARN
// Check selected Fchoice [MPU6500 and MPU9250 only]
#ifdef CONFIG_MPU6500
fchoice_t fchoice = getFchoice();
if (MPU_ERR_CHECK(lastError())) return err;
if (fchoice != FCHOICE_3) {
MPU_LOGWMSG(msgs::INVALID_STATE, ", sample rate divider is not effective when Fchoice != 3");
}
#endif
// Check dlpf configuration
dlpf_t dlpf = getDigitalLowPassFilter();
if (MPU_ERR_CHECK(lastError())) return err;
if (dlpf == 0 || dlpf == 7)
MPU_LOGWMSG(msgs::INVALID_STATE, ", sample rate divider is not effective when DLPF is (0 or 7)");
#endif
constexpr uint16_t internalSampleRate = 1000;
uint16_t divider = internalSampleRate / rate - 1;
// Check for rate match
uint16_t finalRate = (internalSampleRate / (1 + divider));
if (finalRate != rate) {
MPU_LOGW("Sample rate constrained to %d Hz", finalRate);
}
else {
MPU_LOGI("Sample rate set to %d Hz", finalRate);
}
// Write divider to register
if (MPU_ERR_CHECK(writeByte(regs::SMPLRT_DIV, (uint8_t) divider))) return err;
// check and set compass sample rate
#ifdef CONFIG_MPU_AK89xx
const auxi2c_slv_config_t magSlaveChgModeConf = getAuxI2CSlaveConfig(MAG_SLAVE_CHG_MODE);
if (MPU_ERR_CHECK(lastError())) return err;
const bool magSlaveChgModeEnabled = getAuxI2CSlaveEnabled(MAG_SLAVE_CHG_MODE);
if (magSlaveChgModeEnabled && magSlaveChgModeConf.addr == COMPASS_I2CADDRESS &&
(magSlaveChgModeConf.txdata & 0xF) == MAG_MODE_SINGLE_MEASURE) {
auxi2c_config_t auxi2cConf = getAuxI2CConfig();
if (MPU_ERR_CHECK(lastError())) return err;
if (rate <= COMPASS_SAMPLE_RATE_MAX) {
auxi2cConf.wait_for_es = 1;
auxi2cConf.sample_delay = 0;
}
else {
auxi2cConf.wait_for_es = 0;
auxi2cConf.sample_delay = (uint8_t)(ceil(static_cast<double>(finalRate) / COMPASS_SAMPLE_RATE_MAX) - 1);
const uint8_t compassRate = (finalRate / (auxi2cConf.sample_delay + 1));
MPU_LOGW("Compass sample rate constrained to %d, magnetometer's maximum is %d Hz", compassRate,
COMPASS_SAMPLE_RATE_MAX);
}
if (MPU_ERR_CHECK(setAuxI2CConfig(auxi2cConf))) return err;
}
#endif
return err;
}
/**
* @brief Retrieve sample rate divider and calculate the actual rate.
*/
uint16_t MPU::getSampleRate()
{
#ifdef CONFIG_MPU6500
fchoice_t fchoice = getFchoice();
MPU_ERR_CHECK(lastError());
if (fchoice != FCHOICE_3) return SAMPLE_RATE_MAX;
#endif
constexpr uint16_t sampleRateMax_nolpf = 8000;
dlpf_t dlpf = getDigitalLowPassFilter();
MPU_ERR_CHECK(lastError());
if (dlpf == 0 || dlpf == 7) return sampleRateMax_nolpf;
constexpr uint16_t internalSampleRate = 1000;
MPU_ERR_CHECK(readByte(regs::SMPLRT_DIV, buffer));
uint16_t rate = internalSampleRate / (1 + buffer[0]);
return rate;
}
/**
* @brief Select clock source.
* @note The gyro PLL is better than internal clock.
* @param clockSrc clock source
*/
esp_err_t MPU::setClockSource(clock_src_t clockSrc)
{
return MPU_ERR_CHECK(writeBits(regs::PWR_MGMT1, regs::PWR1_CLKSEL_BIT, regs::PWR1_CLKSEL_LENGTH, clockSrc));
}
/**
* @brief Return clock source.
*/
clock_src_t MPU::getClockSource()
{
MPU_ERR_CHECK(readBits(regs::PWR_MGMT1, regs::PWR1_CLKSEL_BIT, regs::PWR1_CLKSEL_LENGTH, buffer));
return (clock_src_t) buffer[0];
}
/**
* @brief Configures Digital Low Pass Filter (DLPF) setting for both the gyroscope and accelerometer.
* @param dlpf digital low-pass filter value
*/
esp_err_t MPU::setDigitalLowPassFilter(dlpf_t dlpf)
{
if (MPU_ERR_CHECK(writeBits(regs::CONFIG, regs::CONFIG_DLPF_CFG_BIT, regs::CONFIG_DLPF_CFG_LENGTH, dlpf))) {
return err;
}
#ifdef CONFIG_MPU6500
MPU_ERR_CHECK(
writeBits(regs::ACCEL_CONFIG2, regs::ACONFIG2_A_DLPF_CFG_BIT, regs::ACONFIG2_A_DLPF_CFG_LENGTH, dlpf));
#endif
return err;
}
/**
* @brief Return Digital Low Pass Filter configuration
*/
dlpf_t MPU::getDigitalLowPassFilter()
{
MPU_ERR_CHECK(readBits(regs::CONFIG, regs::CONFIG_DLPF_CFG_BIT, regs::CONFIG_DLPF_CFG_LENGTH, buffer));
return (dlpf_t) buffer[0];
}
/**
* @brief Reset sensors signal path.
*
* Reset all gyro digital signal path, accel digital signal path, and temp
* digital signal path. This also clears all the sensor registers.
*
* @note This function delays 100 ms, needed for reset to complete.
* */
esp_err_t MPU::resetSignalPath()
{
if (MPU_ERR_CHECK(writeBit(regs::USER_CTRL, regs::USERCTRL_SIG_COND_RESET_BIT, 1))) return err;
vTaskDelay(100 / portTICK_PERIOD_MS);
return err;
}
/**
* @brief Enter Low Power Accelerometer mode.
*
* In low-power accel mode, the chip goes to sleep and only wakes up to sample
* the accelerometer at a certain frequency.
* See setLowPowerAccelRate() to set the frequency.
*
* @param enable value
* + This function does the following to enable:
* - Set CYCLE bit to 1
* - Set SLEEP bit to 0
* - Set TEMP_DIS bit to 1
* - Set STBY_XG, STBY_YG, STBY_ZG bits to 1
* - Set STBY_XA, STBY_YA, STBY_ZA bits to 0
* - Set FCHOICE to 0 (ACCEL_FCHOICE_B bit to 1) [MPU6500 / MPU9250 only]
* - Disable Auxiliary I2C Master I/F
*
* + This function does the following to disable:
* - Set CYCLE bit to 0
* - Set TEMP_DIS bit to 0
* - Set STBY_XG, STBY_YG, STBY_ZG bits to 0
* - Set STBY_XA, STBY_YA, STBY_ZA bits to 0
* - Set FCHOICE to 3 (ACCEL_FCHOICE_B bit to 0) [MPU6500 / MPU9250 only]
* - Enable Auxiliary I2C Master I/F
* */
esp_err_t MPU::setLowPowerAccelMode(bool enable)
{
// set FCHOICE
#ifdef CONFIG_MPU6500
fchoice_t fchoice = enable ? FCHOICE_0 : FCHOICE_3;
if (MPU_ERR_CHECK(setFchoice(fchoice))) return err;
MPU_LOGVMSG(msgs::EMPTY, "Fchoice set to %d", fchoice);
#endif
// read PWR_MGMT1 and PWR_MGMT2 at once
if (MPU_ERR_CHECK(readBytes(regs::PWR_MGMT1, 2, buffer))) return err;
if (enable) {
// set CYCLE bit to 1 and SLEEP bit to 0 and TEMP_DIS bit to 1
buffer[0] |= 1 << regs::PWR1_CYCLE_BIT;
buffer[0] &= ~(1 << regs::PWR1_SLEEP_BIT);
buffer[0] |= 1 << regs::PWR1_TEMP_DIS_BIT;
// set STBY_XG, STBY_YG, STBY_ZG bits to 1
buffer[1] |= regs::PWR2_STBY_XYZG_BITS;
}
else { // disable
// set CYCLE bit to 0 and TEMP_DIS bit to 0
buffer[0] &= ~(1 << regs::PWR1_CYCLE_BIT);
buffer[0] &= ~(1 << regs::PWR1_TEMP_DIS_BIT);
// set STBY_XG, STBY_YG, STBY_ZG bits to 0
buffer[1] &= ~(regs::PWR2_STBY_XYZG_BITS);
}
// set STBY_XA, STBY_YA, STBY_ZA bits to 0
buffer[1] &= ~(regs::PWR2_STBY_XYZA_BITS);
// write back PWR_MGMT1 and PWR_MGMT2 at once
if (MPU_ERR_CHECK(writeBytes(regs::PWR_MGMT1, 2, buffer))) return err;
// disable Auxiliary I2C Master I/F in case it was active
if (MPU_ERR_CHECK(setAuxI2CEnabled(!enable))) return err;
return err;
}
/**
* @brief Return Low Power Accelerometer state.
*
* Condition to return true:
* - CYCLE bit is 1
* - SLEEP bit is 0
* - TEMP_DIS bit is 1
* - STBY_XG, STBY_YG, STBY_ZG bits are 1
* - STBY_XA, STBY_YA, STBY_ZA bits are 0
* - FCHOICE is 0 (ACCEL_FCHOICE_B bit is 1) [MPU6500 / MPU9250 only]
*
* */
bool MPU::getLowPowerAccelMode()
{
// check FCHOICE
#ifdef CONFIG_MPU6500
fchoice_t fchoice = getFchoice();
MPU_ERR_CHECK(lastError());
if (fchoice != FCHOICE_0) {
return false;
}
#endif
// read PWR_MGMT1 and PWR_MGMT2 at once
MPU_ERR_CHECK(readBytes(regs::PWR_MGMT1, 2, buffer));
// define configuration bits
constexpr uint8_t LPACCEL_CONFIG_BITMASK[2] = {
(1 << regs::PWR1_SLEEP_BIT) | (1 << regs::PWR1_CYCLE_BIT) | (1 << regs::PWR1_TEMP_DIS_BIT),
regs::PWR2_STBY_XYZA_BITS | regs::PWR2_STBY_XYZG_BITS};
constexpr uint8_t LPACCEL_ENABLED_VALUE[2] = {(1 << regs::PWR1_CYCLE_BIT) | (1 << regs::PWR1_TEMP_DIS_BIT),
regs::PWR2_STBY_XYZG_BITS};
// get just the configuration bits
buffer[0] &= LPACCEL_CONFIG_BITMASK[0];
buffer[1] &= LPACCEL_CONFIG_BITMASK[1];
// check pattern
return buffer[0] == LPACCEL_ENABLED_VALUE[0] && buffer[1] == LPACCEL_ENABLED_VALUE[1];
}
/**
* @brief Set Low Power Accelerometer frequency of wake-up.
* */
esp_err_t MPU::setLowPowerAccelRate(lp_accel_rate_t rate)
{
#if defined CONFIG_MPU6050
return MPU_ERR_CHECK(writeBits(regs::PWR_MGMT2, regs::PWR2_LP_WAKE_CTRL_BIT, regs::PWR2_LP_WAKE_CTRL_LENGTH, rate));
#elif defined CONFIG_MPU6500
return MPU_ERR_CHECK(writeBits(regs::LP_ACCEL_ODR, regs::LPA_ODR_CLKSEL_BIT, regs::LPA_ODR_CLKSEL_LENGTH, rate));
#endif
}
/**
* @brief Get Low Power Accelerometer frequency of wake-up.
*/
lp_accel_rate_t MPU::getLowPowerAccelRate()
{
#if defined CONFIG_MPU6050
MPU_ERR_CHECK(readBits(regs::PWR_MGMT2, regs::PWR2_LP_WAKE_CTRL_BIT, regs::PWR2_LP_WAKE_CTRL_LENGTH, buffer));
#elif defined CONFIG_MPU6500
MPU_ERR_CHECK(readBits(regs::LP_ACCEL_ODR, regs::LPA_ODR_CLKSEL_BIT, regs::LPA_ODR_CLKSEL_LENGTH, buffer));
#endif
return (lp_accel_rate_t) buffer[0];
}
/**
* @brief Enable/disable Motion modules (Motion detect, Zero-motion, Free-Fall).
*
* @attention
* The configurations must've already been set with setMotionDetectConfig() before
* enabling the module!
* @note
* - Call getMotionDetectStatus() to find out which axis generated motion interrupt. [MPU6000, MPU6050, MPU9150].
* - It is recommended to set the Motion Interrupt to propagate to the INT pin. To do that, use setInterruptEnabled().
* @param enable
* - On _true_, this function modifies the DLPF, put gyro and temperature in standby,
* and disable Auxiliary I2C Master I/F.
* - On _false_, this function sets DLPF to 42Hz and enables Auxiliary I2C master I/F.
* */
esp_err_t MPU::setMotionFeatureEnabled(bool enable)
{
#if defined CONFIG_MPU6050
if (MPU_ERR_CHECK(
writeBits(regs::ACCEL_CONFIG, regs::ACONFIG_HPF_BIT, regs::ACONFIG_HPF_LENGTH, ACCEL_DHPF_RESET))) {
return err;
}
#endif
/* enabling */
if (enable) {
#if defined CONFIG_MPU6050
constexpr dlpf_t kDLPF = DLPF_256HZ_NOLPF;
#elif defined CONFIG_MPU6500
constexpr dlpf_t kDLPF = DLPF_188HZ;
#endif
if (MPU_ERR_CHECK(setDigitalLowPassFilter(kDLPF))) return err;
#if defined CONFIG_MPU6050
// give a time for accumulation of samples
vTaskDelay(10 / portTICK_PERIOD_MS);
if (MPU_ERR_CHECK(
writeBits(regs::ACCEL_CONFIG, regs::ACONFIG_HPF_BIT, regs::ACONFIG_HPF_LENGTH, ACCEL_DHPF_HOLD))) {
return err;
}
#elif defined CONFIG_MPU6500
if (MPU_ERR_CHECK(
writeByte(regs::ACCEL_INTEL_CTRL, (1 << regs::ACCEL_INTEL_EN_BIT) | (1 << regs::ACCEL_INTEL_MODE_BIT))))
return err;
#endif
/* disabling */
}
else {
#if defined CONFIG_MPU6500
if (MPU_ERR_CHECK(writeBits(regs::ACCEL_INTEL_CTRL, regs::ACCEL_INTEL_EN_BIT, 2, 0x0))) {
return err;
}
#endif
constexpr dlpf_t kDLPF = DLPF_42HZ;
if (MPU_ERR_CHECK(setDigitalLowPassFilter(kDLPF))) return err;
}
// disable Auxiliary I2C Master I/F in case it was active
if (MPU_ERR_CHECK(setAuxI2CEnabled(!enable))) return err;
return err;
}
/**
* @brief Return true if a Motion Dectection module is enabled.
*/
bool MPU::getMotionFeatureEnabled()
{
uint8_t data;
#if defined CONFIG_MPU6050
MPU_ERR_CHECK(readBits(regs::ACCEL_CONFIG, regs::ACONFIG_HPF_BIT, regs::ACONFIG_HPF_LENGTH, &data));
if (data != ACCEL_DHPF_HOLD) return false;
constexpr dlpf_t kDLPF = DLPF_256HZ_NOLPF;
#elif defined CONFIG_MPU6500
MPU_ERR_CHECK(readByte(regs::ACCEL_INTEL_CTRL, &data));
constexpr uint8_t kAccelIntel = (1 << regs::ACCEL_INTEL_EN_BIT) | (1 << regs::ACCEL_INTEL_MODE_BIT);
if ((data & kAccelIntel) != kAccelIntel) return false;
constexpr dlpf_t kDLPF = DLPF_188HZ;
#endif
dlpf_t dlpf = getDigitalLowPassFilter();
MPU_ERR_CHECK(lastError());
if (dlpf != kDLPF) return false;
return true;
}
/**
* @brief Configure Motion-Detect or Wake-on-motion feature.
*
* The behaviour of this feature is very different between the MPU6050 (MPU9150) and the
* MPU6500 (MPU9250). Each chip's version of this feature is explained below.
*
* [MPU6050, MPU6000, MPU9150]:
* Accelerometer measurements are passed through a configurable digital high pass filter (DHPF)
* in order to eliminate bias due to gravity. A qualifying motion sample is one where the high
* passed sample from any axis has an absolute value exceeding a user-programmable threshold. A
* counter increments for each qualifying sample, and decrements for each non-qualifying sample.
* Once the counter reaches a user-programmable counter threshold, a motion interrupt is triggered.
* The axis and polarity which caused the interrupt to be triggered is flagged in the
* MOT_DETECT_STATUS register.
*
* [MPU6500, MPU9250]:
* Unlike the MPU6050 version, the hardware does not "lock in" a reference sample.
* The hardware monitors the accel data and detects any large change over a short period of time.
* A qualifying motion sample is one where the high passed sample from any axis has
* an absolute value exceeding the threshold.
* The hardware motion threshold can be between 4mg and 1020mg in 4mg increments.
*
* @note
* It is possible to enable **wake-on-motion** mode by doing the following:
* 1. Enter Low Power Accelerometer mode with setLowPowerAccelMode();
* 2. Select the wake-up rate with setLowPowerAccelRate();
* 3. Configure motion-detect interrupt with setMotionDetectConfig();
* 4. Enable the motion detection module with setMotionFeatureEnabled();
* */
esp_err_t MPU::setMotionDetectConfig(mot_config_t& config)
{
#if defined CONFIG_MPU6050
if (MPU_ERR_CHECK(writeByte(regs::MOTION_DUR, config.time))) return err;
if (MPU_ERR_CHECK(writeBits(regs::MOTION_DETECT_CTRL, regs::MOTCTRL_ACCEL_ON_DELAY_BIT,
regs::MOTCTRL_ACCEL_ON_DELAY_LENGTH, config.accel_on_delay))) {
return err;
}
if (MPU_ERR_CHECK(writeBits(regs::MOTION_DETECT_CTRL, regs::MOTCTRL_MOT_COUNT_BIT, regs::MOTCTRL_MOT_COUNT_LENGTH,
config.counter))) {
return err;
}
#endif
return MPU_ERR_CHECK(writeByte(regs::MOTION_THR, config.threshold));
}
/**
* @brief Return Motion Detection Configuration.
*/
mot_config_t MPU::getMotionDetectConfig()
{
mot_config_t config{};
#if defined CONFIG_MPU6050
MPU_ERR_CHECK(readByte(regs::MOTION_DUR, &config.time));
MPU_ERR_CHECK(readByte(regs::MOTION_DETECT_CTRL, buffer));
config.accel_on_delay =
(buffer[0] >> (regs::MOTCTRL_ACCEL_ON_DELAY_BIT - regs::MOTCTRL_ACCEL_ON_DELAY_LENGTH + 1)) & 0x3;
config.counter =
(mot_counter_t)((buffer[0] >> (regs::MOTCTRL_MOT_COUNT_BIT - regs::MOTCTRL_MOT_COUNT_LENGTH + 1)) & 0x3);
#endif
MPU_ERR_CHECK(readByte(regs::MOTION_THR, &config.threshold));
return config;
}
#if defined CONFIG_MPU6050
/**
* @brief Configure Zero-Motion.
*
* The Zero Motion detection capability uses the digital high pass filter (DHPF) and a similar
* threshold scheme to that of Free Fall detection. Each axis of the high passed accelerometer
* measurement must have an absolute value less than a threshold specified in the ZRMOT_THR
* register, which can be increased in 1 mg increments. Each time a motion sample meets this
* condition, a counter increments. When this counter reaches a threshold specified in ZRMOT_DUR, an
* interrupt is generated.
*
* Unlike Free Fall or Motion detection, Zero Motion detection triggers an interrupt both when Zero
* Motion is first detected and when Zero Motion is no longer detected. While Free Fall and Motion
* are indicated with a flag which clears after being read, reading the state of the Zero Motion
* detected from the MOT_DETECT_STATUS register does not clear its status.
*
* @note Enable by calling setMotionFeatureEnabled();
* */
esp_err_t MPU::setZeroMotionConfig(zrmot_config_t& config)
{
buffer[0] = config.threshold;
buffer[1] = config.time;
return MPU_ERR_CHECK(writeBytes(regs::ZRMOTION_THR, 2, buffer));
}
/**
* @brief Return Zero-Motion configuration.
*/
zrmot_config_t MPU::getZeroMotionConfig()
{
MPU_ERR_CHECK(readBytes(regs::ZRMOTION_THR, 2, buffer));
zrmot_config_t config{};
config.threshold = buffer[0];
config.time = buffer[1];
return config;
}
/**
* @brief Configure Free-Fall.
*
* Free fall is detected by checking if the accelerometer measurements from all 3 axes have an
* absolute value below a user-programmable threshold (acceleration threshold). For each sample
* where this condition is true (a qualifying sample), a counter is incremented. For each sample
* where this condition is false (a non- qualifying sample), the counter is decremented. Once the
* counter reaches a user-programmable threshold (the counter threshold), the Free Fall interrupt is
* triggered and a flag is set. The flag is cleared once the counter has decremented to zero. The
* counter does not increment above the counter threshold or decrement below zero.
*
* @note Enable by calling setMotionFeatureEnabled().
* */
esp_err_t MPU::setFreeFallConfig(ff_config_t& config)
{
buffer[0] = config.threshold;
buffer[1] = config.time;
if (MPU_ERR_CHECK(writeBytes(regs::FF_THR, 2, buffer))) return err;
if (MPU_ERR_CHECK(writeBits(regs::MOTION_DETECT_CTRL, regs::MOTCTRL_ACCEL_ON_DELAY_BIT,
regs::MOTCTRL_ACCEL_ON_DELAY_LENGTH, config.accel_on_delay))) {
return err;
}
if (MPU_ERR_CHECK(writeBits(regs::MOTION_DETECT_CTRL, regs::MOTCTRL_MOT_COUNT_BIT, regs::MOTCTRL_MOT_COUNT_LENGTH,
config.counter))) {
return err;
}
return err;
}
/**
* @brief Return Free-Fall Configuration.
*/
ff_config_t MPU::getFreeFallConfig()
{
ff_config_t config{};
MPU_ERR_CHECK(readBytes(regs::FF_THR, 2, buffer));
config.threshold = buffer[0];
config.time = buffer[1];
MPU_ERR_CHECK(readByte(regs::MOTION_DETECT_CTRL, buffer));
config.accel_on_delay =
(buffer[0] >> (regs::MOTCTRL_ACCEL_ON_DELAY_BIT - regs::MOTCTRL_ACCEL_ON_DELAY_LENGTH + 1)) & 0x3;
config.counter =
(mot_counter_t)((buffer[0] >> (regs::MOTCTRL_MOT_COUNT_BIT - regs::MOTCTRL_MOT_COUNT_LENGTH + 1)) & 0x3);
return config;
}
/**
* @brief Return Motion Detection Status.
* @note Reading this register clears all motion detection status bits.
* */
mot_stat_t MPU::getMotionDetectStatus()
{
MPU_ERR_CHECK(readByte(regs::MOTION_DETECT_STATUS, buffer));
return (mot_stat_t) buffer[0];
}
#endif // MPU6050's stuff
/**
* @brief Configure sensors' standby mode.
* */
esp_err_t MPU::setStandbyMode(stby_en_t mask)
{
const uint8_t kPwr1StbyBits = mask >> 6;
if (MPU_ERR_CHECK(writeBits(regs::PWR_MGMT1, regs::PWR1_GYRO_STANDBY_BIT, 2, kPwr1StbyBits))) {
return err;
}
return MPU_ERR_CHECK(writeBits(regs::PWR_MGMT2, regs::PWR2_STBY_XA_BIT, 6, mask));
}
/**
* @brief Return Standby configuration.
* */
stby_en_t MPU::getStandbyMode()
{
MPU_ERR_CHECK(readBytes(regs::PWR_MGMT1, 2, buffer));
constexpr uint8_t kStbyTempAndGyroPLLBits = STBY_EN_TEMP | STBY_EN_LOWPWR_GYRO_PLL_ON;
stby_en_t mask = buffer[0] << 3 & kStbyTempAndGyroPLLBits;
constexpr uint8_t kStbyAccelAndGyroBits = STBY_EN_ACCEL | STBY_EN_GYRO;
mask |= buffer[1] & kStbyAccelAndGyroBits;
return mask;
}
#ifdef CONFIG_MPU6500
/**
* @brief Select FCHOICE.
*
* Dev note: FCHOICE is the inverted value of FCHOICE_B (e.g. FCHOICE=2b’00 is same as FCHOICE_B=2b’11).
* Reset value is FCHOICE_3
* */
esp_err_t MPU::setFchoice(fchoice_t fchoice)
{
buffer[0] = (~(fchoice) &0x3); // invert to fchoice_b
if (MPU_ERR_CHECK(
writeBits(regs::GYRO_CONFIG, regs::GCONFIG_FCHOICE_B, regs::GCONFIG_FCHOICE_B_LENGTH, buffer[0]))) {
return err;
}
return MPU_ERR_CHECK(writeBit(regs::ACCEL_CONFIG2, regs::ACONFIG2_ACCEL_FCHOICE_B_BIT, (buffer[0] == 0) ? 0 : 1));
}
/**
* @brief Return FCHOICE.
*/
fchoice_t MPU::getFchoice()
{
MPU_ERR_CHECK(readBits(regs::GYRO_CONFIG, regs::GCONFIG_FCHOICE_B, regs::GCONFIG_FCHOICE_B_LENGTH, buffer));
return (fchoice_t)(~(buffer[0]) & 0x3);
}
#endif
/**
* @brief Select Gyroscope Full-scale range.
* */
esp_err_t MPU::setGyroFullScale(gyro_fs_t fsr)
{
return MPU_ERR_CHECK(writeBits(regs::GYRO_CONFIG, regs::GCONFIG_FS_SEL_BIT, regs::GCONFIG_FS_SEL_LENGTH, fsr));
}
/**
* @brief Return Gyroscope Full-scale range.
*/
gyro_fs_t MPU::getGyroFullScale()
{
MPU_ERR_CHECK(readBits(regs::GYRO_CONFIG, regs::GCONFIG_FS_SEL_BIT, regs::GCONFIG_FS_SEL_LENGTH, buffer));
return (gyro_fs_t) buffer[0];
}
/**
* @brief Select Accelerometer Full-scale range.
* */
esp_err_t MPU::setAccelFullScale(accel_fs_t fsr)
{
return MPU_ERR_CHECK(writeBits(regs::ACCEL_CONFIG, regs::ACONFIG_FS_SEL_BIT, regs::ACONFIG_FS_SEL_LENGTH, fsr));
}
/**
* @brief Return Accelerometer Full-scale range.
*/
accel_fs_t MPU::getAccelFullScale()
{
MPU_ERR_CHECK(readBits(regs::ACCEL_CONFIG, regs::ACONFIG_FS_SEL_BIT, regs::ACONFIG_FS_SEL_LENGTH, buffer));
return (accel_fs_t) buffer[0];
}
/**
* @brief Push biases to the gyro offset registers.
*
* This function expects biases relative to the current sensor output, and
* these biases will be added to the factory-supplied values.
*
* Note: Bias inputs are LSB in +-1000dps format.
* */
esp_err_t MPU::setGyroOffset(raw_axes_t bias)
{
buffer[0] = (uint8_t)(bias.x >> 8);
buffer[1] = (uint8_t)(bias.x);
buffer[2] = (uint8_t)(bias.y >> 8);
buffer[3] = (uint8_t)(bias.y);
buffer[4] = (uint8_t)(bias.z >> 8);
buffer[5] = (uint8_t)(bias.z);
return MPU_ERR_CHECK(writeBytes(regs::XG_OFFSET_H, 6, buffer));
}
/**
* @brief Return biases from the gyro offset registers.
*
* Note: Bias output are LSB in +-1000dps format.
* */
raw_axes_t MPU::getGyroOffset()
{
MPU_ERR_CHECK(readBytes(regs::XG_OFFSET_H, 6, buffer));
raw_axes_t bias;
bias.x = (buffer[0] << 8) | buffer[1];
bias.y = (buffer[2] << 8) | buffer[3];
bias.z = (buffer[4] << 8) | buffer[5];
return bias;
}
/**
* @brief Push biases to the accel offset registers.
*
* This function expects biases relative to the current sensor output, and
* these biases will be added to the factory-supplied values.
*
* Note: Bias inputs are LSB in +-16G format.
* */
esp_err_t MPU::setAccelOffset(raw_axes_t bias)
{
raw_axes_t facBias;
// first, read OTP values of Accel factory trim
#if defined CONFIG_MPU6050
if (MPU_ERR_CHECK(readBytes(regs::XA_OFFSET_H, 6, buffer))) return err;
facBias.x = (buffer[0] << 8) | buffer[1];
facBias.y = (buffer[2] << 8) | buffer[3];
facBias.z = (buffer[4] << 8) | buffer[5];
#elif defined CONFIG_MPU6500
if (MPU_ERR_CHECK(readBytes(regs::XA_OFFSET_H, 8, buffer))) return err;
// note: buffer[2] and buffer[5], stay the same,
// they are read just to keep the burst reading
facBias.x = (buffer[0] << 8) | buffer[1];
facBias.y = (buffer[3] << 8) | buffer[4];
facBias.z = (buffer[6] << 8) | buffer[7];
#endif
// note: preserve bit 0 of factory value (for temperature compensation)
facBias.x += (bias.x & ~1);
facBias.y += (bias.y & ~1);
facBias.z += (bias.z & ~1);
#if defined CONFIG_MPU6050
buffer[0] = (uint8_t)(facBias.x >> 8);
buffer[1] = (uint8_t)(facBias.x);
buffer[2] = (uint8_t)(facBias.y >> 8);
buffer[3] = (uint8_t)(facBias.y);
buffer[4] = (uint8_t)(facBias.z >> 8);
buffer[5] = (uint8_t)(facBias.z);
if (MPU_ERR_CHECK(writeBytes(regs::XA_OFFSET_H, 6, buffer))) return err;
#elif defined CONFIG_MPU6500
buffer[0] = (uint8_t)(facBias.x >> 8);
buffer[1] = (uint8_t)(facBias.x);
buffer[3] = (uint8_t)(facBias.y >> 8);
buffer[4] = (uint8_t)(facBias.y);
buffer[6] = (uint8_t)(facBias.z >> 8);
buffer[7] = (uint8_t)(facBias.z);
return MPU_ERR_CHECK(writeBytes(regs::XA_OFFSET_H, 8, buffer));
#endif
return err;
}
/**
* @brief Return biases from accel offset registers.
* This returns the biases with OTP values from factory trim added,
* so returned values will be different than that ones set with setAccelOffset().
*
* Note: Bias output are LSB in +-16G format.
* */
raw_axes_t MPU::getAccelOffset()
{
raw_axes_t bias;
#if defined CONFIG_MPU6050
MPU_ERR_CHECK(readBytes(regs::XA_OFFSET_H, 6, buffer));
bias.x = (buffer[0] << 8) | buffer[1];
bias.y = (buffer[2] << 8) | buffer[3];
bias.z = (buffer[4] << 8) | buffer[5];
#elif defined CONFIG_MPU6500
MPU_ERR_CHECK(readBytes(regs::XA_OFFSET_H, 8, buffer));
bias.x = (buffer[0] << 8) | buffer[1];
bias.y = (buffer[3] << 8) | buffer[4];
bias.z = (buffer[6] << 8) | buffer[7];
#endif
return bias;
}
/**
* @brief Compute Accelerometer and Gyroscope offsets.
*
* This takes about ~400ms to compute offsets.
* When calculating the offsets the MPU must remain as horizontal as possible (0 degrees), facing
* up. It is better to call computeOffsets() before any configuration is done (better right after
* initialize()).
*
* Note: Gyro offset output are LSB in 1000DPS format.
* Note: Accel offset output are LSB in 16G format.
* */
esp_err_t MPU::computeOffsets(raw_axes_t* accel, raw_axes_t* gyro)
{
constexpr accel_fs_t kAccelFS = ACCEL_FS_2G; // most sensitive
constexpr gyro_fs_t kGyroFS = GYRO_FS_250DPS; // most sensitive
if (MPU_ERR_CHECK(getBiases(kAccelFS, kGyroFS, accel, gyro, false))) return err;
// convert offsets to 16G and 1000DPS format and invert values
for (int i = 0; i < 3; i++) {
(*accel)[i] = -((*accel)[i] >> (types::ACCEL_FS_16G - kAccelFS));
(*gyro)[i] = -((*gyro)[i] >> (types::GYRO_FS_1000DPS - kGyroFS));
}
return err;
}
/**
* @brief Read accelerometer raw data.
* */
esp_err_t MPU::acceleration(raw_axes_t* accel)
{
if (MPU_ERR_CHECK(readBytes(regs::ACCEL_XOUT_H, 6, buffer))) return err;
accel->x = buffer[0] << 8 | buffer[1];
accel->y = buffer[2] << 8 | buffer[3];
accel->z = buffer[4] << 8 | buffer[5];
return err;
}
/**
* @brief Read accelerometer raw data.
* */
esp_err_t MPU::acceleration(int16_t* x, int16_t* y, int16_t* z)
{
if (MPU_ERR_CHECK(readBytes(regs::ACCEL_XOUT_H, 6, buffer))) return err;
*x = buffer[0] << 8 | buffer[1];
*y = buffer[2] << 8 | buffer[3];
*z = buffer[4] << 8 | buffer[5];
return err;
}
/**
* @brief Read gyroscope raw data.
* */
esp_err_t MPU::rotation(raw_axes_t* gyro)
{
if (MPU_ERR_CHECK(readBytes(regs::GYRO_XOUT_H, 6, buffer))) return err;
gyro->x = buffer[0] << 8 | buffer[1];
gyro->y = buffer[2] << 8 | buffer[3];
gyro->z = buffer[4] << 8 | buffer[5];
return err;
}
/**
* @brief Read gyroscope raw data.
* */
esp_err_t MPU::rotation(int16_t* x, int16_t* y, int16_t* z)
{
if (MPU_ERR_CHECK(readBytes(regs::GYRO_XOUT_H, 6, buffer))) return err;
*x = buffer[0] << 8 | buffer[1];
*y = buffer[2] << 8 | buffer[3];
*z = buffer[4] << 8 | buffer[5];
return err;
}
/**
* Read temperature raw data.
* */
esp_err_t MPU::temperature(int16_t* temp)
{
if (MPU_ERR_CHECK(readBytes(regs::TEMP_OUT_H, 2, buffer))) return err;
*temp = buffer[0] << 8 | buffer[1];
return err;
}
/**
* @brief Read accelerometer and gyroscope data at once.
* */
esp_err_t MPU::motion(raw_axes_t* accel, raw_axes_t* gyro)
{
if (MPU_ERR_CHECK(readBytes(regs::ACCEL_XOUT_H, 14, buffer))) return err;
accel->x = buffer[0] << 8 | buffer[1];
accel->y = buffer[2] << 8 | buffer[3];
accel->z = buffer[4] << 8 | buffer[5];
gyro->x = buffer[8] << 8 | buffer[9];
gyro->y = buffer[10] << 8 | buffer[11];
gyro->z = buffer[12] << 8 | buffer[13];
return err;
}
#if defined CONFIG_MPU_AK89xx
/**
* @brief Read compass data.
* */
esp_err_t MPU::heading(raw_axes_t* mag)
{
if (MPU_ERR_CHECK(readBytes(regs::EXT_SENS_DATA_01, 6, buffer))) return err;
mag->x = buffer[1] << 8 | buffer[0];
mag->y = buffer[3] << 8 | buffer[2];
mag->z = buffer[5] << 8 | buffer[4];
return err;