-
Notifications
You must be signed in to change notification settings - Fork 0
/
mpu6050.cpp
1039 lines (913 loc) · 37.3 KB
/
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
/**
******************************************************************************
* @file mpu6050.cpp
* @author Ali Batuhan KINDAN
* @date 20.12.2020
* @brief This file constains MPU6050 driver implementation.
*
* MIT License
*
* Copyright (c) 2022 Ali Batuhan KINDAN
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "mpu6050.h"
namespace MPU6050_Driver {
/**
* @brief Class constructor. In order to make the class communicate with sensor
* user should pass a valid I2C_Interface class instance!
* @param comInterface I2C interface pointer
* @retval none
*/
MPU6050::MPU6050(I2C_Interface *comInterface)
{
/* assign internal interface pointer if given is not null! */
if (comInterface)
{
this->i2c = comInterface;
}
}
/**
* @brief This method wakes up the sensor and configures the accelerometer and
* gyroscope full scale renges with given parameters. It returns the result of
* the process.
* @param gyroScale Gyroscope scale value to be set
* @param accelScale Accelerometer scale value to be set
* @retval i2c_status_t Success rate
*/
i2c_status_t MPU6050::InitializeSensor(
Gyro_FS_t gyroScale,
Accel_FS_t accelScale)
{
i2c_status_t result = WakeUpSensor();
if(result == I2C_STATUS_SUCCESS)
result = SetGyroFullScale(gyroScale);
if(result == I2C_STATUS_SUCCESS)
result = SetAccelFullScale(accelScale);
return result;
}
/**
* @brief This method wakes the sensor up by cleraing the MPU6050_Regs::PWR_MGMT_1
* BIT_SLEEP. Power management 1 sensors default values is 0x40 so it will
* be in sleep mode when it's powered up.
* @param none
* @retval i2c_status_t
*/
i2c_status_t MPU6050::WakeUpSensor(void)
{
return i2c->WriteRegisterBit(MPU6050_ADDRESS, Sensor_Regs::PWR_MGMT_1, Regbits_PWR_MGMT_1::BIT_SLEEP, false);
}
/**
* @brief This method resets the sensor by simply setting the MPU6050_Regs::PWR_MGMT_1
* Device_Reset bit. After the sensor reset this bit will be cleared automatically.
* TODO: Can be modify later to check the Device_Reset bit is clear after the reset
* in order to make it safer (for this we probably need an interface for platform
* delay function).
* @param none
* @retval i2c_status_t
*/
i2c_status_t MPU6050::ResetSensor(void)
{
return i2c->WriteRegisterBit(MPU6050_ADDRESS, Sensor_Regs::PWR_MGMT_1, Regbits_PWR_MGMT_1::BIT_DEVICE_RESET, true);
}
/**
* @brief This method used for configuring the gyroscope full scale range.
* Check gyro_full_scale_range_t for available scales.
* @param gyroScale Gyroscope scale value to be set
* @retval i2c_status_t
*/
i2c_status_t MPU6050::SetGyroFullScale(Gyro_FS_t gyroScale)
{
return i2c->WriteRegister(MPU6050_ADDRESS, Sensor_Regs::GYRO_CONFIG, ((uint8_t)gyroScale << 3));
}
/**
* @brief This method used for getting the gyroscope full scale range.
* Check gyro_full_scale_range_t for available scales. It basically reads the
* Gyro configuration register and returns the full scale range.
* @param error Result of the sensor reading process
* @retval gyro_full_scale_range_t
*/
Gyro_FS_t MPU6050::GetGyroFullScale(i2c_status_t *error)
{
uint8_t gyroConfig = i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::GYRO_CONFIG, error);
return (Gyro_FS_t)((gyroConfig >> 3) & 0x03);
}
/**
* @brief This method used for getting the latest gyroscope X axis RAW value from
* the sensor. Make sure that sensor is not in sleeping mode and gyroscope full
* scale range is set to desired range before reading the values.
* @param error Error state of process
* @retval int16_t X axis RAW gyroscope value
*/
int16_t MPU6050::GetGyro_X_Raw(i2c_status_t *error)
{
int16_t gyroXVal = i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::GYRO_X_OUT_H, error); // higher 8 bits
if(*error == I2C_STATUS_SUCCESS)
{
gyroXVal = (gyroXVal << 8) | i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::GYRO_X_OUT_L, error); // assemble higher and lower bytes
return gyroXVal;
}
return 0x00;
}
/**
* @brief This method used for getting the latest gyroscope Y axis RAW value from
* the sensor. Make sure that sensor is not in sleeping mode and gyroscope full
* scale range is set to desired range before reading the values.
* @param error Error state of process
* @retval int16_t Y axis RAW gyroscope value
*/
int16_t MPU6050::GetGyro_Y_Raw(i2c_status_t *error)
{
int16_t gyroYVal = i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::GYRO_Y_OUT_H, error); // higher 8 bits
if(*error == I2C_STATUS_SUCCESS)
{
gyroYVal = (gyroYVal << 8) | i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::GYRO_Y_OUT_L, error); // assemble higher and lower bytes
return gyroYVal;
}
return 0x00;
}
/**
* @brief This method used for getting the latest gyroscope Z axis RAW value from
* the sensor. Make sure that sensor is not in sleeping mode and gyroscope full
* scale range is set to desired range before reading the values.
* @param error Error state of process
* @retval int16_t Z axis RAW gyroscope value
*/
int16_t MPU6050::GetGyro_Z_Raw(i2c_status_t *error)
{
int16_t gyroZVal = i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::GYRO_Z_OUT_H, error); // higher 8 bits
if(*error == I2C_STATUS_SUCCESS)
{
gyroZVal = (gyroZVal << 8) | i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::GYRO_Z_OUT_L, error); // assemble higher and lower bytes
return gyroZVal;
}
return 0x00;
}
/**
* @brief This method used for configuring the accelerometer full scale range.
* Check accel_full_scale_range_t for available scales.
* @param accelScale Accelerometer scale value to be set
* @retval i2c_status_t
*/
i2c_status_t MPU6050::SetAccelFullScale(Accel_FS_t accelScale)
{
return i2c->WriteRegister(MPU6050_ADDRESS, Sensor_Regs::ACCEL_CONFIG, ((uint8_t)accelScale << 3));
}
/**
* @brief This method used for getting the acceleromteter full scale range.
* Check accel_full_scale_range_t for available scales. It basically reads the
* Accel configuration register and returns the full scale range.
* @param error Result of the sensor reading process
* @retval accel_full_scale_range_t
*/
Accel_FS_t MPU6050::GetAccelFullScale(i2c_status_t *error)
{
uint8_t accelConfig = i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::ACCEL_CONFIG, error);
return (Accel_FS_t)((accelConfig >> 3) & 0x03);
}
/**
* @brief This method used for getting the latest accelerometer X axis RAW value from
* the sensor. Make sure that sensor is not in sleeping mode and accelerometer full
* scale range is set to desired range, before reading the values.
* @param error Error state of process
* @retval int16_t X axis RAW acceleration value
*/
int16_t MPU6050::GetAccel_X_Raw(i2c_status_t *error)
{
int16_t accelXVal = i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::ACCEL_X_OUT_H, error); // higher 8 bits
if(*error == I2C_STATUS_SUCCESS)
{
accelXVal = (accelXVal << 8) | i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::ACCEL_X_OUT_L, error); // assemble higher and lower bytes
return accelXVal;
}
return 0x00;
}
/**
* @brief This method used for getting the latest accelerometer Y axis RAW value from
* the sensor. Make sure that sensor is not in sleeping mode and accelerometer full
* scale range is set to desired range, before reading the values.
* @param error Error state of process
* @retval int16_t Y axis RAW acceleration value
*/
int16_t MPU6050::GetAccel_Y_Raw(i2c_status_t *error)
{
int16_t accelYVal = i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::ACCEL_Y_OUT_H, error); // higher 8 bits
if(*error == I2C_STATUS_SUCCESS)
{
accelYVal = (accelYVal << 8) | i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::ACCEL_Y_OUT_L, error); // assemble higher and lower bytes
return accelYVal;
}
return 0x00;
}
/**
* @brief This method used for getting the latest accelerometer Z axis RAW value from
* the sensor. Make sure that sensor is not in sleeping mode and accelerometer full
* scale range is set to desired range, before reading the values.
* @param error Error state of process
* @retval int16_t Z axis RAW acceleration value
*/
int16_t MPU6050::GetAccel_Z_Raw(i2c_status_t *error)
{
int16_t accelZVal = i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::ACCEL_Z_OUT_H, error); // higher 8 bits
if(*error == I2C_STATUS_SUCCESS)
{
accelZVal = (accelZVal << 8) | i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::ACCEL_Z_OUT_L, error); // assemble higher and lower bytes
return accelZVal;
}
return 0x00;
}
/**
* @brief This method used for getting the latest temperature value from the sensor.
* scale range is set to desired range, before reading the values.
* @param error Error state of process
* @retval float Temperature in celcius-degrees
*/
float MPU6050::GetTemperature_Celcius(i2c_status_t *error)
{
int16_t sensorTemp = i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::TEMP_OUT_H, error); // higher 8 bits
if(*error == I2C_STATUS_SUCCESS)
{
sensorTemp = (sensorTemp << 8) | i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::TEMP_OUT_L, error); // assemble higher and lower bytes
return (sensorTemp / 340.0 + 36.53f);
}
return 0x00;
}
/**
* @brief This method used for setting the gyroscope X axis offset value. Offset is
* using in the sensor calibration routine.
* @param offset
* @retval i2c_status_t
*/
i2c_status_t MPU6050::SetGyro_X_Offset(int16_t offset)
{
i2c_status_t result = i2c->WriteRegister(MPU6050_ADDRESS, Sensor_Regs::XG_OFFS_USR_H, (offset >> 8));
if(result == I2C_STATUS_SUCCESS)
{
result = i2c->WriteRegister(MPU6050_ADDRESS, Sensor_Regs::XG_OFFS_USR_L, (offset & 0x00FF));
}
return result;
}
/**
* @brief This method used for getting the gyroscope X axis offset value.
* @param error Result of the operation
* @retval int16_t
*/
int16_t MPU6050::GetGyro_X_Offset(i2c_status_t *error)
{
int16_t gyroXOffset = i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::XG_OFFS_USR_H, error); // higher 8 bits
if(*error == I2C_STATUS_SUCCESS)
{
gyroXOffset = (gyroXOffset << 8) | i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::XG_OFFS_USR_L, error); // assemble higher and lower bytes
return gyroXOffset;
}
return 0x00;
}
/**
* @brief This method used for setting the gyroscope Y axis offset value. Offset is
* using in the sensor calibration routine.
* @param offset
* @retval i2c_status_t
*/
i2c_status_t MPU6050::SetGyro_Y_Offset(int16_t offset)
{
i2c_status_t result = i2c->WriteRegister(MPU6050_ADDRESS, Sensor_Regs::YG_OFFS_USR_H, (offset >> 8));
if(result == I2C_STATUS_SUCCESS)
{
result = i2c->WriteRegister(MPU6050_ADDRESS, Sensor_Regs::YG_OFFS_USR_L, (offset & 0x00FF));
}
return result;
}
/**
* @brief This method used for getting the gyroscope Y axis offset value.
* @param error Result of the operation
* @retval int16_t
*/
int16_t MPU6050::GetGyro_Y_Offset(i2c_status_t *error)
{
int16_t gyroYOffset = i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::YG_OFFS_USR_H, error); // higher 8 bits
if(*error == I2C_STATUS_SUCCESS)
{
gyroYOffset = (gyroYOffset << 8) | i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::YG_OFFS_USR_L, error); // assemble higher and lower bytes
return gyroYOffset;
}
return 0x00;
}
/**
* @brief This method used for setting the gyroscope Z axis offset value. Offset is
* using in the sensor calibration routine.
* @param offset
* @retval i2c_status_t
*/
i2c_status_t MPU6050::SetGyro_Z_Offset(int16_t offset)
{
i2c_status_t result = i2c->WriteRegister(MPU6050_ADDRESS, Sensor_Regs::ZG_OFFS_USR_H, (offset >> 8));
if(result == I2C_STATUS_SUCCESS)
{
result = i2c->WriteRegister(MPU6050_ADDRESS, Sensor_Regs::ZG_OFFS_USR_L, (offset & 0x00FF));
}
return result;
}
/**
* @brief This method used for getting the gyroscope Z axis offset value.
* @param error Result of the operation
* @retval int16_t
*/
int16_t MPU6050::GetGyro_Z_Offset(i2c_status_t *error)
{
int16_t gyroZOffset = i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::ZG_OFFS_USR_H, error); // higher 8 bits
if(*error == I2C_STATUS_SUCCESS)
{
gyroZOffset = (gyroZOffset << 8) | i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::ZG_OFFS_USR_L, error); // assemble higher and lower bytes
return gyroZOffset;
}
return 0x00;
}
/**
* @brief This method used for calibrating the gyroscope registers to given target values.
* Its VERY important to mention that when you call this method make sure that the sensor is
* standing statically (no vibrations, no rotations, no movement etc.) otherwise you will end
* up with wrong calibration values!
* TODO: Use more detailed return type about the calibration status to inform user about the
* failure (which step it failed and why etc.).
* @param targetX target value for gyroscope X axis register
* @param targetY target value for gyroscope Y axis register
* @param targetZ target value for gyroscope Z axis register
* @retval i2c_status_t
*/
i2c_status_t MPU6050::Calibrate_Gyro_Registers(int16_t targetX, int16_t targetY, int16_t targetZ)
{
i2c_status_t result = I2C_STATUS_NONE;
Gyro_FS_t gyroRange = GetGyroFullScale(&result);
if(result != I2C_STATUS_SUCCESS)
return result;
/* DPS constant to convert raw register value to the
* degree per seconds (angular velocity). */
const float dpsConstant = dpsConstantArr[static_cast<uint8_t>(gyroRange)];
float sumOfSamples = 0;
int16_t offsetVal = 0;
/*
* Gyro X axis calibration
*/
for(uint16_t i = 0; i < 1000 && result == I2C_STATUS_SUCCESS; i++)
{
sumOfSamples += GetGyro_X_Raw(&result);
}
sumOfSamples *= 0.001f; // get mean value of 1000 readings
if(result != I2C_STATUS_SUCCESS)
return result;
offsetVal = (int16_t)(((targetX - sumOfSamples) * dpsConstant) * gyro_offset_1dps);
result = SetGyro_X_Offset(offsetVal);
if(result != I2C_STATUS_SUCCESS)
return result;
/*
* Gyro Y axis calibration
*/
sumOfSamples = 0;
for(uint16_t i = 0; i < 1000 && result == I2C_STATUS_SUCCESS; i++)
{
sumOfSamples += GetGyro_Y_Raw(&result);
}
sumOfSamples *= 0.001f; // get mean value of 1000 readings
if(result != I2C_STATUS_SUCCESS)
return result;
offsetVal = (int16_t)(((targetY - sumOfSamples) * dpsConstant) * gyro_offset_1dps);
result = SetGyro_Y_Offset(offsetVal);
if(result != I2C_STATUS_SUCCESS)
return result;
/*
* Gyro Z axis calibration
*/
sumOfSamples = 0;
for(uint16_t i = 0; i < 1000 && result == I2C_STATUS_SUCCESS; i++)
{
sumOfSamples += GetGyro_Z_Raw(&result);
}
sumOfSamples *= 0.001f; // get mean value of 1000 readings
if(result != I2C_STATUS_SUCCESS)
return result;
offsetVal = (int16_t)(((targetZ - sumOfSamples) * dpsConstant) * gyro_offset_1dps);
result = SetGyro_Z_Offset(offsetVal);
return result;
}
/**
* @brief This method returns the DPS (Degree Per Second) coversion value depending on
* the gyroscope full scale range. DPS value is used to convert raw sensor value to angular
* velocity for orientation related calculations.
* @param gyroRange Configured gyro full scale range
* @retval float
*/
float MPU6050::GetGyro_DPS_Constant(Gyro_FS_t gyroRange)
{
return dpsConstantArr[static_cast<uint8_t>(gyroRange)];
}
/**
* @brief This method used for setting the accelerometer X axis offset value. Offset is
* using in the sensor calibration routine.
* @param offset
* @retval i2c_status_t
*/
i2c_status_t MPU6050::SetAccel_X_Offset(int16_t offset)
{
i2c_status_t result = i2c->WriteRegister(MPU6050_ADDRESS, Sensor_Regs::XA_OFFS_USR_H, (offset >> 8));
if(result == I2C_STATUS_SUCCESS)
{
result = i2c->WriteRegister(MPU6050_ADDRESS, Sensor_Regs::XA_OFFS_USR_L, (offset & 0x00FF));
}
return result;
}
/**
* @brief This method used for getting the accelerometer X axis offset value.
* @param error Result of the operation
* @retval int16_t
*/
int16_t MPU6050::GetAccel_X_Offset(i2c_status_t *error)
{
int16_t accelXOffset = i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::XA_OFFS_USR_H, error); // higher 8 bits
if(*error == I2C_STATUS_SUCCESS)
{
accelXOffset = (accelXOffset << 8) | i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::XA_OFFS_USR_L, error); // assemble higher and lower bytes
return accelXOffset;
}
return 0x00;
}
/**
* @brief This method used for setting the accelerometer Y axis offset value. Offset is
* using in the sensor calibration routine.
* @param offset
* @retval i2c_status_t
*/
i2c_status_t MPU6050::SetAccel_Y_Offset(int16_t offset)
{
i2c_status_t result = i2c->WriteRegister(MPU6050_ADDRESS, Sensor_Regs::YA_OFFS_USR_H, (offset >> 8));
if(result == I2C_STATUS_SUCCESS)
{
result = i2c->WriteRegister(MPU6050_ADDRESS, Sensor_Regs::YA_OFFS_USR_L, (offset & 0x00FF));
}
return result;
}
/**
* @brief This method used for getting the accelerometer Y axis offset value.
* @param error Result of the operation
* @retval int16_t
*/
int16_t MPU6050::GetAccel_Y_Offset(i2c_status_t *error)
{
int16_t accelYOffset = i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::YA_OFFS_USR_H, error); // higher 8 bits
if(*error == I2C_STATUS_SUCCESS)
{
accelYOffset = (accelYOffset << 8) | i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::YA_OFFS_USR_L, error); // assemble higher and lower bytes
return accelYOffset;
}
return 0x00;
}
/**
* @brief This method used for setting the accelerometer Z axis offset value. Offset is
* using in the sensor calibration routine.
* @param offset
* @retval i2c_status_t
*/
i2c_status_t MPU6050::SetAccel_Z_Offset(int16_t offset)
{
i2c_status_t result = i2c->WriteRegister(MPU6050_ADDRESS, Sensor_Regs::ZA_OFFS_USR_H, (offset >> 8));
if(result == I2C_STATUS_SUCCESS)
{
result = i2c->WriteRegister(MPU6050_ADDRESS, Sensor_Regs::ZA_OFFS_USR_L, (offset & 0x00FF));
}
return result;
}
/**
* @brief This method used for getting the accelerometer Z axis offset value.
* @param error Result of the operation
* @retval int16_t
*/
int16_t MPU6050::GetAccel_Z_Offset(i2c_status_t *error)
{
int16_t accelZOffset = i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::ZA_OFFS_USR_H, error); // higher 8 bits
if(*error == I2C_STATUS_SUCCESS)
{
accelZOffset = (accelZOffset << 8) | i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::ZA_OFFS_USR_L, error); // assemble higher and lower bytes
return accelZOffset;
}
return 0x00;
}
/**
* @brief This method used for calibrating the accelerometer registers to given target values. Even if
* the official calibration method in the invensense application notes are tried, it didnt work as expected.
* So there is another method implemented to calibrate accelerometer registers automatically. It works with the
* similar concept of binary search algorithm (setting a range and narrowing on each step).
* @param targetX target value for accelerometer X axis register in MG so 1.0f means 1G
* @param targetY target value for accelerometer Y axis register in MG
* @param targetZ target value for accelerometer Z axis register in MG
* @retval i2c_status_t
*/
i2c_status_t MPU6050::Calibrate_Accel_Registers(float targetX_MG, float targetY_MG, float targetZ_MG)
{
i2c_status_t result = I2C_STATUS_NONE;
Accel_FS_t accelRange = GetAccelFullScale(&result);
if(result != I2C_STATUS_SUCCESS)
return result;
/* MG constant to convert raw register value to the
* gravity (9.81 m/s2). */
const float mgConstant = mgCostantArr[static_cast<uint8_t>(accelRange)];
/* Some constants for our calibration routine to modify easily when needed. */
const int16_t calibrationRangeHigh = 4096;
const int16_t calibrationRangeLow = -calibrationRangeHigh;
const uint8_t calibrationSteps = 13; // if the calibrationRangeHigh = 2^n so this will be (n +1)
const int tolerance = 5; // acceptable tolerance between target and mean value of samples
float meanOfNSamples = 0;
int16_t regExpected = 0;
int16_t diff = 0;
int16_t high = calibrationRangeHigh;
int16_t low = calibrationRangeLow;
int16_t currentOffsetVal = 0;
result = SetAccel_X_Offset(0); // set the offset to 0 first
if(result != I2C_STATUS_SUCCESS)
return result;
result = SetAccel_Y_Offset(0); // set the offset to 0 first
if(result != I2C_STATUS_SUCCESS)
return result;
result = SetAccel_Z_Offset(0); // set the offset to 0 first
if(result != I2C_STATUS_SUCCESS)
return result;
/*
* Accel X axis calibration
*/
regExpected = targetX_MG / mgConstant;
/* Get the initial deviation from our target value after reseting the offset register */
meanOfNSamples = 0;
for (uint8_t i = 0; i < 100 && result == I2C_STATUS_SUCCESS; i++)
{
meanOfNSamples += GetAccel_X_Raw(&result);
}
if(result != I2C_STATUS_SUCCESS)
return result;
meanOfNSamples *= 0.01;
diff = regExpected - meanOfNSamples;
/* Limit our ranges depending on the initial results. So we
* are either work on negative or positive range during the
* calibration steps. */
if (diff < 0)
high = 0;
else
low = 0;
/* Start N steps of calibration. This method is very similar to binary search
* algorightm in sorted list. On every iteration we are setting the offset register
* to a middle value of our high and low range then we read 100 samples from
* Accelerometer and compare our target and mean value of the samples. Depending on the
* result we are narrowing our high and low limits and repeat... */
for (uint8_t step = 0; step < calibrationSteps; step++)
{
/* Update offset register! */
currentOffsetVal = (int16_t)((high + low) /2.0f);
result = SetAccel_X_Offset(currentOffsetVal);
if (result != I2C_STATUS_SUCCESS)
return result;
/* Take 100 samples and compare with target */
meanOfNSamples = 0;
for (uint8_t i = 0; i < 100 && result == I2C_STATUS_SUCCESS; i++)
{
meanOfNSamples += GetAccel_X_Raw(&result);
}
if (result != I2C_STATUS_SUCCESS)
return result;
meanOfNSamples *= 0.01;
diff = regExpected - meanOfNSamples;
/* Quick math.abs to check if difference is in tolerance level.
* If yes abort calibration for this axis its done already! */
if((diff & 0x8000 ? -diff : diff) < tolerance)
break;
/* Update ranges! */
if(diff < 0)
high = currentOffsetVal;
else
low = currentOffsetVal;
} // for calibrationSteps
/*
* Accel Y axis calibration (TODO: unfortunately bad practice of code reusing but keep it for now!)
*/
high = calibrationRangeHigh;
low = calibrationRangeLow;
currentOffsetVal = 0;
regExpected = targetY_MG / mgConstant;
/* Get the initial deviation from our target value after reseting the offset register */
meanOfNSamples = 0;
for (uint8_t i = 0; i < 100 && result == I2C_STATUS_SUCCESS; i++)
{
meanOfNSamples += GetAccel_Y_Raw(&result);
}
if (result != I2C_STATUS_SUCCESS)
return result;
meanOfNSamples *= 0.01;
diff = regExpected - meanOfNSamples;
/* Limit our ranges depending on the initial results. So we
* are either work on negative or positive range during the
* calibration steps. */
if (diff < 0)
high = 0;
else
low = 0;
/* Start N steps of calibration. This method is very similar to binary search
* algorightm in sorted list. On every iteration we are setting the offset register
* to a middle value of our high and low range then we read 100 samples from
* Accelerometer and compare our target and mean value of the samples. Depending on the
* result we are narrowing our high and low limits and repeat... */
for (uint8_t step = 0; step < calibrationSteps; step++)
{
/* Update offset register! */
currentOffsetVal = (int16_t)((high + low) /2.0f);
result = SetAccel_Y_Offset(currentOffsetVal);
if (result != I2C_STATUS_SUCCESS)
return result;
/* Take 100 samples and compare with target */
meanOfNSamples = 0;
for (uint8_t i = 0; i < 100 && result == I2C_STATUS_SUCCESS; i++)
{
meanOfNSamples += GetAccel_Y_Raw(&result);
}
if (result != I2C_STATUS_SUCCESS)
return result;
meanOfNSamples *= 0.01;
diff = regExpected - meanOfNSamples;
/* Quick math.abs to check if difference is in tolerance level.
* If yes abort calibration for this axis its done already! */
if((diff & 0x8000 ? -diff : diff) < tolerance)
break;
/* Update ranges! */
if(diff < 0)
high = currentOffsetVal;
else
low = currentOffsetVal;
} // for calibrationSteps
/*
* Accel Z axis calibration (TODO: unfortunately bad practice of code reusing but keep it for now!)
*/
high = calibrationRangeHigh;
low = calibrationRangeLow;
currentOffsetVal = 0;
regExpected = targetZ_MG / mgConstant;
/* Get the initial deviation from our target value after reseting the offset register */
meanOfNSamples = 0;
for (uint8_t i = 0; i < 100 && result == I2C_STATUS_SUCCESS; i++)
{
meanOfNSamples += GetAccel_Z_Raw(&result);
}
if (result != I2C_STATUS_SUCCESS)
return result;
meanOfNSamples *= 0.01;
diff = regExpected - meanOfNSamples;
/* Limit our ranges depending on the initial results. So we
* are either work on negative or positive range during the
* calibration steps. */
if (diff < 0)
high = 0;
else
low = 0;
/* Start N steps of calibration. This method is very similar to binary search
* algorightm in sorted list. On every iteration we are setting the offset register
* to a middle value of our high and low range then we read 100 samples from
* Accelerometer and compare our target and mean value of the samples. Depending on the
* result we are narrowing our high and low limits and repeat... */
for (uint8_t step = 0; step < calibrationSteps; step++)
{
/* Update offset register! */
currentOffsetVal = (int16_t)((high + low) /2.0f);
result = SetAccel_Z_Offset(currentOffsetVal);
if (result != I2C_STATUS_SUCCESS)
return result;
/* Take 100 samples and compare with target */
meanOfNSamples = 0;
for (uint8_t i = 0; i < 100 && result == I2C_STATUS_SUCCESS; i++)
{
meanOfNSamples += GetAccel_Z_Raw(&result);
}
if (result != I2C_STATUS_SUCCESS)
return result;
meanOfNSamples *= 0.01;
diff = regExpected - meanOfNSamples;
/* Quick math.abs to check if difference is in tolerance level.
* If yes abort calibration for this axis its done already! */
if((diff & 0x8000 ? -diff : diff) < tolerance)
break;
/* Update ranges! */
if(diff < 0)
high = currentOffsetVal;
else
low = currentOffsetVal;
} // for calibrationSteps
return result;
}
/**
* @brief This method returns the MG (Gravity) coversion value depending on
* the accelerometer full scale range. MG value is used to convert raw sensor value to Gravity
* for acceleration related calculations.
* @param accelRange Configured accelerometer full scale range
* @retval float
*/
float MPU6050::GetAccel_MG_Constant(Accel_FS_t accelRange)
{
return mgCostantArr[static_cast<uint8_t>(accelRange)];
}
/**
* @brief This function sets the gyroscope sample rate divider. Once the sample rate divider set, actual sample rate
* can be found with this formula:
* Actual sample rate = Gyroscope Output Rate / (1 + sampleRate)
* Keep in mind that Gyroscope Output Rate = 8kHz when the DLPF (digital low pass filter) is disabled
* (DLPF_CFG = 0 or 7), and 1kHz when the DLPF is enabled. Accel sample rate is constantly 1 kHz.
* @param sampleRate Gyroscope sample rate divider value
* @retval i2c_status_t
*/
i2c_status_t MPU6050::SetGyro_SampleRateDivider(uint8_t sampleRate)
{
return i2c->WriteRegister(MPU6050_ADDRESS, Sensor_Regs::SMPRT_DIV, sampleRate);
}
/**
* @brief This function gets the gyroscope sample rate divider.
* Actual sample rate = Gyroscope Output Rate / (1 + sampleRate)
* Keep in mind that Gyroscope Output Rate = 8kHz when the DLPF (digital low pass filter) is disabled
* (DLPF_CFG = 0 or 7), and 1kHz when the DLPF is enabled. Accel sample rate is constantly 1 kHz.
* @param error Result of the operation
* @retval uint8_t
*/
uint8_t MPU6050::GetGyro_SampleRateDivider(i2c_status_t *error)
{
return i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::SMPRT_DIV, error);
}
/**
* @brief This function sets the sensor digital low pass filter values. Tighter bandwitdh configs will
* generate more delay on the sensor outputs (check sensor datasheet). Keep in mind that default
* Gyroscope sample rate is 8 kHz but if we set DLPF config different than 0 it will be 1 kHz by default
* unless if we make an extra configuration to Sample Rate Divider.
* @param dlpfConfig Digital low pass filter configuration value
* @retval i2c_status_t
*/
i2c_status_t MPU6050::SetSensor_DLPF_Config(DLPF_t dlpfConfig)
{
i2c_status_t error = I2C_STATUS_NONE;
/* This register also have EXT_SYNC config, so only set the DLPF part! */
uint8_t currentRegVal = i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::CONFIG, &error);
if (error == I2C_STATUS_SUCCESS) {
currentRegVal &= (~0x07); // clear the DLPF section from the current register value
error = i2c->WriteRegister(MPU6050_ADDRESS, Sensor_Regs::CONFIG, (uint8_t)dlpfConfig | currentRegVal);
}
return error;
}
/**
* @brief This function gets the current sensor digital low pass filter configuration.
* @param error Result of the operation
* @retval dlpf_config_t
*/
DLPF_t MPU6050::GetSensor_DLPF_Config(i2c_status_t *error)
{
/* get only the first 3 bit of the register */
return (DLPF_t) (i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::CONFIG, error) & 0x07);
}
/**
* @brief This function gets the current sensor sample rate. In order to do this, method
* reads Sample Rate Divider (0x19) and DLPF Config (0x1A) registers.
* @param error Result of the operation
* @retval float Current sample rate in Hz
*/
float MPU6050::GetSensor_CurrentSampleRate_Hz(i2c_status_t *error)
{
uint8_t sampleRateDivider = GetGyro_SampleRateDivider(error);
if(*error != I2C_STATUS_SUCCESS)
return 0x00;
const uint8_t dlpfConfig = static_cast<uint8_t>(GetSensor_DLPF_Config(error));
if(*error != I2C_STATUS_SUCCESS)
return 0x00;
/* if dlpf config is disabled (0 or 7) then sample rate is 8 kHz otherwise 1 kHz */
const float gyroDefaultOutRateHz = (dlpfConfig == static_cast<uint8_t>(DLPF_t::BW_260Hz) || dlpfConfig == static_cast<uint8_t>(DLPF_t::RESERVED)) ? 8000 : 1000;
return gyroDefaultOutRateHz / (1 + sampleRateDivider);
}
/**
* @brief This function gets the number of bytes written in the sensor FIFO buffers.
* @param error Result of the operation
* @retval uint16_t Number of samples in the FIFO buffer in bytes
*/
uint16_t MPU6050::GetSensor_FIFOCount(i2c_status_t* error)
{
uint16_t fifoCount = i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::FIFO_COUNT_H, error); // higher 8 bits
if(*error == I2C_STATUS_SUCCESS)
{
fifoCount = (fifoCount << 8) | i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::FIFO_COUNT_L, error); // assemble higher and lower bytes
return fifoCount;
}
return 0x00;
}
/**
* @brief This function gets the INT_ENABLE register value.
* @param error Result of the operation
* @retval uint8_t Enabled/Disabled sensor interrupts. Use Regbits_INT_ENABLE namespace as bitmask to check enabled interrupts.
*/
uint8_t MPU6050::GetSensor_InterruptEnable(i2c_status_t* error)
{
return i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::INT_ENABLE, error);
}
/**
* @brief This function sets the sensor INT_ENABLE register with given value.
* @param enabledInterrupts Enabled/Disabled sensor interrupts. Use Regbits_INT_ENABLE namespace.
* @retval i2c_status_t
*/
i2c_status_t MPU6050::SetSensor_InterruptEnable(uint8_t enabledInterrupts)
{
return i2c->WriteRegister(MPU6050_ADDRESS, Sensor_Regs::INT_ENABLE, enabledInterrupts);
}
/**
* @brief This function gets the sensor FIFO configuration. Use Regbits_FIFO_EN as bitmask to check which
* samples enabled in the FIFO reading.
* @param error Result of the operation
* @retval uint8_t Sensor fifo configuration value, use Regbits_FIFO_EN to check fifo config.
*/
uint8_t MPU6050::GetSensor_FIFO_Config(i2c_status_t* error)
{
return i2c->ReadRegister(MPU6050_ADDRESS, Sensor_Regs::FIFO_EN, error);
}
/**
* @brief This function sets the sensor FIFO configuration.
* @param fifoConfigVal FIFO config value, use Regbits_FIFO_EN as bitmask to configure.
* @retval i2c_status_t
*/
i2c_status_t MPU6050::SetSensor_FIFO_Config(uint8_t fifoConfigVal)
{
return i2c->WriteRegister(MPU6050_ADDRESS, Sensor_Regs::FIFO_EN, fifoConfigVal);
}
/**
* @brief This function gets the sensor FIFO enable bit in USER_CTRL register.
* @param error Result of the operation
* @retval bool True if FIFO enabled
*/
bool MPU6050::GetSensor_FIFO_Enable(i2c_status_t* error)
{
return i2c->ReadRegisterBit(MPU6050_ADDRESS, Sensor_Regs::USER_CTRL, Regbits_USER_CTRL::BIT_FIFO_EN, error);
}
/**
* @brief This function sets the sensor FIFO enable bit in USER_CTRL register.
* @param state State of the FIFO to be set. True if it will be enabled.
* @retval i2c_status_t
*/
i2c_status_t MPU6050::SetSensor_FIFO_Enable(bool state)
{
return i2c->WriteRegisterBit(MPU6050_ADDRESS, Sensor_Regs::USER_CTRL, Regbits_USER_CTRL::BIT_FIFO_EN, state);
}
/**
* @brief This function resets the sensor FIFO.
* @param none
* @retval i2c_status_t
*/
i2c_status_t MPU6050::Reset_Sensor_FIFO(void)
{
return i2c->WriteRegisterBit(MPU6050_ADDRESS, Sensor_Regs::USER_CTRL, Regbits_USER_CTRL::BIT_FIFO_RESET, true);
}
/**
* @brief This function gets the sensor interrput status (INT_STATUS) register.