-
Notifications
You must be signed in to change notification settings - Fork 1
/
ESP32_Precision-9_compass.ino
2026 lines (1814 loc) · 83.1 KB
/
ESP32_Precision-9_compass.ino
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
bool invertRoll = false;
bool invertPitch = true;
#include <Arduino.h>
#include <SPI.h>
#include <Wire.h>
#include <EEPROM.h> // include library to read and write from flash memory
const uint8_t EEPROM_SIZE = 1 + (sizeof(float) * 3 * 4) + 4;
bool b_calibrated = false;
long gyro_bias[3] = {0, 0, 0}, accel_bias[3] = {0, 0, 0}, calibrated_gyro_bias[3] = {0,0,0}, calibrated_accel_bias[3] = {0,0,0};
enum EEP_ADDR
{
EEP_CALIB_FLAG = 0x00,
EEP_ACC_BIAS = 0x01,
EEP_GYRO_BIAS = 0x0D,
EEP_MAG_BIAS = 0x19,
EEP_MAG_SCALE = 0x25,
EEP_HEADING_OFFSET = 0x31,
EEP_HEEL_OFFSET = 0x32,
EEP_TRIM_OFFSET = 0x33,
EEP_AUTOCALIBRATION = 0x34
};
#define CAN_RX_PIN GPIO_NUM_34
#define CAN_TX_PIN GPIO_NUM_32
#include "N2kMessages.h"
#include <NMEA2000_esp32.h>
#include "runningAngle.h"
#include <SparkFunBME280.h>
#define LED_BUILTIN 2
// List here messages your device will transmit.
const unsigned long TransmitMessagesCompass[] PROGMEM = { 127250L, 127251L, 127257L , 0 }; //Vessel Heading, Rate of Turn, Attitude
const unsigned long TransmitMessagesEnv[] PROGMEM = { 130310L, 130311L, 0 }; //Atmospheric Pressure, Temperature
#define DEV_COMPASS 0 // 60-140
tNMEA2000* nmea2000;
tN2kMsg N2kMsg;
tN2kMsg N2kMsgReply;
int DEVICE_ID = 65;
int SID;
// Running angles
runningAngle AP(runningAngle::DEGREES);
runningAngle AR(runningAngle::DEGREES);
runningAngle AY(runningAngle::DEGREES);
runningAngle AG(runningAngle::DEGREES);
// B&G calibration stop/start
bool calibrationStart = false;
bool calibrationStop = false;
bool calibrationFinished = false;
// Deviation variables
float Deviation[128];
bool calibrationRecording = false;
unsigned long t_dev;
int dev_num = 0;
// Barometer variables
BME280 bmp;
double T, P, P0;
unsigned long recentMaxPressureTimestamp;
float recentMinPressure;
const int numReadings = 250;
double readings[numReadings]; // the readings from the analog input
int readIndex = 0; // the index of the current reading
int total = 0; // the running total
int average = 0; // the average
unsigned long t_next; // Timer
// ----- Arduino pin definitions
byte intPin = 2; // Interrupt pin (not used) ... 2 and 3 are the Arduinos ext int pins
bool showOutput = false;
// ----- Select a TASK
/*
Choose a TASK from the following list:
#define TASK 0 // Calibrate each time at start-up
#define TASK 1 // Calibrate all sensors once and store in EEPROM
#define TASK 2 // Calibrate gyro and accel sensors once and store in EEPROM
#define TASK 5 // No calibration
*/
#define TASK 5
// ----- user offsets and scale-factors
/*
Each of the following values must be overwritten with the offsets and scale - factors for
YOUR location otherwise you will have to "tumble" your compass every time you switch it on.
here are two methods for obtaining this data :
Method 1 :
----------
Set "#define TASK 1". Upload this change to your Arduino.
You will be asked to "tumble" your compass for 30 seconds.
Results will be stored in EEPROM
Method 2 :
----------
Set "#define TASK 2". Upload this change to your Arduino.
Only accel & gyro are calibrated.
Results will be stored in EEPROM
*/
float
Mag_x_offset = -150.55,
Mag_y_offset = 467.50,
Mag_z_offset = -132.20,
Mag_x_scale = 1.00,
Mag_y_scale = 1.07,
Mag_z_scale = 0.94;
#define True_North false // change this to "true" for True North
char InputChar; // incoming characters stored here
// ----- software timer
unsigned long Timer1 = 500000L; // 500mS loop ... used when sending data to to Processing
unsigned long Stop1; // Timer1 stops when micros() exceeds this value
// ----- MPU-9250 addresses
#define MPU9250_ADDRESS 0x68 // Device address when ADO = 0; Use 0x69 when AD0 = 1
#define AK8963_ADDRESS 0x0C // Address of magnetometer
/*
See also MPU-9250 Register Map and Descriptions, Revision 4.0, and
RM-MPU-9250A-00, Rev. 1.4, 9/9/2013 for registers not listed in the above document;
The MPU9250 and MPU9150 are virtually identical but the latter has a different register map
The MPU9255 is similar but WHO_AM_I reports 0x73
*/
// ----- MPU-9250 register map
#define AK8963_WHO_AM_I 0x00 // should return 0x48
#define AK8963_INFO 0x01
#define AK8963_ST1 0x02 // data ready status bit 0
#define AK8963_XOUT_L 0x03 // data
#define AK8963_XOUT_H 0x04
#define AK8963_YOUT_L 0x05
#define AK8963_YOUT_H 0x06
#define AK8963_ZOUT_L 0x07
#define AK8963_ZOUT_H 0x08
#define AK8963_ST2 0x09 // Data overflow bit 3 and data read error status bit 2
#define AK8963_CNTL 0x0A // Power down (0000), single-measurement (0001), self-test (1000) and Fuse ROM (1111) modes on bits 3:0
#define AK8963_ASTC 0x0C // Self test control
#define AK8963_I2CDIS 0x0F // I2C disable
#define AK8963_ASAX 0x10 // Fuse ROM x-axis sensitivity adjustment value
#define AK8963_ASAY 0x11 // Fuse ROM y-axis sensitivity adjustment value
#define AK8963_ASAZ 0x12 // Fuse ROM z-axis sensitivity adjustment value
#define SELF_TEST_X_GYRO 0x00
#define SELF_TEST_Y_GYRO 0x01
#define SELF_TEST_Z_GYRO 0x02
/*
#define X_FINE_GAIN 0x03 // [7:0] fine gain
#define Y_FINE_GAIN 0x04
#define Z_FINE_GAIN 0x05
#define XA_OFFSET_H 0x06 // User-defined trim values for accelerometer
#define XA_OFFSET_L_TC 0x07
#define YA_OFFSET_H 0x08
#define YA_OFFSET_L_TC 0x09
#define ZA_OFFSET_H 0x0A
#define ZA_OFFSET_L_TC 0x0B
*/
#define SELF_TEST_X_ACCEL 0x0D
#define SELF_TEST_Y_ACCEL 0x0E
#define SELF_TEST_Z_ACCEL 0x0F
#define SELF_TEST_A 0x10
#define XG_OFFSET_H 0x13 // User-defined trim values for gyroscope
#define XG_OFFSET_L 0x14
#define YG_OFFSET_H 0x15
#define YG_OFFSET_L 0x16
#define ZG_OFFSET_H 0x17
#define ZG_OFFSET_L 0x18
#define SMPLRT_DIV 0x19
#define CONFIG 0x1A
#define GYRO_CONFIG 0x1B
#define ACCEL_CONFIG 0x1C
#define ACCEL_CONFIG2 0x1D
#define LP_ACCEL_ODR 0x1E
#define WOM_THR 0x1F
#define MOT_DUR 0x20 // Duration counter threshold for motion interrupt generation, 1 kHz rate, LSB = 1 ms
#define ZMOT_THR 0x21 // Zero-motion detection threshold bits [7:0]
#define ZRMOT_DUR 0x22 // Duration counter threshold for zero motion interrupt generation, 16 Hz rate, LSB = 64 ms
#define FIFO_EN 0x23
#define I2C_MST_CTRL 0x24
#define I2C_SLV0_ADDR 0x25
#define I2C_SLV0_REG 0x26
#define I2C_SLV0_CTRL 0x27
#define I2C_SLV1_ADDR 0x28
#define I2C_SLV1_REG 0x29
#define I2C_SLV1_CTRL 0x2A
#define I2C_SLV2_ADDR 0x2B
#define I2C_SLV2_REG 0x2C
#define I2C_SLV2_CTRL 0x2D
#define I2C_SLV3_ADDR 0x2E
#define I2C_SLV3_REG 0x2F
#define I2C_SLV3_CTRL 0x30
#define I2C_SLV4_ADDR 0x31
#define I2C_SLV4_REG 0x32
#define I2C_SLV4_DO 0x33
#define I2C_SLV4_CTRL 0x34
#define I2C_SLV4_DI 0x35
#define I2C_MST_STATUS 0x36
#define INT_PIN_CFG 0x37
#define INT_ENABLE 0x38
#define DMP_INT_STATUS 0x39 // Check DMP interrupt
#define INT_STATUS 0x3A
#define ACCEL_XOUT_H 0x3B
#define ACCEL_XOUT_L 0x3C
#define ACCEL_YOUT_H 0x3D
#define ACCEL_YOUT_L 0x3E
#define ACCEL_ZOUT_H 0x3F
#define ACCEL_ZOUT_L 0x40
#define TEMP_OUT_H 0x41
#define TEMP_OUT_L 0x42
#define GYRO_XOUT_H 0x43
#define GYRO_XOUT_L 0x44
#define GYRO_YOUT_H 0x45
#define GYRO_YOUT_L 0x46
#define GYRO_ZOUT_H 0x47
#define GYRO_ZOUT_L 0x48
#define EXT_SENS_DATA_00 0x49
#define EXT_SENS_DATA_01 0x4A
#define EXT_SENS_DATA_02 0x4B
#define EXT_SENS_DATA_03 0x4C
#define EXT_SENS_DATA_04 0x4D
#define EXT_SENS_DATA_05 0x4E
#define EXT_SENS_DATA_06 0x4F
#define EXT_SENS_DATA_07 0x50
#define EXT_SENS_DATA_08 0x51
#define EXT_SENS_DATA_09 0x52
#define EXT_SENS_DATA_10 0x53
#define EXT_SENS_DATA_11 0x54
#define EXT_SENS_DATA_12 0x55
#define EXT_SENS_DATA_13 0x56
#define EXT_SENS_DATA_14 0x57
#define EXT_SENS_DATA_15 0x58
#define EXT_SENS_DATA_16 0x59
#define EXT_SENS_DATA_17 0x5A
#define EXT_SENS_DATA_18 0x5B
#define EXT_SENS_DATA_19 0x5C
#define EXT_SENS_DATA_20 0x5D
#define EXT_SENS_DATA_21 0x5E
#define EXT_SENS_DATA_22 0x5F
#define EXT_SENS_DATA_23 0x60
#define MOT_DETECT_STATUS 0x61
#define I2C_SLV0_DO 0x63
#define I2C_SLV1_DO 0x64
#define I2C_SLV2_DO 0x65
#define I2C_SLV3_DO 0x66
#define I2C_MST_DELAY_CTRL 0x67
#define SIGNAL_PATH_RESET 0x68
#define MOT_DETECT_CTRL 0x69
#define USER_CTRL 0x6A // Bit 7 enable DMP, bit 3 reset DMP
#define PWR_MGMT_1 0x6B // Device defaults to the SLEEP mode
#define PWR_MGMT_2 0x6C
#define DMP_BANK 0x6D // Activates a specific bank in the DMP
#define DMP_RW_PNT 0x6E // Set read/write pointer to a specific start address in specified DMP bank
#define DMP_REG 0x6F // Register in DMP from which to read or to which to write
#define DMP_REG_1 0x70
#define DMP_REG_2 0x71
#define FIFO_COUNTH 0x72
#define FIFO_COUNTL 0x73
#define FIFO_R_W 0x74
#define WHO_AM_I_MPU9250 0x75 // Should return 0x71; MPU9255 will return 0x73
#define XA_OFFSET_H 0x77
#define XA_OFFSET_L 0x78
#define YA_OFFSET_H 0x7A
#define YA_OFFSET_L 0x7B
#define ZA_OFFSET_H 0x7D
#define ZA_OFFSET_L 0x7E
// ----- Set initial input parameters
enum Ascale {
AFS_2G = 0,
AFS_4G,
AFS_8G,
AFS_16G
};
enum Gscale {
GFS_250DPS = 0,
GFS_500DPS,
GFS_1000DPS,
GFS_2000DPS
};
enum Mscale {
MFS_14BITS = 0, // 0.6 mG per LSB;
MFS_16BITS // 0.15 mG per LSB
};
enum M_MODE {
M_8HZ = 0x02, // 8 Hz ODR (output data rate) update
M_100HZ = 0x06 // 100 Hz continuous magnetometer
};
// ----- Specify sensor full scale
byte Gscale = GFS_250DPS;
byte Ascale = AFS_2G;
byte Mscale = MFS_14BITS; // Choose either 14-bit or 16-bit magnetometer resolution (AK8963=14-bits)
byte Mmode = 0x02; // 2 for 8 Hz, 6 for 100 Hz continuous magnetometer data read
float aRes, gRes, mRes; // scale resolutions per LSB for the sensors
short accelCount[3]; // Stores the 16-bit signed accelerometer sensor output
short gyroCount[3]; // Stores the 16-bit signed gyro sensor output
short magCount[3]; // Stores the 16-bit signed magnetometer sensor output
float magCalibration[3] = {0, 0, 0},
magBias[3] = {0, 0, 0},
magScale[3] = {0, 0, 0}; // Factory mag calibration, mag offset , mag scale-factor
float gyroBias[3] = {0, 0, 0},
accelBias[3] = {0, 0, 0}; // Bias corrections for gyro and accelerometer
short tempCount; // temperature raw count output
float temperature; // Stores the real internal chip temperature in degrees Celsius
float SelfTest[6]; // holds results of gyro and accelerometer self test
/*
There is a tradeoff in the beta parameter between accuracy and response speed.
In the original Madgwick study, beta of 0.041 (corresponding to GyroMeasError of 2.7 degrees/s) was found to give optimal accuracy.
However, with this value, the LSM9SD0 response time is about 10 seconds to a stable initial quaternion.
Subsequent changes also require a longish lag time to a stable output, not fast enough for a quadcopter or robot car!
By increasing beta (GyroMeasError) by about a factor of fifteen, the response time constant is reduced to ~2 sec
I haven't noticed any reduction in solution accuracy. This is essentially the I coefficient in a PID control sense;
the bigger the feedback coefficient, the faster the solution converges, usually at the expense of accuracy.
In any case, this is the free parameter in the Madgwick filtering and fusion scheme.
*/
// ----- global constants for 9 DoF fusion and AHRS (Attitude and Heading Reference System)
float GyroMeasError = PI * (40.0f / 180.0f); // gyroscope measurement error in rads/s (start at 40 deg/s)
float GyroMeasDrift = PI * (0.0f / 180.0f); // gyroscope measurement drift in rad/s/s (start at 0.0 deg/s/s)
// ----- Madgwick free parameters
float beta = sqrt(3.0f / 4.0f) * GyroMeasError; // compute beta
float zeta = sqrt(3.0f / 4.0f) * GyroMeasDrift; // compute zeta, the other free parameter in the Madgwick scheme usually set to a small or zero value
// ----- Mahony free parameters
#define Kp 2.0f * 5.0f // original Kp proportional feedback parameter in Mahony filter and fusion scheme
//#define Kp 40.0f // Kp proportional feedback parameter in Mahony filter and fusion scheme
#define Ki 0.0f // Ki integral parameter in Mahony filter and fusion scheme
unsigned long delt_t = 0; // used to control display output rate
unsigned long count = 0, sumCount = 0; // used to control display output rate
float pitch, roll, yaw;
float deltat = 0.0f, sum = 0.0f; // integration interval for both filter schemes
unsigned long lastUpdate = 0, firstUpdate = 0; // used to calculate integration interval
unsigned long Now = 0; // used to calculate integration interval
float ax, ay, az, gx, gy, gz, mx, my, mz; // variables to hold latest sensor data values
float q[4] = {1.0f, 0.0f, 0.0f, 0.0f}; // vector to hold quaternion
float eInt[3] = {0.0f, 0.0f, 0.0f}; // vector to hold integral error for Mahony method
float heading, heading_true, heading_variation = 0,
heading_offset_rad = 0,
heel_offset_rad = 0,
trim_offset_rad = 0;
int heading_offset_deg = 0,
heel_offset_deg = 0,
trim_offset_deg = 0;
bool send_heading = true; // to do 20 vs 10hz
bool send_heading_true = false; // to do 20 vs 10hz
unsigned char compass_autocalibration = 0x00;
// -----------------
// setup()
// -----------------
void setup()
{
Wire.begin(16,17);
Wire.setClock(400000); // 400 kbit/sec I2C speed
Serial.begin(115200);
while (!Serial); // required for Feather M4 Express
// Setup LED
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
Serial.println("BMP Start");
bmp.settings.commInterface = I2C_MODE;
bmp.settings.I2CAddress = 0x76;
bmp.settings.runMode = 3;
bmp.settings.filter = 0;
bmp.settings.tempOverSample = 1;
bmp.settings.pressOverSample = 1;
//bmp.settings.disableHumidity = true;
if (!bmp.begin()) {
Serial.println(F("BMP init failed!"));
while (1);
}
else Serial.println(F("BMP init success!"));
delay(2000);
// ----- Display title
Serial.println("\nMPU-9250 Quaternion Compass");
Serial.println("");
delay(2000);
// ----- Read the WHO_AM_I register, this is a good test of communication
byte c = readByte(MPU9250_ADDRESS, WHO_AM_I_MPU9250); // Read WHO_AM_I register for MPU-9250
delay(1000);
if ((c == 0x71) || (c == 0x73)) // MPU9250=0x68; MPU9255=0x73
{
Serial.println(F("MPU9250 is online..."));
Serial.println("");
delay(2000);
MPU9250SelfTest(SelfTest); // Start by performing self test and reporting values
Serial.println(F("Self test (14% acceptable)"));
Serial.print(F("x-axis acceleration trim within : ")); Serial.print(SelfTest[0], 1); Serial.println(F("% of factory value"));
Serial.print(F("y-axis acceleration trim within : ")); Serial.print(SelfTest[1], 1); Serial.println(F("% of factory value"));
Serial.print(F("z-axis acceleration trim within : ")); Serial.print(SelfTest[2], 1); Serial.println(F("% of factory value"));
Serial.print(F("x-axis gyration trim within : ")); Serial.print(SelfTest[3], 1); Serial.println(F("% of factory value"));
Serial.print(F("y-axis gyration trim within : ")); Serial.print(SelfTest[4], 1); Serial.println(F("% of factory value"));
Serial.print(F("z-axis gyration trim within : ")); Serial.print(SelfTest[5], 1); Serial.println(F("% of factory value"));
Serial.println("");
Serial.println("EEPROM start");
if (!EEPROM.begin(EEPROM_SIZE))
{
Serial.println("EEPROM start failed");
}
if (MPU9250isCalibrated() && TASK == 5) {
printCalibration();
if (loadMPU9250Calibration()) {
Serial.println("MPU9250 calibration sucessfully read from EEPROM");
calibrateMPU9250(gyroBias, accelBias); // Load biases in bias registers
// printBiases2();
} else {
Serial.println("MPU9250 calibration reading from EEPROM failed");
}
} else {
Serial.println("MPU9250 needs calibration.");
// ----- Level surface message
Serial.println("Place the compass on a level surface");
delay(1000);
calibrateMPU9250(gyroBias, accelBias); // Calibrate gyro and accelerometers, load biases in bias registers
if (saveMPU9250Calibration()) {
Serial.println("MPU9250 calibration saved to EEPROM");
} else {
Serial.println("MPU9250 calibration saving to EEPROM failed");
}
}
printBiases();
delay(1000);
initMPU9250();
Serial.println(F("MPU9250 initialized for active data mode....")); // Initialize device for active mode read of acclerometer, gyroscope, and temperature
Serial.println("");
// Read the WHO_AM_I register of the magnetometer, this is a good test of communication
byte d = readByte(AK8963_ADDRESS, AK8963_WHO_AM_I); // Read WHO_AM_I register for AK8963
if (d == 0x48)
{
// ----- AK8963 found
Serial.println(F("AK8963 is online ..."));
// Get magnetometer calibration from AK8963 ROM
initAK8963(magCalibration);
Serial.println(F("AK8963 initialized for active data mode ...")); // Initialize device for active mode read of magnetometer
Serial.println("");
Serial.println(F("Asahi sensitivity adjustment values"));
Serial.print(F("ASAX = ")); Serial.println(magCalibration[0], 2);
Serial.print(F("ASAY = ")); Serial.println(magCalibration[1], 2);
Serial.print(F("ASAZ = ")); Serial.println(magCalibration[2], 2);
Serial.println("");
delay(1000);
}
else
{
// ----- AK8963 not found
Serial.print(F("AK8963 WHO_AM_I = ")); Serial.println(c, HEX);
Serial.println(F("I should be 0x48"));
Serial.print(F("Could not connect to AK8963: 0x"));
Serial.println(d, HEX);
Serial.println("");
while (1) ; // Loop forever if communication doesn't happen
}
}
else
{
// ----- MPU9250 not found
Serial.print(F("MPU9250 WHO_AM_I = ")); Serial.println(c, HEX);
Serial.println(F("I should be 0x71 or 0x73"));
Serial.print(F("Could not connect to MPU9250: 0x"));
Serial.println(c, HEX);
Serial.println("");
while (1) ; // Loop forever if communication doesn't happen
}
// --------------------------
// TASK 0,1 tasks & messages
// --------------------------
if ((TASK == 0) || (TASK == 1))
{
// ----- Calculate magnetometer offsets & scale-factors
Serial.println(F("Magnetometer calibration ..."));
Serial.println(F("Tumble/wave device for 30 seconds in a figure 8"));
delay(2000);
magCalMPU9250(magBias, magScale);
Serial.println(F("Stop tumbling"));
Serial.println("");
delay(4000);
}
if (TASK == 1) {
// ----- Message
Serial.println(F("------------------------------------------"));
Serial.println(F("The following offsets were found and will "));
Serial.println(F("be stored in EEPROM"));
Serial.println(F("------------------------------------------"));
Serial.println(F(""));
Serial.println(F("float"));
Serial.print(F("Mag_x_offset = "));
Serial.print(magBias[0]);
Serial.println(",");
Serial.print(F("Mag_y_offset = "));
Serial.print(magBias[1]);
Serial.println(",");
Serial.print(F("Mag_z_offset = "));
Serial.print(magBias[2]);
Serial.println(",");
Serial.print(F("Mag_x_scale = "));
Serial.print(magScale[0]);
Serial.println(",");
Serial.print(F("Mag_y_scale = "));
Serial.print(magScale[1]);
Serial.println(",");
Serial.print(F("Mag_z_scale = "));
Serial.print(magScale[2]);
Serial.println(F(";"));
// ----- Halt program
while (true);
}
// Initialise canbus
Serial.println("Set up NMEA2000 device");
nmea2000 = new tNMEA2000_esp32(CAN_TX_PIN, CAN_RX_PIN);
nmea2000->SetN2kCANSendFrameBufSize(250);
nmea2000->SetN2kCANReceiveFrameBufSize(250);
// nmea2000->SetDeviceCount(1);
// nmea2000->SetInstallationDescription1("");
// nmea2000->SetInstallationDescription2("");
nmea2000->SetProductInformation("107018103", // Manufacturer's Model serial code
13233, // Manufacturer's product code
"Precision-9 Compass", // Manufacturer's Model ID
"2.0.3-0", // Manufacturer's Software version code
"", // Manufacturer's Model version
1, // load equivalency *50ma
0xffff, // NMEA 2000 version - use default
0xff, // Sertification level - use default
DEV_COMPASS
);
// Set device information
nmea2000->SetDeviceInformation(1048678, // Unique number. Use e.g. Serial number.
140, // Device function=Temperature See codes on http://www.nmea.org/Assets/20120726%20nmea%202000%20class%20%26%20function%20codes%20v%202.00.pdf
60, // Device class=Sensor Communication Interface. See codes on http://www.nmea.org/Assets/20120726%20nmea%202000%20class%20%26%20function%20codes%20v%202.00.pdf
275, // Just choosen free from code list on http://www.nmea.org/Assets/20121020%20nmea%202000%20registration%20list.pdf
4,
DEV_COMPASS
);
nmea2000->SetMode(tNMEA2000::N2km_NodeOnly, DEVICE_ID);
nmea2000->EnableForward(false);
nmea2000->SetForwardStream(&Serial);
nmea2000->SetForwardType(tNMEA2000::fwdt_Text);
nmea2000->ExtendTransmitMessages(TransmitMessagesCompass, DEV_COMPASS);
nmea2000->SetN2kCANMsgBufSize(20);
nmea2000->SetMsgHandler(HandleNMEA2000Msg);
nmea2000->Open();
// Running angles weights
AP.setWeight(0.3);
AR.setWeight(0.3);
AY.setWeight(0.3);
AG.setWeight(0.3);
Serial.println("Press 'o' to enable serial output.");
t_next = 0;
}
// ----------
// loop()
// ----------
void loop()
{
refresh_data(); // This must be done each time through the loop
calc_quaternion(); // This must be done each time through the loop
calc_pitchRollYaw();
if (t_next + 50 <= millis()) // Set timer for 50ms
{
t_next = millis();
calc_heading();
printValues();
if (send_heading) {
SetN2kPGN127250(N2kMsg, SID, heading * DEG_TO_RAD, N2kDoubleNA, N2kDoubleNA, N2khr_magnetic);
nmea2000->SendMsg(N2kMsg, DEV_COMPASS);
if (send_heading_true) {
SetN2kPGN127250(N2kMsg, SID, heading_true * DEG_TO_RAD, N2kDoubleNA, N2kDoubleNA, N2khr_true);
nmea2000->SendMsg(N2kMsg, DEV_COMPASS);
}
SetN2kRateOfTurn(N2kMsg, SID, gz * 0.017448352875489); // radians
nmea2000->SendMsg(N2kMsg, DEV_COMPASS);
}
send_heading = !send_heading; // Toggle to do 10hz
SetN2kAttitude(N2kMsg, SID, N2kDoubleNA, pitch * DEG_TO_RAD, roll * DEG_TO_RAD);
nmea2000->SendMsg(N2kMsg, DEV_COMPASS);
SID++; if (SID > 253) {
SID = 1;
}
// Check for commands
if (Serial.available()) {
InputChar = Serial.read();
if (InputChar == 'o') {
showOutput = !showOutput;
}
if (InputChar == 'd') {
Serial.println("Starting deviation calibration. Start turning at a steady 3 degrees/second and press 's' to start.");
calibrationStart = true;
}
if (InputChar == 's' && calibrationRecording == false) {
Serial.println("Calibration recording started. Keep turning at a steady 3 degrees/second for 390 degrees.");
calibrationRecording = true;
}
}
if (calibrationStart == true && calibrationStop == false) {
Serial.println("Calibration recording started. Keep turning at a steady 3 degrees/second for 390 degrees.");
calibrationRecording = true;
}
if ( calibrationRecording) {
recordDeviation();
t_dev = millis();
}
if (calibrationStop == true && calibrationStart == true) {
calibrationStart = false;
calibrationStop = false;
calibrationRecording = false;
Serial.println("Calibration cancelled.");
}
if (calibrationFinished) {
Serial.println("Calibration finished.");
calibrationRecording = false;
calibrationStart = false;
showDeviationTable();
}
ToggleLed(); // Toggle led
}
nmea2000->ParseMessages();
}
void printBiases() {
Serial.println(F("MPU9250 accelerometer bias"));
Serial.print(F("x = ")); Serial.println((int)(1000 * accelBias[0]));
Serial.print(F("y = ")); Serial.println((int)(1000 * accelBias[1]));
Serial.print(F("z = ")); Serial.print((int)(1000 * accelBias[2]));
Serial.println(F(" mg"));
Serial.println("");
Serial.println(F("MPU9250 gyro bias"));
Serial.print(F("x = ")); Serial.println(gyroBias[0], 1);
Serial.print(F("y = ")); Serial.println(gyroBias[1], 1);
Serial.print(F("z = ")); Serial.print(gyroBias[2], 1);
Serial.println(F(" o/s"));
Serial.println("");
Serial.println(F("MPU9250 magnetometer bias"));
Serial.print(F("x = ")); Serial.println(Mag_x_offset, 1);
Serial.print(F("y = ")); Serial.println(Mag_y_offset, 1);
Serial.print(F("z = ")); Serial.print(Mag_z_offset, 1);
Serial.println("\n");
}
void printBiases2() {
Serial.println(F("MPU9250 accelerometer bias"));
Serial.print(F("x = ")); Serial.println((int)(accel_bias[0]));
Serial.print(F("y = ")); Serial.println((int)(accel_bias[1]));
Serial.print(F("z = ")); Serial.print((int)(accel_bias[2]));
Serial.println("");
Serial.println(F("MPU9250 gyro bias"));
Serial.print(F("x = ")); Serial.println(gyro_bias[0], 1);
Serial.print(F("y = ")); Serial.println(gyro_bias[1], 1);
Serial.print(F("z = ")); Serial.print(gyro_bias[2], 1);
Serial.println("");
Serial.println(F("MPU9250 magnetometer bias"));
Serial.print(F("x = ")); Serial.println(Mag_x_offset, 1);
Serial.print(F("y = ")); Serial.println(Mag_y_offset, 1);
Serial.print(F("z = ")); Serial.print(Mag_z_offset, 1);
Serial.println("\n");
}
void recordDeviation() {
// Record compass headings to create deviation table
// With 3 degrees/second we can record the heading every 0.5 seconds in a table of 120 measurements
if (millis() > t_dev) {
t_dev += 500; // Next measurement to happen 500ms from now
if (calibrationRecording) {
Deviation[dev_num] = heading;
Serial.printf("Rate of turn: % 5.2f dps Deviation[%3d] = %05.2f\n", gz, dev_num, Deviation[dev_num]);
dev_num++;
if (dev_num > 120) {
dev_num = 0;
}
} else {
Serial.printf("Rate of turn: % 3.0f dps Press 's' to start recording.\n", gz);
}
}
}
void showDeviationTable() {
Serial.printf("num heading\n");
for (dev_num = 0; dev_num <= 120; dev_num++) {
Serial.printf("%3d, %05.2f\n", dev_num, Deviation[dev_num]);
}
}
int num_n2k_messages = 0;
void HandleNMEA2000Msg(const tN2kMsg &N2kMsg) {
// N2kMsg.Print(&Serial);
// Serial.printf("PGN: %u\n", (unsigned int)N2kMsg.PGN);
switch (N2kMsg.PGN) {
case 130850L:
if (ParseN2kPGN130850(N2kMsg)) {
Serial.printf("calibrationStart: %s calibrationStop: %s\n", String(calibrationStart), String(calibrationStop));
}
break;
case 127258L:
unsigned char SID;
tN2kMagneticVariation source;
uint16_t DaysSince1970;
double variation;
ParseN2kMagneticVariation(N2kMsg, SID, source, DaysSince1970, variation);
heading_variation = (float)variation * RAD_TO_DEG;
send_heading_true = true;
break;
case 130845L:
uint16_t Key, Command, Value;
if (ParseN2kPGN130845(N2kMsg, Key, Command, Value)) {
// Serial.printf("Key: %d Command: %d Value: %d\n", Key, Command, Value);
}
break;
}
num_n2k_messages++;
// Serial.printf("Message count: %d\n", num_n2k_messages);
ToggleLed();
}
bool ParseN2kPGN130850(const tN2kMsg &N2kMsg) {
Serial.println("Entering ParseN2kPGN130850");
if (N2kMsg.PGN!=130850L) return false;
int Index=2;
unsigned char Command1=N2kMsg.GetByte(Index);
unsigned char Command2=N2kMsg.GetByte(Index);
unsigned char Command3=N2kMsg.GetByte(Index);
unsigned char Command4=N2kMsg.GetByte(Index);
unsigned char CalibrationStopStart=N2kMsg.GetByte(Index);
//Serial.printf("Command1: %u Command4: %u CalibrationStopStart: %u ", (unsigned int)Command1, (unsigned int)Command4, (unsigned int)CalibrationStopStart);
if (Command1 == DEVICE_ID && Command4 == 18 && CalibrationStopStart == 0) {
calibrationStart = true;
// Send ack
Send130851Ack(0);
return true;
} else {
if (Command1 == DEVICE_ID && Command4 == 18 && CalibrationStopStart == 1) {
calibrationStop = true;
// Send ack
Send130851Ack(1);
return true;
}
}
return false;
}
bool ParseN2kPGN130845(const tN2kMsg &N2kMsg, uint16_t &Key, uint16_t &Command, uint16_t &Value) {
// Serial.println("Entering ParseN2kPGN130845");
if (N2kMsg.PGN != 130845L) return false;
int Index=2;
unsigned char Target = N2kMsg.GetByte(Index);
if (Target == 65) {
N2kMsg.Print(&Serial);
tN2kMsg N2kMsgReply;
unsigned char source = N2kMsg.Source;
Index = 6;
Key = N2kMsg.Get2ByteUInt(Index);
Command = N2kMsg.Get2ByteUInt(Index);
if (Command == 0x0000) {
// Get
if (SetN2kPGN130845(N2kMsgReply, DEVICE_ID, Key, 2)) // 2 = Ack
nmea2000->SendMsg(N2kMsgReply, DEV_COMPASS);
}
if (Command == 0x0100) {
// Set
switch (Key) {
case 0x0000: // Heading offset
heading_offset_rad = N2kMsg.Get2ByteUDouble(0.0001, Index);
heading_offset_deg = (int)round(heading_offset_rad * RAD_TO_DEG);
Serial.printf("heading_offset_rad: %f heading_offset_deg: %d\n", heading_offset_rad, heading_offset_deg);
EEPROM.writeByte(EEP_HEADING_OFFSET, (unsigned char)heading_offset_deg);
EEPROM.commit();
break;
case 0x0039: // Heel offset
heel_offset_rad = N2kMsg.Get2ByteUDouble(0.0001, Index);
heel_offset_deg = (int)round(heel_offset_rad * RAD_TO_DEG);
Serial.printf("heel_offset_rad: %f heel_offset_deg: %d\n", heel_offset_rad, heel_offset_deg);
EEPROM.writeByte(EEP_HEEL_OFFSET, (unsigned char)heel_offset_deg);
EEPROM.commit();
break;
case 0x0031: // Trim offset
trim_offset_rad = N2kMsg.Get2ByteUDouble(0.0001, Index);
trim_offset_deg = (int)round(trim_offset_rad * RAD_TO_DEG);
Serial.printf("trim_offset_rad: %f trim_offset_deg: %d\n", trim_offset_rad, trim_offset_deg);
EEPROM.writeByte(EEP_TRIM_OFFSET, (unsigned char)trim_offset_deg);
EEPROM.commit();
break;
case 0xd200: // Auto calibration (01=on, 02=auto locked)
compass_autocalibration = N2kMsg.GetByte(Index);
if (SetN2kPGN130845(N2kMsgReply, DEVICE_ID, 0xd400, 2))
nmea2000->SendMsg(N2kMsgReply, DEV_COMPASS);
EEPROM.writeByte(EEP_AUTOCALIBRATION, (unsigned char)compass_autocalibration);
EEPROM.commit();
break;
case 0xd300: // Warning
break;
case 0xd400: // Status
break; }
}
if (SetN2kPGN130845(N2kMsgReply, DEVICE_ID, Key, 2))
nmea2000->SendMsg(N2kMsgReply, DEV_COMPASS);
return true;
} else {
// Serial.printf("Skipping this one...\n");
return false;
}
return false;
}
void Send130851Ack(int StopStart) {
tN2kMsg N2kMsg;
SetN2k130851Ack(N2kMsg, DEVICE_ID, 18, (unsigned char)StopStart);
nmea2000->SendMsg(N2kMsg, DEV_COMPASS);
}
bool SetN2kPGN130845(tN2kMsg &N2kMsg, unsigned char DEVICE_ID, uint16_t Key, uint16_t Command) {
N2kMsg.SetPGN(130845L);
N2kMsg.Priority=2;
N2kMsg.AddByte(0x41); // Reserved
N2kMsg.AddByte(0x9f); // Reserved
N2kMsg.AddByte((unsigned char)DEVICE_ID);
N2kMsg.AddByte(0xff); // Reserved
N2kMsg.AddByte(0xff); // Reserved
N2kMsg.AddByte(0xff); // Reserved
N2kMsg.Add2ByteUInt((uint16_t)Key);
if (Command == 2) {
N2kMsg.Add2ByteUInt(0x0200);
}
switch (Key) {
case 0x0000: // Heading offset
N2kMsg.Add2ByteDouble(heading_offset_rad, 0.0001);
N2kMsg.AddByte(0xff); // Reserved
break;
case 0x0039: // Heel offset
N2kMsg.Add2ByteDouble(heel_offset_rad, 0.0001);
break;
case 0x0031: // Trim offset
N2kMsg.Add2ByteDouble(trim_offset_rad, 0.0001);
break;
case 0xd200: // Auto calibration (01=on, 02=auto locked)
N2kMsg.AddByte(compass_autocalibration); // Reserved
N2kMsg.AddByte(0xff); // Reserved
break;
case 0xd300: // Warning
N2kMsg.AddByte(0x00); // Reserved // 00=No warning, 01=First calibration in progress, 02=Parameters in use are not valid
N2kMsg.AddByte(0xff); // Reserved
break;
case 0xd400: // Status
N2kMsg.AddByte(0x00); // Reserved // 00=Is calibrated, 01=Not calibrated, 02=Is calibrating
N2kMsg.AddByte(0xff); // Reserved
break;
default:
return false;
}
N2kMsg.AddByte(0xff); // Reserved
N2kMsg.AddByte(0xff); // Reserved
return true;
}
void SetN2kPGN130851(tN2kMsg &N2kMsg, int DEVICE_ID, unsigned char Command, unsigned char CalibrationStopStart) {
N2kMsg.SetPGN(130851L);
N2kMsg.Priority=2;
N2kMsg.AddByte(0x41); // Reserved
N2kMsg.AddByte(0x9f); // Reserved
N2kMsg.AddByte((unsigned char)DEVICE_ID);
N2kMsg.AddByte(0xff); // Reserved
N2kMsg.AddByte(0xff); // Reserved
N2kMsg.AddByte((unsigned char)Command);
N2kMsg.AddByte((unsigned char)CalibrationStopStart);
N2kMsg.AddByte(0x00); // Reserved
N2kMsg.AddByte(0xff); // Reserved
N2kMsg.AddByte(0xff); // Reserved
N2kMsg.AddByte(0xff); // Reserved
N2kMsg.AddByte(0xff); // Reserved
}
void SetN2k130851Ack(tN2kMsg &N2kMsg, int DEVICE_ID, unsigned char Command, unsigned char CalibrationStopStart) {
SetN2kPGN130851(N2kMsg, DEVICE_ID, Command, CalibrationStopStart);
}
void SetN2k130845(tN2kMsg &N2kMsg, int DEVICE_ID, uint16_t Key, uint16_t Command) {
SetN2kPGN130845(N2kMsg, DEVICE_ID, Key, Command);
}
// -------------------
// getMres()
// -------------------
/* Get magnetometer resolution */
void getMres() {
switch (Mscale)
{
// Possible magnetometer scales (and their register bit settings) are:
// 14 bit resolution (0) and 16 bit resolution (1)
case MFS_14BITS:
mRes = 10.*4912. / 8190.; // Proper scale to return milliGauss
break;
case MFS_16BITS:
mRes = 10.*4912. / 32760.0; // Proper scale to return milliGauss
break;
}
}
// -------------------
// getGres()
// -------------------
/* Get gyro resolution */
void getGres() {
switch (Gscale)
{
// Possible gyro scales (and their register bit settings) are:
// 250 DPS (00), 500 DPS (01), 1000 DPS (10), and 2000 DPS (11).
// Here's a bit of an algorith to calculate DPS/(ADC tick) based on that 2-bit value:
case GFS_250DPS:
gRes = 250.0 / 32768.0;
break;
case GFS_500DPS:
gRes = 500.0 / 32768.0;
break;
case GFS_1000DPS:
gRes = 1000.0 / 32768.0;
break;
case GFS_2000DPS:
gRes = 2000.0 / 32768.0;
break;
}
}
// -------------------
// getAres()
// -------------------
/* Get accelerometer resolution */
void getAres() {
switch (Ascale)
{
// Possible accelerometer scales (and their register bit settings) are:
// 2 Gs (00), 4 Gs (01), 8 Gs (10), and 16 Gs (11).
// Here's a bit of an algorith to calculate DPS/(ADC tick) based on that 2-bit value:
case AFS_2G:
aRes = 2.0 / 32768.0;
break;
case AFS_4G:
aRes = 4.0 / 32768.0;
break;
case AFS_8G:
aRes = 8.0 / 32768.0;
break;
case AFS_16G:
aRes = 16.0 / 32768.0;