-
Notifications
You must be signed in to change notification settings - Fork 0
/
esprosimu.ino
2487 lines (1828 loc) · 69.9 KB
/
esprosimu.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
// COMPILA SE METTO NEI PATH I FOLDER SEGUENTI
//C:\Users\Luca\Documents\Arduino\SW\libraries\i2cdevlib\Arduino; C:\Users\Luca\Documents\Arduino\SW\libraries\i2cdevlib\Arduino\I2Cdev; C:\Users\Luca\Documents\Arduino\SW\libraries\i2cdevlib\Arduino\MPU6050; C:\Users\Luca\Documents\Arduino\SW\libraries\i2cdevlib\Arduino\HMC5883L; C:\Users\Luca\Documents\Arduino\SW\ESP8266\esprosimu; C:\Users\Luca\AppData\Local\arduino15\packages\esp8266\hardware\esp8266\2.2.0\libraries; C:\Users\Luca\AppData\Local\arduino15\packages\esp8266\hardware\esp8266\2.2.0\cores\esp8266; C:\Users\Luca\Documents\Arduino\SW\libraries; C:\Users\Luca\Documents\Arduino\SW\libraries\pgmspace
#include <SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include <ros.h>
#include <Wire.h>
// ricordati di verificare in ros.h
// che sia
// #include "ArduinoHardware.h"
#define SIMULATION_STEPPER_ON 0
#define SIMULATION_LDS_ON 0
#define WEBSERVER 0
//#define DEBUG_ON 1
#define SERIAL_SPEED 115200 //default at boot= 74880
#define OPT_COMPASS 1
#define OPT_MPU6050 1
#define OPT_BLYNK 0
//#define dbg(s) printf(s);
// ///////////////////////////////////////////////////////////////////////////////
///
// DEBUG
///
// ///////////////////////////////////////////////////////////////////////////////
#ifdef DEBUG_ON
#define dbg(s) Serial.println(s);
#define dbg2(s,v) Serial.print(s);Serial.println(v);
#define dbgV(...) Serial.printf(__VA_ARGS__)
#else
#define dbg(s)
#define dbg2(s,v)
#define dbgV(...)
#endif
// ///////////////////////////////////////////////////////////////////////////////
///
// OLED DISPLAY
///
// ///////////////////////////////////////////////////////////////////////////////
#pragma region OledDisplay
//https://github.com/ThingPulse/esp8266-oled-ssd1306
#include <TimeLib.h>
#include <Wire.h> // Only needed for Arduino 1.6.5 and earlier
#include "SSD1306.h" // alias for `#include "SSD1306Wire.h"`
// Include the UI lib
#include "OLEDDisplayUi.h"
#include <CircularBuffer\CircularBuffer.h>
CircularBuffer<String, 4> displayBuffer;
// Include custom images
//#include "images.h"
const char activeSymbol[] PROGMEM = {
B00000000,
B00000000,
B00011000,
B00100100,
B01000010,
B01000010,
B00100100,
B00011000
};
const char inactiveSymbol[] PROGMEM = {
B00000000,
B00000000,
B00000000,
B00000000,
B00011000,
B00011000,
B00000000,
B00000000
};
// Initialize the OLED display using Wire library
SSD1306 display(0x3c, D2, D1);
OLEDDisplayUi ui(&display);
int screenW = 128;
int screenH = 64;
int clockCenterX = screenW / 2;
int clockCenterY = ((screenH - 16) / 2) + 16; // top yellow part is 16 px height
int clockRadius = 23;
void drawProgressBarDemo(int percent) {
// draw the progress bar
display.drawProgressBar(0, 32, 120, 10, percent);
// draw the percentage as String
display.setTextAlignment(TEXT_ALIGN_CENTER);
display.drawString(64, 15, String(percent) + "%");
}
void drawTextFlowDemo(String s) {
display.setFont(ArialMT_Plain_10);
display.setTextAlignment(TEXT_ALIGN_LEFT);
display.drawStringMaxWidth(0, 0, 128, s);
}
int displayFrameIndex = 0; // scheda corrente, incrementata dal pulsante flash
#define DISPLAY_BUFF_ROWS 4
void displayCircularBuffer(void) {
// Initialize the log buffer
// allocate memory to store 8 lines of text and 30 chars per line.
display.setLogBuffer(DISPLAY_BUFF_ROWS, 30);
// distanza in pixel tra due righe; dipende dal font size
#define INTERLINEA 11
#define BUFFER_START_Y 13
display.clear();
// 4 linee x 21 caratteri
for (uint8_t i = 0; i < DISPLAY_BUFF_ROWS; i++) {
// Print to the screen
display.drawString(0, BUFFER_START_Y + INTERLINEA * (i), displayBuffer[i]);
//display.println(displayBuffer[i]);
// Draw it to the internal screen buffer
display.drawLogBuffer(0, 0);
// Display it on the screen
}
display.display();
}
#define dbgD(s) displayBuffer.push(s); displayCircularBuffer();
// disegna un cerchio e un raggio orientato secondo l'angolo rad
void displayCompass(float rad) {
// offset da impostare per allineare la barra sul display all'asse x del magnetometro
// positivo in senso orario
#define OFFSET PI/2
#define CENTER_X 80
#define CENTER_Y 38
#define RADIUS 22
display.drawCircle(CENTER_X, CENTER_Y, RADIUS);
int dx =round( RADIUS* cos(-rad+OFFSET));
int dy =round( RADIUS* sin(-rad+ OFFSET));
display.drawLine(CENTER_X, CENTER_Y, CENTER_X + dx, CENTER_Y+ dy);
}
void setup_display() {
// Sets the current font. Available default fonts
// ArialMT_Plain_10, ArialMT_Plain_16, ArialMT_Plain_24
display.setFont(ArialMT_Plain_10);
// The ESP is capable of rendering 60fps in 80Mhz mode
// but that won't give you much time for anything else
// run it in 160Mhz mode or just set it to 30 fps
ui.setTargetFPS(30);
// Customize the active and inactive symbol
ui.setActiveSymbol(activeSymbol);
ui.setInactiveSymbol(inactiveSymbol);
// You can change this to
// TOP, LEFT, BOTTOM, RIGHT
ui.setIndicatorPosition(TOP);
// Defines where the first frame is located in the bar.
ui.setIndicatorDirection(LEFT_RIGHT);
// You can change the transition that is used
// SLIDE_LEFT, SLIDE_RIGHT, SLIDE_UP, SLIDE_DOWN
ui.setFrameAnimation(SLIDE_LEFT);
// Add frames
//ui.setFrames(frames, frameCount);
// Add overlays
//ui.setOverlays(overlays, overlaysCount);
// Initialising the UI will init the display too.
ui.init();
display.flipScreenVertically();
dbgD(".");
dbgD(".");
dbgD(".");
dbgD(".");
dbg("\nOled Display setup complete\n");
display.display();
}
#pragma endregion // OLED DISPLAY
// ///////////////////////////////////////////////////////////////////////////////
///
// HELPER FUNCTIONS
///
// ///////////////////////////////////////////////////////////////////////////////
#pragma region HelperFunctions
enum systemStatus_e {
STARTING = 0,
WIFICONNECTED,
ROSCONNECTED,
SCANNING,
ENDSCAN,
PUBLISHING,
ENDPUBLISH,
SLOWPUBLISH, // la pubblicazione termina dopo l'arrivo a HOME
SLOWSCAN //la scansione termina dopo l'arrivo a END
};
systemStatus_e SystemStatus;
void ledSeq1(int ms, int times = 3) {
pinMode(LED_BUILTIN, OUTPUT);
for (int i = 0; i < times; i++)
{
digitalWrite(LED_BUILTIN, 0); delay(ms);
digitalWrite(LED_BUILTIN, 1); delay(ms);
}
}
String ftoa(float number, uint8_t precision, uint8_t size) {
// Based on mem, 16.07.2008
// http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num = 1207226548/6#6
// prints val with number of decimal places determine by precision
// precision is a number from 0 to 6 indicating the desired decimial places
// example: printDouble(3.1415, 2); // prints 3.14 (two decimal places)
// Added rounding, size and overflow #
// ftoa(343.1453, 2, 10) -> " 343.15"
// ftoa(343.1453, 4, 7) -> "# "
// avenue33, April 10th, 2010
String s = "";
// Negative
if (number < 0.0) {
s = "-";
number = -number;
}
double rounding = 0.5;
for (uint8_t i = 0; i < precision; ++i) rounding /= 10.0;
number += rounding;
s += String(uint16_t(number)); // prints the integer part
if (precision > 0) {
s += "."; // prints the decimal point
uint32_t frac;
uint32_t mult = 1;
uint8_t padding = precision - 1;
while (precision--) mult *= 10;
frac = (number - uint16_t(number)) * mult;
uint32_t frac1 = frac;
while (frac1 /= 10) padding--;
while (padding--) s += "0";
s += String(frac, DEC); // prints the fractional part
}
if (size > 0) // checks size
if (s.length() > size) return("#");
else while (s.length() < size) s = " " + s;
return s;
}
#pragma region Hearthbeat
//const unsigned char _heartbeat_values[] = { 21,21,21,21,21,21,21,21,21,21,21,21,21,22,23,25,
//28,34,42,54,71,92,117,145,175,203,228,246,255,254,242,220,191,157,121,87,
//58,34,17,6,1,0,2,5,9,13,16,18,19,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21 };
const unsigned char _heartbeat_values[] = { 1,2,3,5,7,9,1,1,1,21,21,21,21,22,23,25,
28,34,42,54,71,92,117,145,175,203,228,246,255,254,242,220,191,157,121,87,
58,34,17,6,1,0,2,5,9,13,16,18,19,20,21,21,21,21,21,21,21,21,9,7,5,3,2,1 };
const unsigned char _HEARTBEAT_INDEXES = 64;
//byte ledPin = 9; //Must be PWM capable pin
//int heartbeat_period = 500; //[ms] 60000/120 (120 beats x min, baby)
int heartbeat_period = 1200; //[ms] 60000/70 (70 beats x min, adult in rest)
//int heartbeat_period = 1000; // slower, feels like soothing
void heartbeat(byte pwmLedPin) {
int index = (millis() % heartbeat_period) * _HEARTBEAT_INDEXES / heartbeat_period;
analogWrite(pwmLedPin, _heartbeat_values[index]);
delay(20);
}
#pragma endregion //Hearthbeat
void printESPinfo() {
dbg2("CPU freq.", ESP.getCpuFreqMHz());
dbg2("FlashChipRealSize: ", ESP.getFlashChipRealSize());
}
int scanI2C()
{
byte error, address;
int nDevices;
Serial.println("I2C Scanning...");
dbgD("I2C Scanning...");
nDevices = 0;
for (address = 1; address < 127; address++)
{
ESP.wdtFeed();
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0)
{
//dbgD("I2C found at address (dec):");
Serial.print("I2C device found at address 0x");
if (address < 16)
Serial.print("0");
dbgD("I2C found at: "+String(address));delay(1000);
Serial.print(address, HEX);
Serial.println(" !");
nDevices++;
}
else if (error == 4)
{
Serial.print("Unknow error at address 0x");
if (address < 16)
Serial.print("0");
Serial.println(address, HEX);
}
}
if (nDevices == 0)
Serial.println("\n########\nNo I2C devices found\n##############");
else
Serial.println("done\n");
return nDevices;
}
void softReset() {
Serial.println("Restarting...");
//Serial.println(WiFi.status());
//esp_wifi_wps_disable() // add this, okay
ESP.restart();
}
#pragma endregion //HelperFunctions
// ///////////////////////////////////////////////////////////////////////////////
///
// NODEMCU HW
///
// ///////////////////////////////////////////////////////////////////////////////
#pragma region NODEMCU_HW
#pragma region NODEMCU_PIN
/*
At startup, pins are configured as INPUT.
GPIO0-GPIO15 can be INPUT, OUTPUT, or INPUT_PULLUP.
GPIO16 can be INPUT, OUTPUT, or INPUT_PULLDOWN_16.
It is also XPD for deepSleep() (perhaps via a small capacitor.)
Note that GPIO6-GPIO11 are typically used to interface with the flash memory
ICs on most esp8266 modules, so these pins should not generally be used.
*/
//LED
#define Pin_LaserOn D0 // Accensione Laser
#define PIN_FLASHBUTTON D3 // PULSANTE FLASH
#define Pin_LED_TOP_B LED_BUILTIN
// I2C
#define ESP_PIN_SPI_SDA D2
#define ESP_PIN_SPI_CK D1
// LED EXT.
#define ESP_PIN_LED2 D9
#define INTERRUPT_PIN 15 // use pin 15 on ESP8266
#define LED2_ON digitalWrite(ESP_PIN_LED2, 1);
#define LED2_OFF digitalWrite(ESP_PIN_LED2, 0);
#define LED_ON digitalWrite(Pin_LED_TOP_B, 0);
#define LED_OFF digitalWrite(Pin_LED_TOP_B, 1);
//LASER
#define writeFast1(gpIO) WRITE_PERI_REG(PERIPHS_GPIO_BASEADDR + 4, (1<<gpIO));
#define writeFast0(gpIO) WRITE_PERI_REG(PERIPHS_GPIO_BASEADDR + 8, (1<<gpIO));
#define BLINK LED_ON; delay(5); LED_OFF;
#pragma endregion
void setup_HW() {
printESPinfo();
//// TFT
//tft.begin();
//tft.setRotation(3);
//tft.setTextSize(2);
//clear_screen();
//display_progress("Initialising", 5);
// LED
pinMode(Pin_LED_TOP_B, OUTPUT);
pinMode(ESP_PIN_LED2, OUTPUT);
pinMode(PIN_FLASHBUTTON, INPUT);
Wire.begin(ESP_PIN_SPI_SDA, ESP_PIN_SPI_CK);
int i2cDevices = scanI2C();
if (i2cDevices > 0)
{
printf("\nTovate %d periferiche I2C", i2cDevices);
#if OPT_MPU6050
setup_MPU();
#endif
#if OPT_COMPASS
setup_compass();
#endif
}
else
{
printf("Impossibile continuare. Soft Reset...");
dbgD("Impossibile continuare");
// ESP.restart();
}
}
// memoria libera ----
// si usa così: uint32_t free = system_get_free_heap_size();
extern "C" {
#include "user_interface.h"
}
#pragma endregion // NODEMCU_HW
// ///////////////////////////////////////////////////////////////////////////////
///
// IMU
///
// ///////////////////////////////////////////////////////////////////////////////
#pragma region IMU
const char DEVICE_NAME[] = "mpu6050";
#ifndef VECTOR_STRUCT_H
#define VECTOR_STRUCT_H
struct Vector
{
float XAxis;
float YAxis;
float ZAxis;
};
struct VectorInt
{
float x;
float y;
float z;
};
#endif
#if OPT_MPU6050
#include "I2Cdev.h"
//#include <MPU6050\MPU6050.h> // not necessary if using MotionApps include file
//#include <MPU6050.h>
#include "MPU6050_6Axis_MotionApps20.h" //libreria nella cartella MPU6050dmp
#include "helper_3dmath.h"
// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu; //MPU6050 mpu(0x69); // <-- use for AD0 high
// MPU control/status vars
bool dmpReady = false; // set true if DMP init was successful
uint8_t mpuIntStatus; // holds actual interrupt status byte from MPU
uint8_t devStatus; // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize; // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount; // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer
// // orientation/motion vars
//Quaternion q; // [w, x, y, z] quaternion container
//VectorInt16 aa; // [x, y, z] accel sensor measurements
//VectorInt16 aaReal; // [x, y, z] gravity-free accel sensor measurements
//VectorInt16 aaWorld; // [x, y, z] world-frame accel sensor measurements
//VectorFloat gravity; // [x, y, z] gravity vector
float euler[3]; // [psi, theta, phi] Euler angle container
float ypr[3]; // [yaw, pitch, roll] yaw/pitch/roll container and gravity vector
// #include <MPU6050dmp\MPU6050_6Axis_MotionApps20.h>
// MPU control/status vars
// orientation/motion vars
Quaternion q; // [w, x, y, z] quaternion container
VectorInt16 aa; // [x, y, z] accel sensor measurements
VectorInt16 gg; // [x, y, z] gyro sensor measurements
VectorInt16 aaReal; // [x, y, z] gravity-free accel sensor measurements
VectorInt16 aaWorld; // [x, y, z] world-frame accel sensor measurements
VectorFloat gravity; // [x, y, z] gravity vector
// packet structure for InvenSense teapot demo
//uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };
// ================================================================
// === INTERRUPT DETECTION ROUTINE ===
// ================================================================
volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
mpuInterrupt = true;
}
void setup_MPU() { // versione per <MPU6050\MPU6050.h>
dbgD("\nInit MPU6050...");
Wire.begin();
Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
// libreria MPU6050dmp: usa mpu.initialize();
// lib. motionaxis.... usa mpu.begin();
mpu.initialize();
pinMode(INTERRUPT_PIN, INPUT);
// verify connection
dbgD("Testing device connections...");
dbgD(mpu.testConnection() ? F("MPU6050 connected") : F("MPU6050 connection failed"));
// load and configure the DMP
dbgD("Initializing DMP...");
devStatus = mpu.dmpInitialize(); //MPU6050_6Axis_Motion lib.
//// supply your own gyro offsets here, scaled for min sensitivity
//mpu.setGyroOffsetX(220);
//mpu.setGyroOffsetY(76);
//mpu.setGyroOffsetZ(-85);
//mpu.setAccelOffsetZ(1788); // 1688 factory default for my test chip
// // turn on the DMP, now that it's ready
// supply your own gyro offsets here, scaled for min sensitivity
mpu.setXGyroOffset(220);
mpu.setYGyroOffset(76);
mpu.setZGyroOffset(-85);
mpu.setZAccelOffset(1788); // 1688 factory default for my test chip
mpu.setFullScaleAccelRange(MPU6050_ACCEL_FS_2);
// make sure it worked (returns 0 if so)
if (devStatus == 0) {
// turn on the DMP, now that it's ready
Serial.println(F("Enabling DMP..."));
mpu.setDMPEnabled(true);
// enable Arduino interrupt detection
Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
mpuIntStatus = mpu.getIntStatus();
// set our DMP Ready flag so the main loop() function knows it's okay to use it
dbg("DMP ready! Waiting for first interrupt...");
dbgD("DMP ready!");
dmpReady = true;
// get expected DMP packet size for later comparison
packetSize = mpu.dmpGetFIFOPacketSize();
}
else {
// ERROR!
// 1 = initial memory load failed
// 2 = DMP configuration updates failed
// (if it's going to break, usually the code will be 1)
dbgD("DMP Initialization failed (code ");
Serial.print(F("DMP Initialization failed (code "));
Serial.print(devStatus);
Serial.println(F(")"));
}
dbg("...done");
}
/*
void setup_MPU() { // versione per MPU6050_6Axis_MotionApps20.h
mpu.initialize();
devStatus = mpu.dmpInitialize();
mpu.setXGyroOffset(220);
mpu.setYGyroOffset(76);
mpu.setZGyroOffset(-85);
mpu.setZAccelOffset(1788); // 1688 factory default for my test chip
}
*/
void printMPUraw() {
//VectorInt16 v;
//v = mpu.readRawAccel();
//dbg("A\t);")
//dbg(v.XAxis); dbg("\t");
//dbg(v.YAxis); dbg("\t");
//dbg(v.ZAxis); dbg("\n");
// display quaternion values in easy matrix form: w x y z
mpu.dmpGetQuaternion(&q, fifoBuffer);
Serial.print("quat \tW ");
Serial.print(q.w);
Serial.print("\tX ");
Serial.print(q.x);
Serial.print("\tY ");
Serial.print(q.y);
Serial.print("\tZ ");
Serial.println(q.z);
}
void mpu_loopTest()
{
#define OUTPUT_READABLE_QUATERNION
// if programming failed, don't try to do anything
if (!dmpReady) return;
// wait for MPU interrupt or extra packet(s) available
if (!mpuInterrupt && fifoCount < packetSize) return;
// reset interrupt flag and get INT_STATUS byte
mpuInterrupt = false;
mpuIntStatus = mpu.getIntStatus();
// get current FIFO count
fifoCount = mpu.getFIFOCount();
// check for overflow (this should never happen unless our code is too inefficient)
if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
// reset so we can continue cleanly
mpu.resetFIFO();
Serial.println(F("FIFO overflow!"));
// otherwise, check for DMP data ready interrupt (this should happen frequently)
}
else if (mpuIntStatus & 0x02)
{
// wait for correct available data length, should be a VERY short wait
while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
// read a packet from FIFO
mpu.getFIFOBytes(fifoBuffer, packetSize);
// track FIFO count here in case there is > 1 packet available
// (this lets us immediately read more without waiting for an interrupt)
fifoCount -= packetSize;
#if 1 //def OUTPUT_READABLE_QUATERNION
// display quaternion values in easy matrix form: w x y z
//mpu.dmpGetQuaternion(&q, fifoBuffer);
//Serial.print("quat\t"); Serial.print(q.w);
//Serial.print("\t"); Serial.print(q.x);
//Serial.print("\t"); Serial.print(q.y);
//Serial.print("\t"); Serial.println(q.z);
readAndDisplayQuat();
#endif
#ifdef OUTPUT_TEAPOT_OSC
#ifndef OUTPUT_READABLE_QUATERNION
// display quaternion values in easy matrix form: w x y z
mpu.dmpGetQuaternion(&q, fifoBuffer);
#endif
// Send OSC message
OSCMessage msg("/imuquat");
msg.add((float)q.w);
msg.add((float)q.x);
msg.add((float)q.y);
msg.add((float)q.z);
Udp.beginPacket(outIp, outPort);
msg.send(Udp);
Udp.endPacket();
msg.empty();
#endif
#ifdef OUTPUT_READABLE_EULER
// display Euler angles in degrees
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetEuler(euler, &q);
Serial.print("euler\t");
Serial.print(euler[0] * 180 / M_PI);
Serial.print("\t");
Serial.print(euler[1] * 180 / M_PI);
Serial.print("\t");
Serial.println(euler[2] * 180 / M_PI);
#endif
#ifdef OUTPUT_READABLE_YAWPITCHROLL
// display Euler angles in degrees
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
Serial.print("ypr\t");
Serial.print(ypr[0] * 180 / M_PI);
Serial.print("\t");
Serial.print(ypr[1] * 180 / M_PI);
Serial.print("\t");
Serial.println(ypr[2] * 180 / M_PI);
#endif
#ifdef OUTPUT_READABLE_REALACCEL
// display real acceleration, adjusted to remove gravity
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetAccel(&aa, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
Serial.print("areal\t");
Serial.print(aaReal.x);
Serial.print("\t");
Serial.print(aaReal.y);
Serial.print("\t");
Serial.println(aaReal.z);
#endif
#ifdef OUTPUT_READABLE_WORLDACCEL
// display initial world-frame acceleration, adjusted to remove gravity
// and rotated based on known orientation from quaternion
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetAccel(&aa, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
Serial.print("aworld\t");
Serial.print(aaWorld.x);
Serial.print("\t");
Serial.print(aaWorld.y);
Serial.print("\t");
Serial.println(aaWorld.z);
#endif
}
}
// ///////////////////////////////////////////////////////////////////////////////
///
// COMPASS
///
// ///////////////////////////////////////////////////////////////////////////////
#pragma region compass
#if OPT_COMPASS
#include <Wire.h>
#include <HMC5883L\HMC5883L.h>
#include <compass\MyCompass.h> // derivato da HMC5883L
//MyCompass_c compass;
// compass;
MyCompass_c compass;
VectorInt16 mag;
void setup_compass() {
// Initialize Initialize HMC5883L
dbgD("Init COMPASS...");
//compass.initialize();
while (!compass.begin(2)) { delay(500); dbg("."); }
//{
// Serial.println("compass not found, check wiring!");
// delay(500);
/**/
// Set measurement range
compass.setRange(hmc5883l_range_t::HMC5883L_RANGE_1_3GA);
// Set measurement mode
compass.setMeasurementMode(hmc5883l_mode_t::HMC5883L_CONTINOUS);
// Set data rate
compass.setDataRate(hmc5883l_dataRate_t::HMC5883L_DATARATE_30HZ);
// Set number of samples averaged
compass.setSamples(hmc5883l_samples_t::HMC5883L_SAMPLES_8);
// Set calibration offset. See HMC5883L_calibration.ino
compass.setOffset(0, 0);
printf("Compass Deg.:%d", compass.getHeadingDeg());
dbgD("...COMPASS OK");
}
void compassPrintRaw() {
Vector v;
v = compass.readRaw();
dbg("Cmp\t");
dbg(v.XAxis); dbg("\t");
dbg(v.YAxis); dbg("\t");
dbg(v.ZAxis); dbg("\n");
}
#endif // COMPASS
#pragma endregion
void mpu_acquisition_dmp()
{
// if programming failed, don't try to do anything
if (!dmpReady) return;
// wait for MPU interrupt or extra packet(s) available
if (!mpuInterrupt && fifoCount < packetSize) return;
// reset interrupt flag and get INT_STATUS byte
mpuInterrupt = false;
mpuIntStatus = mpu.getIntStatus();
// get current FIFO count
fifoCount = mpu.getFIFOCount();
// check for overflow (this should never happen unless our code is too inefficient)
if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
// reset so we can continue cleanly
mpu.resetFIFO();
dbgD(F("FIFO overflow!"));
// otherwise, check for DMP data ready interrupt (this should happen frequently)
}
else if (mpuIntStatus & 0x02) {
// wait for correct available data length, should be a VERY short wait
while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
// read a packet from FIFO
mpu.getFIFOBytes(fifoBuffer, packetSize);
// track FIFO count here in case there is > 1 packet available
// (this lets us immediately read more without waiting for an interrupt)
fifoCount -= packetSize;
// display quaternion values in easy matrix form: w x y z
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.getMotion6(&aa.x, &aa.y, &aa.z, &gg.x, &gg.y, &gg.z);
// display Euler angles in degrees
///mpu.dmpGetEuler(euler, &q);
// display Euler angles in degrees
///mpu.dmpGetGravity(&gravity, &q);
///mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
// display real acceleration, adjusted to remove gravity
///mpu.dmpGetAccel(&aa, fifoBuffer);
///mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
// display initial world-frame acceleration, adjusted to remove gravity
// and rotated based on known orientation from quaternion
///mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
}
}
void mpu_acquisition_complementaryFilter()
{
// wait for MPU interrupt or extra packet(s) available
if (!mpuInterrupt && fifoCount < packetSize) return;
// reset interrupt flag and get INT_STATUS byte
mpuInterrupt = false;
mpuIntStatus = mpu.getIntStatus();
// get current FIFO count
fifoCount = mpu.getFIFOCount();
// check for overflow (this should never happen unless our code is too inefficient)
if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
// reset so we can continue cleanly
mpu.resetFIFO();
dbgD(F("FIFO overflow!"));
// otherwise, check for DMP data ready interrupt (this should happen frequently)
}
else if (mpuIntStatus & 0x02) {
// wait for correct available data length, should be a VERY short wait
while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
// read a packet from FIFO
mpu.getFIFOBytes(fifoBuffer, packetSize);
// track FIFO count here in case there is > 1 packet available
// (this lets us immediately read more without waiting for an interrupt)
fifoCount -= packetSize;
//mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.getMotion6(&aa.x, &aa.y, &aa.z, &gg.x, &gg.y, &gg.z);
// VectorInt16 mag; //compass raw data
}
// Legge compass
compass.getHeading(&mag.x, &mag.y, &mag.z);