forked from ZHomeSlice/Simple_MPU6050
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Simple_MPU6050.cpp
1653 lines (1428 loc) · 64.7 KB
/
Simple_MPU6050.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
#include <Wire.h>
#include <I2Cdev.h>
#include "DMP_Image.h"
#include "Simple_MPU6050.h"
#include "MPU_ReadMacros.h"
#include "MPU_WriteMacros.h"
//#define USE_OLD_GETYAWPITCHROLL // Calculation returns different values but possibly relevant for your project Try both out
// OLD Yaw +- 180, Pitch and Roll +- 90 (Peaks at 90 deg then fall back to zero, shows Negative when pointing down pitch and left roll)
// NEW Yaw +- 180, Pitch and Roll +- 180 (Continues to 180 deg then -180 back to zero, shows Negative when pointing down pitch and left roll)
#define MPU6050_ADDRESS_AD0_LOW 0x68 // address pin low (GND), default for InvenSense evaluation board
#define MPU6050_ADDRESS_AD0_HIGH 0x69 // address pin high (VCC)
#define MPU6050_DEFAULT_ADDRESS MPU6050_ADDRESS_AD0_LOW
volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has changed
volatile uint8_t _maxPackets;
/**
@brief Initialization functions
*/
Simple_MPU6050::Simple_MPU6050() {
SetAddress(MPU6050_DEFAULT_ADDRESS);
packet_length = 28;
/*
packet_length += 6;//DMP_FEATURE_SEND_RAW_ACCEL
packet_length += 6;//DMP_FEATURE_SEND_RAW_GYRO
packet_length += 16;//DMP_FEATURE_6X_LP_QUAT
*/
_maxPackets = floor(512 / packet_length); // MPU 9250 can only handle 512 bytes of data in the FIFO
}
Simple_MPU6050 & Simple_MPU6050::SetAddress(uint8_t address) {
devAddr = address;
return *this;
}
uint8_t Simple_MPU6050::CheckAddress() {
return devAddr;
}
/**
@brief Set FIFO Callback
*/
Simple_MPU6050 & Simple_MPU6050::on_FIFO(void (*CB)(int16_t *, int16_t *, int32_t *, uint32_t *)) {
on_FIFO_cb = CB;
return *this; // return Pointer to this class
}
/**
@brief Reset funnctions
*/
Simple_MPU6050 & Simple_MPU6050::reset_fifo() {
USER_CTRL_WRITE_FIFO_RST(); // Reset FIFO module. Reset is asynchronous. This bit auto clears after one clock cycle.
return *this;
}
Simple_MPU6050 & Simple_MPU6050::full_reset_fifo(void) { // Official way to reset fifo
USER_CTRL_WRITE_RESET_FIFO_DMP();
return *this;
}
/**
@brief Start and Stop DMP int pin triggering // 1 Enable, 0 = Disable
*/
Simple_MPU6050 & Simple_MPU6050::DMP_InterruptEnable(uint8_t Data) {
INT_ENABLE_WRITE_RAW_DMP_INT_EN(Data);
dmp_on = Data;
return *this;
};
//***************************************************************************************
//********************** Overflow Protection functions **********************
//***************************************************************************************
/**
@brief manages properly testing interrupt trigger from interrupt pin
*/
uint8_t Simple_MPU6050::CheckForInterrupt(void) {
uint8_t InteruptTriggered;
noInterrupts ();
InteruptTriggered = mpuInterrupt;
mpuInterrupt = false;
interrupts ();
return InteruptTriggered;
}
/**
@brief During the Dreded delay() using yield() limit the fifo packets to 10 less than max packets
*/
void Simple_MPU6050::OverflowProtection(void) {
uint32_t Timestamp ;
Timestamp = millis();
static uint32_t spamtimer;
if ((Timestamp - spamtimer) >= 30) {
spamtimer = Timestamp;
uint16_t fifo_count;
int8_t Packets;
FIFO_COUNTH_READ_FIFO_CNT(&fifo_count);
Packets = (fifo_count / packet_length) - (_maxPackets - 10); // Leaves room for 2 more readings
if (Packets <= 0)return;
uint8_t trash[packet_length + 1] ;
while (0 < Packets--) {
FIFO_READ(packet_length, trash);
}
}
}
//***************************************************************************************
//********************** FIFO functions **********************
//***************************************************************************************
/**
@brief Reads Newest packet from fifo then on success triggers Callback routine
*/
Simple_MPU6050 & Simple_MPU6050::dmp_read_fifo(uint8_t CheckInterrupt = 1) {
if (CheckInterrupt && !CheckForInterrupt()) return *this;
if (!dmp_read_fifo(gyro, accel, quat, sensor_timestamp)) {
return *this;
}
if (on_FIFO_cb) on_FIFO_cb(gyro, accel, quat, sensor_timestamp);
return *this;
}
int16_t Simple_MPU6050::getFIFOCount(){
int16_t fifo_count;
FIFO_COUNTH_READ_FIFO_CNT(&fifo_count);
return (fifo_count);
}
/** Get latest byte from FIFO buffer no matter how much time has passed.
* === GetCurrentFIFOPacket ===
* ================================================================
* Returns 1) when nothing special was done
* 0) when no valid data is available
* ================================================================ */
int8_t Simple_MPU6050::GetCurrentFIFOPacket(uint8_t *data, uint8_t length) { // overflow proof
int16_t fifoC;
// This section of code is for when we allowed more than 1 packet to be acquired
uint32_t BreakTimer = micros();
do {
if ((fifoC = getFIFOCount()) > length) {
if (fifoC > 200) { // if you waited to get the FIFO buffer to > 200 bytes it will take longer to get the last packet in the FIFO Buffer than it will take to reset the buffer and wait for the next to arrive
USER_CTRL_WRITE_FIFO_RST(); // Fixes any overflow corruption
fifoC = 0;
while (!(fifoC = getFIFOCount()) && ((micros() - BreakTimer) <= (11000))); // Get Next New Packet
} else { //We have more than 1 packet but less than 200 bytes of data in the FIFO Buffer
uint8_t Trash[BUFFER_LENGTH];
while ((fifoC = getFIFOCount()) > length) { // Test each time just in case the MPU is writing to the FIFO Buffer
fifoC = fifoC - length; // Save the last packet
uint16_t RemoveBytes;
while (fifoC) { // fifo count will reach zero so this is safe
RemoveBytes = min((int)fifoC, BUFFER_LENGTH); // Buffer Length is different than the packet length this will efficiently clear the buffer
// getFIFOBytes(Trash, (uint8_t)RemoveBytes);
FIFO_READ((uint8_t)RemoveBytes, Trash);
fifoC -= RemoveBytes;
}
}
}
}
if (!fifoC) return 0; // Called too early no data or we timed out after FIFO Reset
// We have 1 packet
if ((micros() - BreakTimer) > (11000)) return 0;
} while (fifoC != length);
FIFO_READ((uint8_t)length, data); //Get 1 packet
// getFIFOBytes(data, length); //Get 1 packet
return 1;
}
/**
@brief Get the Newest packet from the FIFO. FIFO Buffer will be empty awaiting for next packet
*/
uint8_t Simple_MPU6050::dmp_read_fifo(int16_t *gyro, int16_t *accel, int32_t *quat, uint32_t *timestamp) {
/* Get a packet. */
uint8_t fifo_data[MAX_PACKET_LENGTH];
if(GetCurrentFIFOPacket(fifo_data, packet_length)){
// FIFO_READ(packet_length, fifo_data);
timestamp = micros();
// fifo_count -= packet_length;
/* Parse DMP packet. */
uint8_t ii = 0;
quat[0] = ((int32_t)fifo_data[0] << 24) | ((int32_t)fifo_data[1] << 16) | ((int32_t)fifo_data[2] << 8) | fifo_data[3];
quat[1] = ((int32_t)fifo_data[4] << 24) | ((int32_t)fifo_data[5] << 16) | ((int32_t)fifo_data[6] << 8) | fifo_data[7];
quat[2] = ((int32_t)fifo_data[8] << 24) | ((int32_t)fifo_data[9] << 16) | ((int32_t)fifo_data[10] << 8) | fifo_data[11];
quat[3] = ((int32_t)fifo_data[12] << 24) | ((int32_t)fifo_data[13] << 16) | ((int32_t)fifo_data[14] << 8) | fifo_data[15];
ii += 16;
accel[0] = ((int16_t)fifo_data[ii + 0] << 8) | fifo_data[ii + 1];
accel[1] = ((int16_t)fifo_data[ii + 2] << 8) | fifo_data[ii + 3];
accel[2] = ((int16_t)fifo_data[ii + 4] << 8) | fifo_data[ii + 5];
ii += 6;
gyro[0] = ((int16_t)fifo_data[ii + 0] << 8) | fifo_data[ii + 1];
gyro[1] = ((int16_t)fifo_data[ii + 2] << 8) | fifo_data[ii + 3];
gyro[2] = ((int16_t)fifo_data[ii + 4] << 8) | fifo_data[ii + 5];
return 1;
}
return 0;
}
//***************************************************************************************
//********************** i2cdev wrapper functions **********************
//***************************************************************************************
// I did this to simplify managing all the macros found in MPU_ReadMacros.h and MPU_WriteMacros.h
// Wrappered I2Cdev read functions
Simple_MPU6050 & Simple_MPU6050::MPUi2cRead(uint8_t regAddr, uint8_t length, uint8_t bitNum, uint8_t *Data) {
return MPUi2cRead( devAddr, regAddr, length, bitNum, Data);
}
Simple_MPU6050 & Simple_MPU6050::MPUi2cRead(uint8_t AltAddress, uint8_t regAddr, uint8_t length, uint8_t bitNum, uint8_t *Data) {
if(length == 1) I2CReadCount = readBit(AltAddress, regAddr, bitNum, Data);
else I2CReadCount = readBits(AltAddress, regAddr, bitNum, length, Data);
return *this;
}
// MPUi2cReadBytes
Simple_MPU6050 & Simple_MPU6050::MPUi2cReadByte(uint8_t regAddr, uint8_t *Data) {
I2CReadCount = readBytes(devAddr, regAddr, 1, Data);
return *this;
}
Simple_MPU6050 & Simple_MPU6050::MPUi2cReadByte(uint8_t AltAddress,uint8_t regAddr, uint8_t *Data) {
I2CReadCount = readBytes(AltAddress, regAddr, 1, Data);
return *this;
}
Simple_MPU6050 & Simple_MPU6050::MPUi2cReadBytes(uint8_t regAddr, uint8_t length, uint8_t *Data) {
I2CReadCount = readBytes(devAddr, regAddr, length, Data);
return *this;
}
Simple_MPU6050 & Simple_MPU6050::MPUi2cReadBytes(uint8_t AltAddress,uint8_t regAddr, uint8_t length, uint8_t *Data) {
I2CReadCount = readBytes(AltAddress, regAddr, length, Data);
return *this;
}
// MPUi2cReadInt or Word
Simple_MPU6050 & Simple_MPU6050::MPUi2cReadInt(uint8_t regAddr, uint16_t *Data) {
I2CReadCount = readWords(devAddr, regAddr, 1, Data); // reads 1 or more 16 bit integers (Word)
return *this;
}
Simple_MPU6050 & Simple_MPU6050::MPUi2cReadInt(uint8_t AltAddress,uint8_t regAddr, uint16_t *Data) {
I2CReadCount = readWords(AltAddress, regAddr, 1, Data); // reads 1 or more 16 bit integers (Word)
return *this;
}
// MPUi2cReadInts or Words
Simple_MPU6050 & Simple_MPU6050::MPUi2cReadInts(uint8_t regAddr, uint16_t size, uint16_t *Data) {
I2CReadCount = readWords(devAddr, regAddr, size, Data); // reads 1 or more 16 bit integers (Word)
return *this;
}
Simple_MPU6050 & Simple_MPU6050::MPUi2cReadInts(uint8_t AltAddress,uint8_t regAddr, uint16_t size, uint16_t *Data) {
I2CReadCount = readWords(AltAddress, regAddr, size, Data); // reads 1 or more 16 bit integers (Word)
return *this;
}
// Wrappered I2Cdev write functions
// MPUi2cWrite
Simple_MPU6050 & Simple_MPU6050::MPUi2cWrite(uint8_t regAddr, uint8_t length, uint8_t bitNum, uint8_t Val) {
return MPUi2cWrite(devAddr, regAddr, length, bitNum, Val);
}
Simple_MPU6050 & Simple_MPU6050::MPUi2cWrite(uint8_t AltAddress,uint8_t regAddr, uint8_t length, uint8_t bitNum, uint8_t Val) {
if (length == 1) {
I2CWriteStatus = writeBit(AltAddress, regAddr, bitNum, &Val); // Alters 1 bit by reading the byte making a change and storing the byte (faster than writeBits)
}
else if (bitNum != 255) {
I2CWriteStatus = writeBits(AltAddress, regAddr, bitNum, length, &Val); // Alters several bits by reading the byte making a change and storing the byte
}
return *this;
}
// MPUi2cWriteByte
Simple_MPU6050 & Simple_MPU6050::MPUi2cWriteByte(uint8_t regAddr, uint8_t Val) {
I2CWriteStatus = writeBytes(devAddr, regAddr, 1, &Val); //Writes 1 or more 8 bit Bytes
return *this;
}
Simple_MPU6050 & Simple_MPU6050::MPUi2cWriteByte(uint8_t AltAddress,uint8_t regAddr, uint8_t Val) {
I2CWriteStatus = writeBytes(AltAddress, regAddr, 1, &Val); //Writes 1 or more 8 bit Bytes
return *this;
}
// MPUi2cWriteBytes
Simple_MPU6050 & Simple_MPU6050::MPUi2cWriteBytes(uint8_t regAddr, uint8_t length, uint8_t *Data) {
I2CWriteStatus = writeBytes(devAddr, regAddr, length, Data); //Writes 1 or more 8 bit Bytes
return *this;
}
Simple_MPU6050 & Simple_MPU6050::MPUi2cWriteBytes(uint8_t AltAddress,uint8_t regAddr, uint8_t length, uint8_t *Data) {
I2CWriteStatus = writeBytes(AltAddress, regAddr, length, Data); //Writes 1 or more 8 bit Bytes
return *this;
}
// MPUi2cWriteInt
Simple_MPU6050 & Simple_MPU6050::MPUi2cWriteInt(uint8_t regAddr, uint16_t Val) {
I2CWriteStatus = writeWords(devAddr, regAddr, 1, &Val);// Writes 1 or more 16 bit integers (Word)
return *this;
}
Simple_MPU6050 & Simple_MPU6050::MPUi2cWriteInt(uint8_t AltAddress,uint8_t regAddr, uint16_t Val) {
I2CWriteStatus = writeWords(AltAddress, regAddr, 1, &Val);// Writes 1 or more 16 bit integers (Word)
return *this;
}
// MPUi2cWriteInts
Simple_MPU6050 & Simple_MPU6050::MPUi2cWriteInts(uint8_t regAddr, uint16_t size, uint16_t *Data) {
I2CWriteStatus = writeWords(devAddr, regAddr, size / 2, Data);
return *this;
}
Simple_MPU6050 & Simple_MPU6050::MPUi2cWriteInts(uint8_t AltAddress,uint8_t regAddr, uint16_t size, uint16_t *Data) {
I2CWriteStatus = writeWords(AltAddress, regAddr, size / 2, Data);
return *this;
}
//***************************************************************************************
//********************** Firmwaer Read Write Functions **********************
//***************************************************************************************
/**
@brief Read and Write to the DMP FIRMWARE memory. using these functions alters the firmware instance
*/
Simple_MPU6050 & Simple_MPU6050::read_mem(uint16_t mem_addr, uint16_t length, uint8_t *Data) {
BANK_SEL_WRITE(mem_addr);
DMP_MEM_READ(length, Data);
return *this;
} Simple_MPU6050 & Simple_MPU6050::write_mem(uint16_t mem_addr, uint16_t length, uint8_t *Data) {
BANK_SEL_WRITE(mem_addr);
DMP_MEM_WRITE(length, Data);
return *this;
}
//***************************************************************************************
//********************** Setup Functions **********************
//***************************************************************************************
/**
@brief ***EVERYTHING!*** needed to get DMP up and running!
*/
Simple_MPU6050 & Simple_MPU6050::load_DMP_Image(int16_t ax_, int16_t ay_, int16_t az_, int16_t gx_, int16_t gy_, int16_t gz_,int8_t Calibrate) {
sax_ = ax_;
say_ = ay_;
saz_ = az_;
sgx_ = gx_;
sgy_ = gy_;
sgz_ = gz_;
load_DMP_Image();
return *this;
}
#define CompassCheck(Cnt) {uint8_t D; Serial.print(F("\n")); Serial.print(Cnt); Serial.print(F(" Read AKM Who am I: ")); Serial.print(I2Cdev::readBytes(0x0C,0,1,&D));Serial.print(F(" Value = 0x"));Serial.println(D);}
//#define PWR_MGMT_1_WRITE_DEVICE_RESET(...) MPUi2cWrite(0x6B, 1, 7, 1);delay(100);MPUi2cWrite(0x6A, 4, 3, 0b1111);delay(100); // 1 Reset the internal registers and restores the default settings. Write a 1 to set the reset, the bit will auto clear.
Simple_MPU6050 & Simple_MPU6050::load_DMP_Image(uint8_t CalibrateMode) {
uint8_t val;
TestConnection(1);
Serial.println();
PWR_MGMT_1_WRITE_DEVICE_RESET(); //PWR_MGMT_1:(0x6B Bit7 true) reset with 100ms delay and full SIGNAL_PATH_RESET:(0x6A Bits 3,2,1,0 True) with another 100ms delay
/* instruction suggest this sequence
MPUi2cWriteByte(0x6B, 0x00);
MPUi2cWriteByte(0x6C, 0x00);
MPUi2cWriteByte(0x1A, 0x03);
MPUi2cWriteByte(0x1B, 0x18);
MPUi2cWriteByte(0x1C, 0x00);
MPUi2cWriteByte(0x23, 0x00);
MPUi2cWriteByte(0x38, 0x00);
MPUi2cWriteByte(0x6A, 0x04);
MPUi2cWriteByte(0x19, 0x04);
if(!CalibrateMode){
load_firmware(DMP_CODE_SIZE, dmp_memory); // Loads the DMP image into the MPU6050 Memory
MPUi2cWriteInt(0x70, 0x0400); // DMP Program Start Address
}
MPUi2cWriteByte(0x6A, 0x40);
MPUi2cWriteByte(0x6A, 0x04);
MPUi2cWriteByte(0x6A, 0x80);
MPUi2cWriteByte(0x6A, 0x08);
MPUi2cWriteByte(0x38, 0x02);
*/
MPUi2cWriteByte(0x6B, 0x00);
MPUi2cWriteByte(0x6C, 0x00);
MPUi2cWriteByte(0x1A, 0x03);
MPUi2cWriteByte(0x1B, 0x18);
MPUi2cWriteByte(0x1C, 0x00);
MPUi2cWriteByte(0x23, 0x00);
MPUi2cWriteByte(0x38, 0x00);
MPUi2cWriteByte(0x6A, 0x04);
MPUi2cWriteByte(0x19, 0x04);
if(!CalibrateMode){
load_firmware(DMP_CODE_SIZE, dmp_memory); // Loads the DMP image into the MPU6050 Memory
MPUi2cWriteInt(0x70, 0x0400); // DMP Program Start Address
}
resetOffset(); // Load Calibration offset values into MPU
if(CalibrateMode)return;
PrintActiveOffsets();
AKM_Init();
MPUi2cWriteByte(0x6A, 0xC0); // 1100 1100 USER_CTRL: Enable FIFO and Reset FIFO
MPUi2cWriteByte(0x38, 0x02); // 0000 0010 INT_ENABLE: RAW_DMP_INT_EN on
/*
MPUi2cWriteByte(0x6B, 0x01); // 0000 0001 PWR_MGMT_1:Clock Source Select PLL_X_gyro
MPUi2cWriteByte(0x38, 0x00); // 0000 0000 INT_ENABLE: no Interrupt
MPUi2cWriteByte(0x23, 0x00); // 0000 0000 MPU FIFO_EN: (all off) Using DMP's FIFO instead
MPUi2cWriteByte(0x1C, 0x00); // 0000 0000 ACCEL_CONFIG: 0 = Accel Full Scale Select: 2g
// MPUi2cWriteByte(0x37, 0x22); // 0010 0010 INT_PIN_CFG: ACTL The logic level for int pin is active low. and interrupt status bits are cleared on any read
MPUi2cWriteByte(0x37, 0x32); // 0010 0010 INT_PIN_CFG: ACTL The logic level for int pin is active low. and interrupt status bits are cleared on any read
MPUi2cWriteByte(0x6B, 0x01); // 0000 0001 PWR_MGMT_1: Clock Source Select PLL_X_gyro
MPUi2cWriteByte(0x19, 0x04); // 0000 0100 SMPLRT_DIV: Divides the internal sample rate 400Hz ( Sample Rate = Gyroscope Output Rate / (1 + SMPLRT_DIV))
MPUi2cWriteByte(0x1A, 0x01); // 0000 0001 CONFIG: Digital Low Pass Filter (DLPF) Configuration 188HZ //Im betting this will be the beat
if(!CalibrateMode){
load_firmware(DMP_CODE_SIZE, dmp_memory); // Loads the DMP image into the MPU6050 Memory
MPUi2cWriteInt(0x70, 0x0400); // DMP Program Start Address
}
MPUi2cWriteByte(0x1B, 0x18); // 0001 1000 GYRO_CONFIG: 3 = +2000 Deg/sec
resetOffset(); // Load Calibration offset values into MPU
if(CalibrateMode)return;
PrintActiveOffsets();
AKM_Init();
MPUi2cWriteByte(0x6A, 0xC0); // 1100 1100 USER_CTRL: Enable FIFO and Reset FIFO
MPUi2cWriteByte(0x38, 0x02); // 0000 0010 INT_ENABLE: RAW_DMP_INT_EN on
MPUi2cWrite(0x6A, 1, 2, 1); // Reset FIFO one last time just for kicks. (MPUi2cWrite reads 0x6A first and only alters 1 byte and then saves the byte)
*/
dmp_on = 1;
#ifdef interruptPin
attachInterrupt(digitalPinToInterrupt(interruptPin), [] {mpuInterrupt = true;}, RISING); //NOTE: "[]{mpuInterrupt = true;}" Is a complete funciton without a name. It is handed to the callback of attachInterrupts Google: "Lambda anonymous functions"
#endif
//These are the features the above code initialized for you by default (ToDo Allow removal of one or more Features)
dmp_features = DMP_FEATURE_6X_LP_QUAT | DMP_FEATURE_SEND_RAW_ACCEL | DMP_FEATURE_SEND_RAW_GYRO | DMP_FEATURE_SEND_CAL_GYRO; // These are Fixed into the DMP_Image and Can't be change easily at this time.
return *this;
}
/*
Simple_MPU6050 & Simple_MPU6050::load_DMP_Image(uint8_t CalibrateMode) {
uint8_t val;
TestConnection(1);
Serial.println();
PWR_MGMT_1_WRITE_DEVICE_RESET(); //PWR_MGMT_1:(0x6B Bit7 true) reset with 100ms delay and full SIGNAL_PATH_RESET:(0x6A Bits 3,2,1,0 True) with another 100ms delay
MPUi2cWriteByte(0x6B, 0x01); // 0000 0001 PWR_MGMT_1:Clock Source Select PLL_X_gyro
MPUi2cWriteByte(0x38, 0x00); // 0000 0000 INT_ENABLE: no Interrupt
MPUi2cWriteByte(0x23, 0x00); // 0000 0000 MPU FIFO_EN: (all off) Using DMP's FIFO instead
MPUi2cWriteByte(0x1C, 0x00); // 0000 0000 ACCEL_CONFIG: 0 = Accel Full Scale Select: 2g
// MPUi2cWriteByte(0x37, 0x22); // 0010 0010 INT_PIN_CFG: ACTL The logic level for int pin is active low. and interrupt status bits are cleared on any read
MPUi2cWriteByte(0x37, 0x32); // 0010 0010 INT_PIN_CFG: ACTL The logic level for int pin is active low. and interrupt status bits are cleared on any read
MPUi2cWriteByte(0x6B, 0x01); // 0000 0001 PWR_MGMT_1: Clock Source Select PLL_X_gyro
MPUi2cWriteByte(0x19, 0x04); // 0000 0100 SMPLRT_DIV: Divides the internal sample rate 400Hz ( Sample Rate = Gyroscope Output Rate / (1 + SMPLRT_DIV))
MPUi2cWriteByte(0x1A, 0x01); // 0000 0001 CONFIG: Digital Low Pass Filter (DLPF) Configuration 188HZ //Im betting this will be the beat
if(!CalibrateMode){
load_firmware(DMP_CODE_SIZE, dmp_memory); // Loads the DMP image into the MPU6050 Memory
MPUi2cWriteInt(0x70, 0x0400); // DMP Program Start Address
}
MPUi2cWriteByte(0x1B, 0x18); // 0001 1000 GYRO_CONFIG: 3 = +2000 Deg/sec
resetOffset(); // Load Calibration offset values into MPU
if(CalibrateMode)return;
PrintActiveOffsets();
AKM_Init();
MPUi2cWriteByte(0x6A, 0xC0); // 1100 1100 USER_CTRL: Enable FIFO and Reset FIFO
MPUi2cWriteByte(0x38, 0x02); // 0000 0010 INT_ENABLE: RAW_DMP_INT_EN on
MPUi2cWrite(0x6A, 1, 2, 1); // Reset FIFO one last time just for kicks. (MPUi2cWrite reads 0x6A first and only alters 1 byte and then saves the byte)
dmp_on = 1;
attachInterrupt(0, [] {mpuInterrupt = true;}, RISING); //NOTE: "[]{mpuInterrupt = true;}" Is a complete funciton without a name. It is handed to the callback of attachInterrupts Google: "Lambda anonymous functions"
//These are the features the above code initialized for you by default (ToDo Allow removal of one or more Features)
dmp_features = DMP_FEATURE_6X_LP_QUAT | DMP_FEATURE_SEND_RAW_ACCEL | DMP_FEATURE_SEND_RAW_GYRO | DMP_FEATURE_SEND_CAL_GYRO; // These are Fixed into the DMP_Image and Can't be change easily at this time.
return *this;
}
*/
/**
@brief ***EVERYTHING!*** needed to get DMP up and running! With Calibration!!!
*/
Simple_MPU6050 & Simple_MPU6050::CalibrateMPU(int16_t ax_, int16_t ay_, int16_t az_, int16_t gx_, int16_t gy_, int16_t gz_) {
sax_ = ax_;
say_ = ay_;
saz_ = az_;
sgx_ = gx_;
sgy_ = gy_;
sgz_ = gz_;
CalibrateMPU(10);
}
Simple_MPU6050 & Simple_MPU6050::CalibrateMPU(uint8_t Loops) {
load_DMP_Image(true);
CalibrateAccel(Loops);
CalibrateGyro(Loops);
if(!WhoAmI) WHO_AM_I_READ_WHOAMI(&WhoAmI);
if(WhoAmI < 0x38){
Serial.println(F("Found MPU6050 or MPU9150"));
XA_OFFSET_H_READ_XA_OFFS(&sax_);
YA_OFFSET_H_READ_YA_OFFS(&say_);
ZA_OFFSET_H_READ_ZA_OFFS(&saz_);
}else {
Serial.println(F("Found MPU6500 or MPU9250"));
XA_OFFSET_H_READ_0x77_XA_OFFS(&sax_);
YA_OFFSET_H_READ_0x77_YA_OFFS(&say_);
ZA_OFFSET_H_READ_0x77_ZA_OFFS(&saz_);
}
XG_OFFSET_H_READ_X_OFFS_USR(&sgx_);
YG_OFFSET_H_READ_Y_OFFS_USR(&sgy_);
ZG_OFFSET_H_READ_Z_OFFS_USR(&sgz_);
return *this;
}
/**
@brief Loads the DMP firmware.
*/
Simple_MPU6050 & Simple_MPU6050::load_firmware(uint16_t length, const uint8_t *firmware) {
static bool loaded = false;
uint16_t ii;
uint16_t this_write;
uint16_t bankNum = 0;
/* Must divide evenly into st.hw->bank_size to avoid bank crossings. */
#define LOAD_CHUNK (16)
uint8_t cur[LOAD_CHUNK], tmp[2];
uint8_t firmware_chunk[LOAD_CHUNK];
if (loaded)return *this; /* DMP should only be loaded once. */
if (!firmware) *this;
for (ii = 0; ii < length; ii += this_write) {
this_write = min(LOAD_CHUNK, length - ii);
int16_t x;
uint8_t *pFirmware = (uint8_t *)&firmware[ii];
for ( x = 0; x < this_write; x++ ) firmware_chunk[x] = pgm_read_byte_near(pFirmware + x);
write_mem(ii, this_write, firmware_chunk);
#ifdef DEBUG
// this displays the firmware by retrieving it from the MPU6050 after it was written to the serial port
read_mem(ii, this_write, cur);
if ((ii % (16 * 16)) == 0) {
Serial.print(F("/* bank # "));
Serial.print(bankNum++);
Serial.println(F(" */"));
}
for (uint16_t c = 0; c < this_write; c++) {
Serial.print(F(" 0x"));
Serial.print(Num >> 4, HEX); //Prints 0 insted of nothing when byte is less than 8
Serial.print(Num & 0X0F, HEX); // Prints the remainder of the hex number
Serial.print(F(","));
}
Serial.println();
#endif
}
#ifdef DEBUG
Serial.println();
#endif
loaded = true;
return *this;
}
/**
@brief Test to be sure we have communication to the MPU
returns 1 on success
stops or returns 0 on fail
*/
uint8_t Simple_MPU6050::TestConnection(int Stop = 1) {
byte x;
Wire.beginTransmission(CheckAddress());
if(Wire.endTransmission() != 0){
if(Stop == 2){
Serial.print(F("\nNothing at Address: 0x"));
Serial.println(CheckAddress(), HEX);
return 2;
}
}
Serial.print("Found MPU at: 0x");
Serial.println(CheckAddress(), HEX);
WHO_AM_I_READ_WHOAMI(&WhoAmI);
Serial.print(F("WhoAmI= 0x"));
Serial.println(WhoAmI, HEX);
uint16_t Device = (WhoAmI < 0x38 )? 6050:6500;
switch(Device){
case 6500:
if(Stop<0){
Serial.println("MPU6500 or MPU9250");
Serial.print(F("The connection to MPU was successful on: 0x"));
Serial.println(WhoAmI, HEX); // Bit 0 mirrors AD0 LOW HIGH state
}
break;
case 6050:
if(Stop<0){
Serial.println("MPU6050 or MPU9150");
Serial.print(F("The connection to MPU was successful on: 0x"));
Serial.println(WhoAmI, HEX); // Bit 0 mirrors AD0 LOW HIGH state
}
break;
default:
if (Stop > 0) {
Serial.println(F("\nFailed to Connect /n check connections and reset."));
while (1) {}
}
return 1;
}
return 0;
}
//***************************************************************************************
//********************** Gather Configuration from working MPU6050 **********************
//***************************************************************************************
// usage after configuration of the MPU6050 to your liking Get these registers to simplify MPU6050 startup
void Simple_MPU6050::view_Vital_MPU_Registers() {
uint8_t val;
// Reset code for your convenience:
Serial.println(F("uint8_t val;"
"PWR_MGMT_1_WRITE_DEVICE_RESET();" //PWR_MGMT_1: reset with 100ms delay and full SIGNAL_PATH_RESET: with another 100ms delay
"MPUi2cWriteByte(0x6B, 0x01);/n" // 0000 0001 PWR_MGMT_1:Clock Source Select PLL_X_gyro
"MPUi2cWriteByte(0x38, 0x00);/n" // 0000 0000 INT_ENABLE: no Interrupt
"MPUi2cWriteByte(0x23, 0x00);/n")); // 0000 0000 MPU FIFO_EN: (all off) Using DMP's FIFO instead
Serial.print(F("writeByte(devAddr,0x1C, 0x")); readBytes(0x68, 0x1C, 1, &val); Serial.print((val >> 4), HEX); Serial.print((val & 0x0F), HEX); Serial.println(F(");/n")); // ACCEL_CONFIG:
Serial.print(F("writeByte(devAddr,0x37, 0x")); readBytes(0x68, 0x37, 1, &val); Serial.print((val >> 4), HEX); Serial.print((val & 0x0F), HEX); Serial.println(F(");/n")); // INT_PIN_CFG:
Serial.print(F("writeByte(devAddr,0x6B, 0x")); readBytes(0x68, 0x6B, 1, &val); Serial.print((val >> 4), HEX); Serial.print((val & 0x0F), HEX); Serial.println(F(");/n")); // PWR_MGMT_1:
Serial.print(F("writeByte(devAddr,0x19, 0x")); readBytes(0x68, 0x19, 1, &val); Serial.print((val >> 4), HEX); Serial.print((val & 0x0F), HEX); Serial.println(F(");/n")); // SMPLRT_DIV:
Serial.print(F("writeByte(devAddr,0x1A, 0x")); readBytes(0x68, 0x1A, 1, &val); Serial.print((val >> 4), HEX); Serial.print((val & 0x0F), HEX); Serial.println(F(");/n")); // CONFIG:
Serial.println(F("delay(100);/n"
"load_firmware(DMP_CODE_SIZE, dmp_memory);/n" // Loads the DMP image into the MPU6050 Memory
"MPUi2cWriteInt(0x70, 0x0400);/n" //DMP Program Start Address"
"setOffset(OFFSETS);/n" )); // Load Calibration offset values into MPU
Serial.print(F("writeByte(devAddr,0x1B, 0x")); readBytes(0x68, 0x19, 1, &val); Serial.print((val >> 4), HEX); Serial.print((val & 0x0F), HEX); Serial.println(F(");/n")); // GYRO_CONFIG:
Serial.println(F("MPUi2cWriteByte(0x6A, 0xC0));/n" // 1100 1100 USER_CTRL: Enable Fifo and Reset Fifo
"MPUi2cWriteBytes(0x38, 0x02));/n" // 0000 0010 INT_ENABLE: RAW_DMP_INT_EN on
"attachInterrupt(0, [] { mpuInterrupt = true;}, FALLING);/n"
"reset_fifo();/n"));
}
#define DPRINTBIN(Num) for (uint32_t t = (1UL<< (sizeof(Num)*8)-1); t; t >>= 1) Serial.write(Num & t ? '1' : '0'); // Prints a binary number with leading zeros (Automatic Handling)
#define DPRINTHEX(Num) Serial.print(Num>>4,HEX);Serial.print(Num&0X0F,HEX);
#define ShowByte(Addr) {uint8_t val; I2Cdev::readBytes(0x68, Addr, 1, &val); Serial.print("0x"); DPRINTHEX(Addr); Serial.print(" = 0x"); DPRINTHEX(val); Serial.print(" = 0B"); DPRINTBIN(val); Serial.println();}
void view_MPU_Startup_Registers() {
uint8_t val;
// Reset code for your convenience:
ShowByte(0x23);
ShowByte(0x1C);
ShowByte(0x37);
ShowByte(0x6B);
ShowByte(0x19);
ShowByte(0x1A);
ShowByte(0x70);
ShowByte(0x1B);
ShowByte(0x6A);
ShowByte(0x38);
}
#define A_OFFSET_H_READ_A_OFFS(Data) MPUi2cReadInts(0x06, 3, Data) // X accelerometer offset cancellation
#define XG_OFFSET_H_READ_OFFS_USR(Data) MPUi2cReadInts(0x13, 3, Data) // Remove DC bias from the gyro sensor Step 0.0305 dps
#define printfloatx(Name,Variable,Spaces,Precision,EndTxt) Serial.print(Name); {char S[(Spaces + Precision + 3)];Serial.print(F(" ")); Serial.print(dtostrf((float)Variable,Spaces,Precision ,S));}Serial.print(EndTxt);//Name,Variable,Spaces,Precision,EndTxt
Simple_MPU6050 & Simple_MPU6050::PrintActiveOffsets( ) {
int16_t Data[3];
if(!WhoAmI) WHO_AM_I_READ_WHOAMI(&WhoAmI);
Serial.print(F("\n// X Accel Y Accel Z Accel X Gyro Y Gyro Z Gyro\n#define OFFSETS "));
if(WhoAmI < 0x38) A_OFFSET_H_READ_A_OFFS(Data);
else {
XA_OFFSET_H_READ_0x77_XA_OFFS(Data);
YA_OFFSET_H_READ_0x77_YA_OFFS(Data+1);
ZA_OFFSET_H_READ_0x77_ZA_OFFS(Data+2);
}
printfloatx("", Data[0], 5, 0, ", ");
printfloatx("", Data[1], 5, 0, ", ");
printfloatx("", Data[2], 5, 0, ", ");
XG_OFFSET_H_READ_OFFS_USR(Data);
printfloatx("", Data[0], 5, 0, ", ");
printfloatx("", Data[1], 5, 0, ", ");
printfloatx("", Data[2], 5, 0, "");
Serial.println();
return *this;
}
// I used the following function to retrieve a working configured DMP firmware instance for use in this program
// copy and modify this function to work elseware
/**
@brief View the DMP firmware.
*/
bool Simple_MPU6050::view_DMP_firmware_Instance(uint16_t length) {
uint16_t ii;
uint16_t this_read;
uint16_t bankNum = 0;
#define LOAD_CHUNK (16)
uint8_t cur[LOAD_CHUNK];
Serial.print(F("const unsigned char dmp_memory[DMP_CODE_SIZE] PROGMEM = {\n"));
for (ii = 0; ii < length; ii += this_read) {
this_read = min(LOAD_CHUNK, length - ii);
writeWords(devAddr, 0x6D, 1, ii);
readBytes(devAddr, 0x6F, this_read, cur);
if ((ii % (16 * 16)) == 0) {
Serial.print(F("/* bank # "));
Serial.print(bankNum++);
Serial.println(F(" */"));
}
for (uint16_t c = 0; c < this_read; c++) {
Serial.print(F(" 0x"));
Serial.print(cur[c] >> 4, HEX); //Prints 0 insted of nothing when byte is less than 8
Serial.print(cur[c] & 0X0F, HEX); // Prints the remainder of the hex number
Serial.print(F(","));
}
Serial.println();
}
Serial.println(F("};"));
return true;
}
//***************************************************************************************
//********************** Calibration Routines **********************
//***************************************************************************************
/**
@brief Fully calibrate Gyro from ZERO in about 6-7 Loops 600-700 readings
*/
Simple_MPU6050 & Simple_MPU6050::CalibrateGyro(uint8_t Loops ) {
double kP = 0.3;
double kI = 90;
float x;
x = (100 - map(Loops, 1, 5, 20, 0)) * .01;
kP *= x;
kI *= x;
PID( 0x43, kP, kI, Loops);
//Serial.println();
return *this;
}
/**
@brief Fully calibrate Accel from ZERO in about 6-7 Loops 600-700 readings
*/
Simple_MPU6050 & Simple_MPU6050::CalibrateAccel(uint8_t Loops ) {
float kP = 0.3;
float kI = 90;
float x;
x = (100 - map(Loops, 1, 5, 20, 0)) * .01;
kP *= x;
kI *= x;
PID( 0x3B, kP, kI, Loops);
//Serial.println();
return *this;
}
#define SPrint(Data) Serial.print(Data);Serial.print(", ");
Simple_MPU6050 & Simple_MPU6050::PID(uint8_t ReadAddress, float kP,float kI, uint8_t Loops) {
uint8_t SaveAddress = (ReadAddress == 0x3B)?((WhoAmI < 0x38 )? 0x06:0x77):0x13;
int16_t Data;
float Reading;
int16_t BitZero[3];
uint8_t shift =(SaveAddress == 0x77)?3:2;
float Error, PTerm, ITerm[3];
int16_t eSample;
uint32_t eSum ;
Serial.write('>');
for (int i = 0; i < 3; i++) {
I2Cdev::readWords(devAddr, SaveAddress + (i * shift), 1, (uint16_t *)&Data); // reads 1 or more 16 bit integers (Word)
Reading = Data;
if(SaveAddress != 0x13){
BitZero[i] = Data & 1; // Capture Bit Zero to properly handle Accelerometer calibration
ITerm[i] = ((float)Reading) * 8;
} else {
ITerm[i] = Reading * 4;
}
}
for (int L = 0; L < Loops; L++) {
eSample = 0;
for (int c = 0; c < 100; c++) {// 100 PI Calculations
eSum = 0;
for (int i = 0; i < 3; i++) {
I2Cdev::readWords(devAddr, ReadAddress + (i * 2), 1, (uint16_t *)&Data); // reads 1 or more 16 bit integers (Word)
Reading = Data;
if ((ReadAddress == 0x3B)&&(i == 2)) Reading -= 16384; //remove Gravity
Error = -Reading;
eSum += abs(Reading);
PTerm = kP * Error;
ITerm[i] += (Error * 0.001) * kI; // Integral term 1000 Calculations a second = 0.001
if(SaveAddress != 0x13){
Data = round((PTerm + ITerm[i] ) / 8); //Compute PID Output
Data = ((Data)&0xFFFE) |BitZero[i]; // Insert Bit0 Saved at beginning
} else Data = round((PTerm + ITerm[i] ) / 4); //Compute PID Output
I2Cdev::writeWords(devAddr, SaveAddress + (i * shift), 1, (uint16_t *)&Data);
}
if((c == 99) && eSum > 1000){ // Error is still to great to continue
c = 0;
Serial.write('*');
}
if((eSum * ((ReadAddress == 0x3B)?.05: 1)) < 5) eSample++; // Successfully found offsets prepare to advance
if((eSum < 100) && (c > 10) && (eSample >= 10)) break; // Advance to next Loop
delay(1);
}
Serial.write('.');
kP *= .75;
kI *= .75;
for (int i = 0; i < 3; i++){
if(SaveAddress != 0x13) {
Data = round((ITerm[i] ) / 8); //Compute PID Output
Data = ((Data)&0xFFFE) |BitZero[i]; // Insert Bit0 Saved at beginning
} else Data = round((ITerm[i]) / 4);
I2Cdev::writeWords(devAddr, SaveAddress + (i * shift), 1, (uint16_t *)&Data);
}
}
SIGNAL_PATH_FULL_RESET_WRITE_RESET();
return *this;
}
Simple_MPU6050 & Simple_MPU6050::resetOffset() {
Serial.println("Reset Offsets");
setOffset( sax_, say_, saz_, sgx_, sgy_, sgz_);
return *this; // return Pointer to this class
}
Simple_MPU6050 & Simple_MPU6050::setOffset(int16_t ax_, int16_t ay_, int16_t az_, int16_t gx_, int16_t gy_, int16_t gz_) {
Serial.println("set Offsets");
sax_ = ax_;
say_ = ay_;
saz_ = az_;
sgx_ = gx_;
sgy_ = gy_;
sgz_ = gz_;
if(!WhoAmI) WHO_AM_I_READ_WHOAMI(&WhoAmI);
if(WhoAmI < 0x38){
XA_OFFSET_H_WRITE_XA_OFFS(ax_);
YA_OFFSET_H_WRITE_YA_OFFS(ay_);
ZA_OFFSET_H_WRITE_ZA_OFFS(az_);
} else {
XA_OFFSET_H_WRITE_0x77_XA_OFFS(ax_);
YA_OFFSET_H_WRITE_0x77_YA_OFFS(ay_);
ZA_OFFSET_H_WRITE_0x77_ZA_OFFS(az_);
}
XG_OFFSET_H_WRITE_X_OFFS_USR(gx_);
YG_OFFSET_H_WRITE_Y_OFFS_USR(gy_);
ZG_OFFSET_H_WRITE_Z_OFFS_USR(gz_);
return *this;
}
//***************************************************************************************
//********************** Helper Math Functions **********************
//***************************************************************************************
Simple_MPU6050 & Simple_MPU6050::SetAccel(VectorInt16 *v, int16_t *accel) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
v -> x = accel[0];
v -> y = accel[1];
v -> z = accel[2];
return *this;
}
Simple_MPU6050 & Simple_MPU6050::GetQuaternion(Quaternion *q, const int32_t* qI) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
q -> w = (float)(qI[0] >> 16) / 16384.0f;
q -> x = (float)(qI[1] >> 16) / 16384.0f;
q -> y = (float)(qI[2] >> 16) / 16384.0f;
q -> z = (float)(qI[3] >> 16) / 16384.0f;
return *this;
}
Simple_MPU6050 & Simple_MPU6050::GetLinearAccel(VectorInt16 *v, VectorInt16 *vRaw, VectorFloat *gravity) {
// get rid of the gravity component (+1g = +16384 in standard DMP FIFO packet, sensitivity is +-2g)
v -> x = vRaw -> x - gravity -> x * 16384;
v -> y = vRaw -> y - gravity -> y * 16384;
v -> z = vRaw -> z - gravity -> z * 16384;
return *this;
}
Simple_MPU6050 & Simple_MPU6050::GetLinearAccelInWorld(VectorInt16 *v, VectorInt16 *vReal, Quaternion *q) {
// rotate measured 3D acceleration vector into original state
// frame of reference based on orientation quaternion
memcpy(v, vReal, sizeof(VectorInt16));
v -> rotate(q);
return *this;
}
Simple_MPU6050 & Simple_MPU6050::GetGravity(VectorFloat *v, Quaternion *q) {
v -> x = 2 * (q -> x * q -> z - q -> w * q -> y);
v -> y = 2 * (q -> w * q -> x + q -> y * q -> z);
v -> z = q -> w * q -> w - q -> x * q -> x - q -> y * q -> y + q -> z * q -> z;
return *this;
}
Simple_MPU6050 & Simple_MPU6050::GetEuler(float *data, Quaternion *q) {
data[0] = atan2(2 * q -> x * q -> y - 2 * q -> w * q -> z, 2 * q -> w * q -> w + 2 * q -> x * q -> x - 1); // psi
data[1] = -asin(2 * q -> x * q -> z + 2 * q -> w * q -> y); // theta
data[2] = atan2(2 * q -> y * q -> z - 2 * q -> w * q -> x, 2 * q -> w * q -> w + 2 * q -> z * q -> z - 1); // phi
return *this;
}
Simple_MPU6050 & Simple_MPU6050::GetYawPitchRoll(float *data, Quaternion *q, VectorFloat *gravity) {
#ifdef USE_OLD_GETYAWPITCHROLL
// yaw: (about Z axis)
data[0] = atan2(2*q -> x*q -> y - 2*q -> w*q -> z, 2*q -> w*q -> w + 2*q -> x*q -> x - 1);
// pitch: (nose up/down, about Y axis)
data[1] = atan(gravity -> x / sqrt(gravity -> y*gravity -> y + gravity -> z*gravity -> z));
// roll: (tilt left/right, about X axis)
data[2] = atan(gravity -> y / sqrt(gravity -> x*gravity -> x + gravity -> z*gravity -> z));
#else
// yaw: (about Z axis)
data[0] = atan2(2*q -> x*q -> y - 2*q -> w*q -> z, 2*q -> w*q -> w + 2*q -> x*q -> x - 1);
// pitch: (nose up/down, about Y axis)
data[1] = atan2(gravity -> x , sqrt(gravity -> y*gravity -> y + gravity -> z*gravity -> z));
// roll: (tilt left/right, about X axis)
data[2] = atan2(gravity -> y , gravity -> z);
if (gravity -> z < 0) {
if(data[1] > 0) {
data[1] = PI - data[1];
} else {
data[1] = -PI - data[1];
}
}
#endif
return *this;
}
Simple_MPU6050 & Simple_MPU6050::GetYawPitchRoll(float *data, Quaternion *q) {
data[0] = atan2(2.0f * (q -> x*q -> y + q -> w * q -> z), q -> w * q -> w + q -> x * q -> x - q -> y * q -> y - q -> z * q -> z);
data[1] = -asin(2.0f * (q -> x * q -> z - q -> w * q -> y));
data[2] = atan2(2.0f * (q -> w * q -> x + q -> y * q -> z), q -> w * q -> w - q -> x * q -> x - q -> y * q -> y + q -> z * q -> z);
return *this;
}
Simple_MPU6050 & Simple_MPU6050::ConvertToDegrees(float*ypr, float*xyz) {
//const float radians_to_degrees = 180.0 / M_PI;
for (int i = 0; i < 3; i++) {
xyz[i] = ypr[i] * radians_to_degrees;
}
if ( xyz[0] < -180 ) xyz[0] += 360;
return *this;
}
Simple_MPU6050 & Simple_MPU6050::ConvertToRadians( float*xyz, float*ypr) {
const float degrees_to_radians = M_PI / 180.0;
for (int i = 0; i < 3; i++) ypr[i] = xyz[i] * degrees_to_radians;
return *this;
}
Simple_MPU6050 & Simple_MPU6050::MagneticNorth(float*data, VectorInt16 *v, Quaternion*q ) {
float ax = v->x, ay = v->y, az = v->z;
float q1 = q->w, q2 = q->x, q3 = q->y, q4 = q->z; // short name local variable for readability
float mx = mag[0], my = mag[1], mz = mag[2];
float hx, hy, bx, bz,vx,vy,vz,wx,wy,wz,ex,ey,ez;
float q1q1 = q1 * q1;
float q1q2 = q1 * q2;
float q1q3 = q1 * q3;
float q1q4 = q1 * q4;
float q2q2 = q2 * q2;
float q2q3 = q2 * q3;
float q2q4 = q2 * q4;
float q3q3 = q3 * q3;
float q3q4 = q3 * q4;
float q4q4 = q4 * q4;
// Reference direction of Earth's magnetic field
hx = 2.0f * mx * (0.5f - q3q3 - q4q4) + 2.0f * my * (q2q3 - q1q4) + 2.0f * mz * (q2q4 + q1q3);
hy = 2.0f * mx * (q2q3 + q1q4) + 2.0f * my * (0.5f - q2q2 - q4q4) + 2.0f * mz * (q3q4 - q1q2);
bx = sqrt((hx * hx) + (hy * hy));
bz = 2.0f * mx * (q2q4 - q1q3) + 2.0f * my * (q3q4 + q1q2) + 2.0f * mz * (0.5f - q2q2 - q3q3);
// Estimated direction of gravity and magnetic field
vx = 2.0f * (q2q4 - q1q3);
vy = 2.0f * (q1q2 + q3q4);
vz = q1q1 - q2q2 - q3q3 + q4q4;
wx = 2.0f * bx * (0.5f - q3q3 - q4q4) + 2.0f * bz * (q2q4 - q1q3);
wy = 2.0f * bx * (q2q3 - q1q4) + 2.0f * bz * (q1q2 + q3q4);
wz = 2.0f * bx * (q1q3 + q2q4) + 2.0f * bz * (0.5f - q2q2 - q3q3);
// Error is cross product between estimated direction and measured direction of gravity
ex = (ay * vz - az * vy) + (my * wz - mz * wy);
ey = (az * vx - ax * vz) + (mz * wx - mx * wz);
ez = (ax * vy - ay * vx) + (mx * wy - my * wx);
data[0] = wx;
data[1] = wy;
data[2] = wz;
data[3] = ex;
data[4] = ey;
data[5] = ez;
return *this;
}
//***************************************************************************************