-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathEmotiBit.cpp
More file actions
4695 lines (4340 loc) · 156 KB
/
EmotiBit.cpp
File metadata and controls
4695 lines (4340 loc) · 156 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "EmotiBit.h"
#include "EmotiBitSerial.h"
#include <math.h>
//FlashStorage(samdFlashStorage, SamdStorageAdcValues);
EmotiBit* myEmotiBit = nullptr;
void(*onInterruptCallback)(void);
#ifdef ARDUINO_FEATHER_ESP32
TaskHandle_t EmotiBitDataAcquisition;
hw_timer_t * timer = NULL;
#endif
EmotiBit::EmotiBit()
{
}
bool EmotiBit::setSamplingRates(SamplingRates s)
{
_samplingRates = s;
_samplingRates.ppg = ppgSettings.sampleRate / ppgSettings.sampleAverage;
_samplingRates.accelerometer = 25.f * pow(2.f, ((float)imuSettings.acc_odr - 6.f)); // See lookup table in BMI160 datasheet
_samplingRates.gyroscope = 25.f * pow(2.f, ((float)imuSettings.gyr_odr - 6.f)); // See lookup table in BMI160 datasheet
_samplingRates.magnetometer = 25.f * pow(2.f, ((float)imuSettings.mag_odr - 6.f)); // See lookup table in BMI160 datasheet
// ToDo: implement logic to determine return val
return true;
}
bool EmotiBit::setSamplesAveraged(SamplesAveraged s)
{
_samplesAveraged = s;
// ToDo: implement logic to determine return val
return true;
}
bool EmotiBit::getBit(uint8_t num, uint8_t bit)
{
uint8_t mask = 1 << bit;
return mask == (num & mask);
}
/*!
* @brief This API reads the data from the given register address of the sensor.
https://github.com/BoschSensortec/BMM150-Sensor-API/blob/master/bmm150.c#L579
*/
void EmotiBit::bmm150GetRegs(uint8_t address, uint8_t* dest, uint16_t len)
{
for (uint16_t i = 0; i < len; i++) {
BMI160.setRegister(BMI160_MAG_IF_2, address); //tell BMI160 to read BMM150 Address, automatically flipping the MAN_OP bit to 1
delay(BMI160_AUX_COM_DELAY);
//add poll
uint8_t p= BMI160.getRegister(BMI160_RA_STATUS);
delay(BMI160_READ_WRITE_DELAY);
while (EmotiBit::getBit(p,BMI160_STATUS_MAG_MAN_OP) != 0) { //wait for MAN_OP to switch back to 0
p= BMI160.getRegister(BMI160_RA_STATUS);
delay(BMI160_READ_WRITE_DELAY);
}
*dest = BMI160.getRegister(BMI160_RA_MAG_X_L); //read in from MAG_[X-Z]
delay(BMI160_READ_WRITE_DELAY);
dest++;
address++;
}
}
/*!
* @brief This internal API reads the trim registers of the BMM150 magnetometer and stores
* the trim values in bmm150TrimData
*
* @retval zero -> Success / +ve value -> Warning / -ve value -> Error.
https://github.com/BoschSensortec/BMM150-Sensor-API/blob/master/bmm150.c#L99
*/
void EmotiBit::bmm150ReadTrimRegisters()
{
int8_t rslt;
uint8_t trim_x1y1[2] = { 0 };
uint8_t trim_xyz_data[4] = { 0 };
uint8_t trim_xy1xy2[10] = { 0 };
uint16_t temp_msb = 0;
/* Trim register value is read */
EmotiBit::bmm150GetRegs(BMM150_DIG_X1, trim_x1y1, 2);
EmotiBit::bmm150GetRegs(BMM150_DIG_Z4_LSB, trim_xyz_data, 4);
EmotiBit::bmm150GetRegs(BMM150_DIG_Z2_LSB, trim_xy1xy2, 10);
bmm150TrimData.dig_x1 = (int8_t)trim_x1y1[0];
bmm150TrimData.dig_y1 = (int8_t)trim_x1y1[1];
bmm150TrimData.dig_x2 = (int8_t)trim_xyz_data[2];
bmm150TrimData.dig_y2 = (int8_t)trim_xyz_data[3];
temp_msb = ((uint16_t)trim_xy1xy2[3]) << 8;
bmm150TrimData.dig_z1 = (uint16_t)(temp_msb | trim_xy1xy2[2]);
temp_msb = ((uint16_t)trim_xy1xy2[1]) << 8;
bmm150TrimData.dig_z2 = (int16_t)(temp_msb | trim_xy1xy2[0]);
temp_msb = ((uint16_t)trim_xy1xy2[7]) << 8;
bmm150TrimData.dig_z3 = (int16_t)(temp_msb | trim_xy1xy2[6]);
temp_msb = ((uint16_t)trim_xyz_data[1]) << 8;
bmm150TrimData.dig_z4 = (int16_t)(temp_msb | trim_xyz_data[0]);
bmm150TrimData.dig_xy1 = trim_xy1xy2[9];
bmm150TrimData.dig_xy2 = (int8_t)trim_xy1xy2[8];
temp_msb = ((uint16_t)(trim_xy1xy2[5] & 0x7F)) << 8;
bmm150TrimData.dig_xyz1 = (uint16_t)(temp_msb | trim_xy1xy2[4]);
}
uint8_t EmotiBit::setup(String firmwareVariant)
{
// Update firmware_variant information
firmware_variant = firmwareVariant;
// ToDo: find a way to extract variant string from build flag
#ifdef EMOTIBIT_PPG_100HZ
firmware_variant = firmware_variant + "_PPG_100Hz";
#endif
#ifdef ARDUINO_FEATHER_ESP32
esp_bt_controller_disable();
// ToDo: assess similarity with btStop();
setCpuFrequencyMhz(CPU_HZ / 1000000); // 80MHz has been tested working to save battery life
#endif
EmotiBitVersionController emotiBitVersionController;
//EmotiBitUtilities::printFreeRAM("Begining of setup", 1);
Serial.print("I2C data pin: "); Serial.println(EmotiBitVersionController::EMOTIBIT_I2C_DAT_PIN);
Serial.print("I2C clk pin: "); Serial.println(EmotiBitVersionController::EMOTIBIT_I2C_CLK_PIN);
Serial.print("hibernate pin: "); Serial.println(EmotiBitVersionController::HIBERNATE_PIN);
Serial.print("chip sel pin: "); Serial.println(EmotiBitVersionController::SD_CARD_CHIP_SEL_PIN);
Barcode barcode;
barcode.rawCode = "";
String factoryTestSerialOutput;
factoryTestSerialOutput.reserve(150);
factoryTestSerialOutput += EmotiBitSerial::MSG_START_CHAR;
uint32_t now = millis();
Serial.print("Firmware version: ");
Serial.println(firmware_version);
Serial.print("firmware_variant: ");
Serial.println(firmware_variant);
// Wait for possible factory test init prompt
while (!Serial.available() && millis() - now < 2000)
{
}
while (Serial.available())
{
char input;
input = Serial.read();
if (input == EmotiBitSerial::Inputs::RESET)
{
// provision to reset added to enable connection to enterprise wifi. weird quirk in enterprise wifi connection. Seeehttps://github.com/EmotiBit/EmotiBit_FeatherWing/pull/250
restartMcu();
}
else if (input == EmotiBitFactoryTest::INIT_FACTORY_TEST)
{
uint32_t waitStarForBarcode = millis();
testingMode = TestingMode::FACTORY_TEST;
String ackString;
ackString += EmotiBitSerial::MSG_START_CHAR;
EmotiBitFactoryTest::updateOutputString(ackString, EmotiBitFactoryTest::TypeTag::FIRMWARE_VERSION, firmware_version.c_str());
ackString = ackString.substring(0, ackString.length() - 1);
ackString += EmotiBitSerial::MSG_TERM_CHAR;
Serial.print(ackString);
Serial.println("\nEntered FACTORY TEST MODE");
bool barcodeReceived = false;
while (Serial.available() || !barcodeReceived)
{
char input;
input = Serial.read();
if (input == EmotiBitSerial::MSG_START_CHAR)
{
String msg = Serial.readStringUntil(EmotiBitSerial::MSG_TERM_CHAR);
Serial.print("Barcode msg: ");
Serial.println(msg);
String msgTypeTag = msg.substring(0, 2);
if (msgTypeTag.equals(EmotiBitFactoryTest::TypeTag::EMOTIBIT_BARCODE))
{
EmotiBitPacket::getPacketElement(msg, barcode.rawCode, 3);
barcodeReceived = true;
Serial.print("barcode.rawCode: ");
Serial.println(barcode.rawCode);
}
else
{
Serial.println("Barcode not received in the correct packet format.");
}
}
if (millis() - waitStarForBarcode > 3000)
break;
}
}
else
{
// do nothing. Junk input.
}
// remove any other char in the buffer before proceeding
while (Serial.available())
{
Serial.read();
}
}
// Added initPinMapping(UNKOWN) to perform basic pin measurements before isEmotiBitReady is successful
emotiBitVersionController.initPinMapping(EmotiBitVersionController::EmotiBitVersion::UNKNOWN);
// Test code to assess pin states
//const int nTestPins = 3;
//int testPins[nTestPins] =
//{
// emotiBitVersionController.getAssignedPin(EmotiBitPinName::BMI_INT1),
// emotiBitVersionController.getAssignedPin(EmotiBitPinName::BMM_INT),
// emotiBitVersionController.getAssignedPin(EmotiBitPinName::PPG_INT)
//};
//for (int t = 0; t < nTestPins; t++)
//{
// pinMode(testPins[t], INPUT);
// Serial.print("Pin ");
// Serial.print(t);
// Serial.print(": ");
// Serial.println(digitalRead(testPins[t]));
//}
if (emotiBitVersionController.isEmotiBitReady())
{
Serial.println("EmotiBit ready");
if (testingMode == TestingMode::FACTORY_TEST)
{
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::EMOTIBIT_READY, EmotiBitFactoryTest::TypeTag::TEST_PASS);
}
}
else
{
if (testingMode == TestingMode::FACTORY_TEST)
{
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::EMOTIBIT_READY, EmotiBitFactoryTest::TypeTag::TEST_FAIL);
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::SETUP_COMPLETE, EmotiBitFactoryTest::TypeTag::TEST_FAIL);
Serial.println(factoryTestSerialOutput);
}
#ifdef ADAFRUIT_FEATHER_M0
PORT->Group[PORTA].PINCFG[17].bit.DRVSTR = 1; // Increase SCL pin drive strength to over-power current pulling up
#endif
// Set Feather LED LOW
pinMode(EmotiBitVersionController::EMOTIBIT_I2C_CLK_PIN, OUTPUT);
// make sure the pin DRV strength is set to sink appropriate current
digitalWrite(EmotiBitVersionController::EMOTIBIT_I2C_CLK_PIN, LOW);
// Not putting EmotiBit to sleep helps with the FW installer process
// Test code to assess pin states
//for (int t = 0; t < nTestPins; t++)
//{
// pinMode(testPins[t], INPUT);
// Serial.print("Pin ");
// Serial.print(t);
// Serial.print(": ");
// Serial.println(digitalRead(testPins[t]));
//}
setupFailed("SD-Card not detected", emotiBitVersionController.getAssignedPin(EmotiBitPinName::EMOTIBIT_BUTTON));
}
bool status = true;
if (_EmotiBit_i2c != nullptr)
{
delete(_EmotiBit_i2c);
}
#ifdef ADAFRUIT_FEATHER_M0
Serial.println("Setting up I2C For M0...");
_EmotiBit_i2c = new TwoWire(&sercom1, EmotiBitVersionController::EMOTIBIT_I2C_DAT_PIN, EmotiBitVersionController::EMOTIBIT_I2C_CLK_PIN);
_EmotiBit_i2c->begin();
// ToDo: detect if i2c init fails
pinPeripheral(EmotiBitVersionController::EMOTIBIT_I2C_DAT_PIN, PIO_SERCOM);
pinPeripheral(EmotiBitVersionController::EMOTIBIT_I2C_CLK_PIN, PIO_SERCOM);
#elif defined ARDUINO_FEATHER_ESP32
_EmotiBit_i2c = new TwoWire(1);
Serial.println("Setting up I2C For ESP32...");
status = _EmotiBit_i2c->begin(EmotiBitVersionController::EMOTIBIT_I2C_DAT_PIN, EmotiBitVersionController::EMOTIBIT_I2C_CLK_PIN);
if (status)
{
Serial.println("I2c setup complete");
}
else
{
Serial.println("I2c setup failed");
}
#endif
uint32_t i2cRate = 100000;
Serial.print("Setting clock to ");
Serial.println(i2cRate);
_EmotiBit_i2c->setClock(i2cRate);
if (testingMode == TestingMode::FACTORY_TEST)
{
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::I2C_COMM_INIT, EmotiBitFactoryTest::TypeTag::TEST_PASS);
}
Serial.print("Initializing NVM controller: ");
if (_emotibitNvmController.init(*_EmotiBit_i2c))
{
Serial.println("success");
if (testingMode == TestingMode::FACTORY_TEST)
{
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::EMOTIBIT_STORAGE, EmotiBitFactoryTest::TypeTag::TEST_PASS);
}
}
else
{
Serial.println("fail");
if (testingMode == TestingMode::FACTORY_TEST)
{
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::EMOTIBIT_STORAGE, EmotiBitFactoryTest::TypeTag::TEST_FAIL);
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::SETUP_COMPLETE, EmotiBitFactoryTest::TypeTag::TEST_FAIL);
Serial.println(factoryTestSerialOutput);
}
setupFailed("EEPROM");
}
if (testingMode == TestingMode::FACTORY_TEST && barcode.rawCode != "")
{
// parse the barcode
EmotiBitFactoryTest::parseBarcode(&barcode);
Serial.print("barcode: ");
Serial.println(barcode.rawCode);
Serial.print("sku: ");
Serial.println(barcode.sku);
Serial.print("hwVersion: ");
Serial.println(barcode.hwVersion);
Serial.print("emotibitSerialNumber: ");
Serial.println(barcode.emotibitSerialNumber);
bool hwValidation, skuValidation = false;
if (emotiBitVersionController.validateBarcodeInfo(*(_EmotiBit_i2c), barcode, hwValidation, skuValidation))
{
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::VERSION_VALIDATION, EmotiBitFactoryTest::TypeTag::TEST_PASS);
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::SKU_VALIDATION, EmotiBitFactoryTest::TypeTag::TEST_PASS);
if (!emotiBitVersionController.writeVariantInfoToNvm(_emotibitNvmController, barcode))
{
sleep(false);
}
}
else
{
if (hwValidation)
{
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::VERSION_VALIDATION, EmotiBitFactoryTest::TypeTag::TEST_PASS);
}
else
{
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::VERSION_VALIDATION, EmotiBitFactoryTest::TypeTag::TEST_FAIL);
}
if (skuValidation)
{
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::SKU_VALIDATION, EmotiBitFactoryTest::TypeTag::TEST_PASS);
}
else
{
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::SKU_VALIDATION, EmotiBitFactoryTest::TypeTag::TEST_FAIL);
}
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::SETUP_COMPLETE, EmotiBitFactoryTest::TypeTag::TEST_FAIL);
Serial.println(factoryTestSerialOutput);
sleep(false);
}
}
if (!emotiBitVersionController.getEmotiBitVariantInfo(_emotibitNvmController, _hwVersion, emotiBitSku, emotibitSerialNumber, emotibitDeviceId))
{
if (!emotiBitVersionController.detectVariantFromHardware(*(_EmotiBit_i2c), _hwVersion, emotiBitSku))
{
setupFailed("CANNOT IDENTIFY HARDWARE");
}
}
// device ID for V3 and lower will be updated after Temp/Humidity sensor is setup below
String fwVersionModifier = "";
if (testingMode == TestingMode::ACUTE)
{
fwVersionModifier = "-TA";
_debugMode = true;
}
else if (testingMode == TestingMode::CHRONIC)
{
fwVersionModifier = "-TC";
_debugMode = true;
}
else if (testingMode == TestingMode::FACTORY_TEST)
{
fwVersionModifier = "-FT";
}
firmware_version += fwVersionModifier;
Serial.print("\n\nEmotiBit HW version: ");
Serial.println(EmotiBitVersionController::getHardwareVersion(_hwVersion));
Serial.print("Firmware version: ");
Serial.println(firmware_version);
Serial.print("firmware_variant: ");
Serial.println(firmware_variant);
if (testingMode == TestingMode::FACTORY_TEST)
{
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::FIRMWARE_VERSION, firmware_version.c_str());
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::EMOTIBIT_VERSION, EmotiBitVersionController::getHardwareVersion(_hwVersion));
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::EMOTIBIT_SERIAL_NUMBER, String(emotibitSerialNumber).c_str());
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::EMOTIBIT_SKU_TYPE, emotiBitSku.c_str());
}
//Serial.println("All Serial inputs must be used with **No Line Ending** option from the serial monitor");
bool initResult = false;
// IMPORTANT. Need pin initialization(Performed below) for emotibit to work
// initializing the pin and constant mapping
emotiBitVersionController.initPinMapping(_hwVersion); // Any unknown version is handled in the version detection code.
initResult = emotiBitVersionController.initConstantMapping(_hwVersion);
// Constant Mapping fails if NUM_CONSTANTS not updated in versionController Class
if (!initResult)
{
Serial.println("Constant Mapping Failed. Stopping execution");
emotiBitVersionController.initConstantMapping(EmotiBitVersionController::EmotiBitVersion::V03B);// Assume the version is V03B to set Hibernate level as Required
setupFailed("CONSTANT MAPPING");
}
#if defined(DEBUG)
// testing if mapping was successful
emotiBitVersionController.echoPinMapping();
emotiBitVersionController.echoConstants();
#endif
// ToDo: Create a organized way to store class vairables
// Set board-specific pins
_batteryReadPin = emotiBitVersionController.getAssignedPin(EmotiBitPinName::BATTERY_READ_PIN);
buttonPin = emotiBitVersionController.getAssignedPin(EmotiBitPinName::EMOTIBIT_BUTTON);
//TODO: Find a better way to swap pin assignments in different modes
_emotiBitSystemConstants[(int)SystemConstants::EMOTIBIT_HIBERNATE_LEVEL] = emotiBitVersionController.getSystemConstant(SystemConstants::EMOTIBIT_HIBERNATE_LEVEL);
_emotiBitSystemConstants[(int)SystemConstants::EMOTIBIT_HIBERNATE_PIN_MODE] = emotiBitVersionController.getSystemConstant(SystemConstants::EMOTIBIT_HIBERNATE_PIN_MODE);
_emotiBitSystemConstants[(int)SystemConstants::LED_DRIVER_CURRENT] = emotiBitVersionController.getSystemConstant(SystemConstants::LED_DRIVER_CURRENT);
// Setup switch
if (buttonPin != LED_BUILTIN)
{
// If the LED_BUILTIN and buttonPin are the same leave it as it was
// Otherwise setup the input
pinMode(buttonPin, INPUT);
}
// Setup battery Reading
pinMode(_batteryReadPin, INPUT);
// Set board specific constants
_adcBits = emotiBitVersionController.getMathConstant(MathConstants::ADC_BITS);
adcRes = emotiBitVersionController.getMathConstant(MathConstants::ADC_MAX_VALUE);
_vcc = emotiBitVersionController.getMathConstant(MathConstants::VCC);
//edrAmplification = emotiBitVersionController.getMathConstant(MathConstants::EDR_AMPLIFICATION);
//edaFeedbackAmpR = emotiBitVersionController.getMathConstant(MathConstants::EDA_FEEDBACK_R);
//vRef1 = emotiBitVersionController.getMathConstant(MathConstants::VREF1);
//vRef2 = emotiBitVersionController.getMathConstant(MathConstants::VREF2);
//_edaSeriesResistance = emotiBitVersionController.getMathConstant(MathConstants::EDA_SERIES_RESISTOR);
if (!_outDataPackets.reserve(OUT_MESSAGE_RESERVE_SIZE)) {
Serial.println("Failed to reserve memory for output");
while (true) {
setupFailed("FAILED TO RESERVE MEM FOR OUT MESSAGE");
}
}
now = millis();
// prompt for serial input
Serial.println("Enter " + String(EmotiBitSerial::Inputs::CRED_UPDATE) + " to enter WiFi config edit mode (Add/ Delete WiFi creds)");
while (!Serial.available() && millis() - now < 2000)
{
}
#ifdef ADAFRUIT_FEATHER_M0
AdcCorrection::AdcCorrectionValues adcCorrectionValues;
#endif
while (Serial.available())
{
char input;
input = Serial.read();
if (input == EmotiBitSerial::Inputs::ADC_CORRECTION_MODE)
{
#ifdef ADAFRUIT_FEATHER_M0
AdcCorrection adcCorrection;
if (!adcCorrection.begin(adcCorrectionValues._gainCorrection, adcCorrectionValues._offsetCorrection, adcCorrectionValues.valid))
{
Serial.println("Exiting ADC Correction.");
delay(3000);
break;
}
if (adcCorrectionValues.valid)
{
adcCorrection.echoResults(adcCorrectionValues._gainCorrection, adcCorrectionValues._offsetCorrection);
}
#endif
}
else if (input == EmotiBitSerial::Inputs::CRED_UPDATE)
{
Serial.println("Wifi Credential edit mode");
setupSdCard(false);
// ToDo: Find a better name that highlights "updating through Serial".
if(_emotibitConfigManager.init(&SD))
{
_emotibitConfigManager.updateWiFiCredentials(firmware_version, _configFilename, EmotiBitWiFi::getMaxNumCredentialAllowed());
}
else
{
// could not attach init EmotiBitConfigManager
Serial.println("EmotiBitConfigManager initialization failed. Skipped credential update.");
}
}
else if (input == EmotiBitSerial::Inputs::DEBUG_MODE)
{
_debugMode = true;
Serial.println("\nENTERING DEBUG MODE\n");
}
else
{
Serial.println("invalid serial input");
}
}
// Setup data buffers
dataDoubleBuffers[(uint8_t)EmotiBit::DataType::EDA] = &eda;
dataDoubleBuffers[(uint8_t)EmotiBit::DataType::EDL] = &edl;
dataDoubleBuffers[(uint8_t)EmotiBit::DataType::EDR] = &edr;
dataDoubleBuffers[(uint8_t)EmotiBit::DataType::PPG_INFRARED] = &ppgInfrared;
dataDoubleBuffers[(uint8_t)EmotiBit::DataType::PPG_RED] = &ppgRed;
dataDoubleBuffers[(uint8_t)EmotiBit::DataType::PPG_GREEN] = &ppgGreen;
dataDoubleBuffers[(uint8_t)EmotiBit::DataType::TEMPERATURE_0] = &temp0;
dataDoubleBuffers[(uint8_t)EmotiBit::DataType::TEMPERATURE_1] = &temp1;
dataDoubleBuffers[(uint8_t)EmotiBit::DataType::THERMOPILE] = &therm0;
dataDoubleBuffers[(uint8_t)EmotiBit::DataType::HUMIDITY_0] = &humidity0;
dataDoubleBuffers[(uint8_t)EmotiBit::DataType::ACCELEROMETER_X] = &accelX;
dataDoubleBuffers[(uint8_t)EmotiBit::DataType::ACCELEROMETER_Y] = &accelY;
dataDoubleBuffers[(uint8_t)EmotiBit::DataType::ACCELEROMETER_Z] = &accelZ;
dataDoubleBuffers[(uint8_t)EmotiBit::DataType::GYROSCOPE_X] = &gyroX;
dataDoubleBuffers[(uint8_t)EmotiBit::DataType::GYROSCOPE_Y] = &gyroY;
dataDoubleBuffers[(uint8_t)EmotiBit::DataType::GYROSCOPE_Z] = &gyroZ;
dataDoubleBuffers[(uint8_t)EmotiBit::DataType::MAGNETOMETER_X] = &magX;
dataDoubleBuffers[(uint8_t)EmotiBit::DataType::MAGNETOMETER_Y] = &magY;
dataDoubleBuffers[(uint8_t)EmotiBit::DataType::MAGNETOMETER_Z] = &magZ;
dataDoubleBuffers[(uint8_t)EmotiBit::DataType::BATTERY_VOLTAGE] = &batteryVoltage;
dataDoubleBuffers[(uint8_t)EmotiBit::DataType::BATTERY_PERCENT] = &batteryPercent;
dataDoubleBuffers[(uint8_t)EmotiBit::DataType::DATA_OVERFLOW] = &dataOverflow;
dataDoubleBuffers[(uint8_t)EmotiBit::DataType::DATA_CLIPPING] = &dataClipping;
dataDoubleBuffers[(uint8_t)EmotiBit::DataType::DEBUG] = &debugBuffer;
// Print board-specific settings
if (testingMode == TestingMode::ACUTE || testingMode == TestingMode::CHRONIC)
{
Serial.println("\nHW version-specific settings:");
Serial.print("buttonPin = "); Serial.println(buttonPin);
Serial.print("_batteryReadPin = "); Serial.println(_batteryReadPin);
Serial.print("Hibernate Pin = "); Serial.println(EmotiBitVersionController::HIBERNATE_PIN);
Serial.print("_vcc = "); Serial.println(_vcc);
Serial.print("adcRes = "); Serial.println(adcRes);
Serial.print("LED Driver Current Level = "); Serial.println(_emotiBitSystemConstants[(int)SystemConstants::LED_DRIVER_CURRENT]);
}
Serial.println("\nSensor setup:");
// setup sampling rates
EmotiBit::SamplingRates samplingRates;
samplingRates.accelerometer = (float) BASE_SAMPLING_FREQ / (float) IMU_SAMPLING_DIV;
samplingRates.gyroscope = (float) BASE_SAMPLING_FREQ / (float) IMU_SAMPLING_DIV;
samplingRates.magnetometer = (float) BASE_SAMPLING_FREQ / (float) IMU_SAMPLING_DIV;
samplingRates.eda = (float) BASE_SAMPLING_FREQ / (float) EDA_SAMPLING_DIV;
samplingRates.humidity = (float) BASE_SAMPLING_FREQ / (float) TEMPERATURE_0_SAMPLING_DIV / 2.f;
samplingRates.temperature = (float) BASE_SAMPLING_FREQ / (float) TEMPERATURE_0_SAMPLING_DIV / 2.f;
samplingRates.temperature_1 = (float)BASE_SAMPLING_FREQ / (float)TEMPERATURE_1_SAMPLING_DIV;
samplingRates.thermopile = (float)BASE_SAMPLING_FREQ / (float)THERMOPILE_SAMPLING_DIV;
setSamplingRates(samplingRates);
// ToDo: make target down-sampled rates more transparent
EmotiBit::SamplesAveraged samplesAveraged;
samplesAveraged.eda = samplingRates.eda / 15.f;
samplesAveraged.humidity = (float)samplingRates.humidity / 7.5f;
samplesAveraged.temperature = (float)samplingRates.temperature / 7.5f;
samplesAveraged.temperature_1 = 1;
if (thermopileMode == MODE_CONTINUOUS)
{
samplesAveraged.thermopile = 1;
}
else
{
samplesAveraged.thermopile = (float)samplingRates.thermopile / 7.5f;
}
samplesAveraged.battery = (float) BASE_SAMPLING_FREQ / (float) BATTERY_SAMPLING_DIV / (0.2f);
setSamplesAveraged(samplesAveraged);
Serial.println("\nSet Samples averaged:");
// setup LED DRIVER
Serial.print("Initializing LedController....");
// ToDo: add a success or fail return statement for LED driver
status = led.begin(_EmotiBit_i2c, _hwVersion);
if (status)
{
chipBegun.NCP5623 = true;
if (testingMode == TestingMode::FACTORY_TEST)
{
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::LED_CONTROLLER, EmotiBitFactoryTest::TypeTag::TEST_PASS);
}
Serial.println("Completed");
}
else
{
Serial.println("Failed");
if (testingMode == TestingMode::FACTORY_TEST)
{
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::LED_CONTROLLER, EmotiBitFactoryTest::TypeTag::TEST_FAIL);
Serial.println(factoryTestSerialOutput);
setupFailed("LED CONTROLLER");
}
}
//// Setup PPG sensor
Serial.print("Initializing MAX30101....");
// Initialize sensor
while (ppgSensor.begin(*_EmotiBit_i2c) == false) // reads the part number to confirm device
{
if (testingMode == TestingMode::FACTORY_TEST)
{
// FAIL
}
Serial.println("MAX30101 was not found. Please check wiring/power. ");
_EmotiBit_i2c->flush();
_EmotiBit_i2c->endTransmission();
_EmotiBit_i2c->clearWriteError();
_EmotiBit_i2c->end();
static uint32_t hibernateTimer = millis();
if (millis() - hibernateTimer > 2000)
{
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::PPG_SENSOR, EmotiBitFactoryTest::TypeTag::TEST_FAIL);
Serial.println(factoryTestSerialOutput);
setupFailed("PPG");
}
}
ppgSensor.wakeUp();
ppgSensor.softReset();
ppgSensor.setup(
ppgSettings.ledPowerLevel,
ppgSettings.sampleAverage,
ppgSettings.ledMode,
ppgSettings.sampleRate,
ppgSettings.pulseWidth,
ppgSettings.adcRange
);
ppgSensor.enableDIETEMPRDY(); //Enable the temp ready interrupt. This is required to read die temperatures. Refer datasheet.
ppgSensor.check();
chipBegun.MAX30101 = true;
if (testingMode == TestingMode::FACTORY_TEST)
{
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::PPG_SENSOR, EmotiBitFactoryTest::TypeTag::TEST_PASS);
}
Serial.println("Completed");
// Setup IMU
Serial.print("Initializing BMI160+BMM150.... ");
status = BMI160.begin(BMI160GenClass::I2C_MODE, *_EmotiBit_i2c);
if (status)
{
uint8_t dev_id = BMI160.getDeviceID();
Serial.print("DEVICE ID: ");
Serial.print(dev_id, HEX);
if (testingMode == TestingMode::FACTORY_TEST)
{
// Add PASS
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::ACCEL_GYRO, EmotiBitFactoryTest::TypeTag::TEST_PASS);
// ToDo: add the device ID
String id = String(dev_id, HEX);
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::IMU_ID, id.c_str());
}
// Accelerometer
_accelerometerRange = 8;
BMI160.setAccelerometerRange(_accelerometerRange);
BMI160.setAccelDLPFMode(BMI160DLPFMode::BMI160_DLPF_MODE_NORM);
//BMI160.setAccelRate(BMI160AccelRate::BMI160_ACCEL_RATE_25HZ);
BMI160.setAccelRate(BMI160AccelRate::BMI160_ACCEL_RATE_100HZ);
// Gyroscope
_gyroRange = 1000;
BMI160.setGyroRange(_gyroRange);
BMI160.setGyroDLPFMode(BMI160DLPFMode::BMI160_DLPF_MODE_NORM);
//BMI160.setGyroRate(BMI160GyroRate::BMI160_GYRO_RATE_25HZ);
BMI160.setGyroRate(BMI160GyroRate::BMI160_GYRO_RATE_100HZ);
// Magnetometer
BMI160.setRegister(BMI160_MAG_IF_0, BMM150_BASED_I2C_ADDR, BMM150_BASED_I2C_MASK); // I2C MAG
delay(BMI160_AUX_COM_DELAY);
//initially load into setup mode to read trim values
BMI160.setRegister(BMI160_MAG_IF_1, BMI160_MANUAL_MODE_EN_MSK, BMI160_MANUAL_MODE_EN_MSK);
delay(BMI160_AUX_COM_DELAY);
EmotiBit::bmm150ReadTrimRegisters();
BMI160.setRegister(BMI160_MAG_IF_2, BMM150_DATA_REG); // ADD_BMM_DATA
delay(BMI160_AUX_COM_DELAY);
//BMI160.setRegister(BMI160_MAG_IF_3, BMM150_OPMODE_REG); // ADD_BMM_MEASURE
//delay(BMI160_AUX_COM_DELAY);
// Following example at https://github.com/BoschSensortec/BMI160_driver#auxiliary-fifo-data-parsing
// Put the BMM150 in normal mode (may or may not be necessary if putting in force mode later)
// BMI160.setRegister(BMM150_OPMODE_REG, BMM150_DATA_RATE_10HZ | BMM150_NORMAL_MODE);
//BMI160.setRegister(BMI160_MAG_IF_4, BMM150_DATA_RATE_10HZ | BMM150_NORMAL_MODE);
//BMI160.setRegister(BMI160_MAG_IF_4, BMM150_NORMAL_MODE);
BMI160.reg_write_bits(BMI160_MAG_IF_4, BMM150_NORMAL_MODE, BMM150_OP_MODE_BIT, BMM150_OP_MODE_LEN);
BMI160.setRegister(BMI160_MAG_IF_3, BMM150_OP_MODE_ADDR);
delay(BMI160_AUX_COM_DELAY);
// Already done in setup
///* Set BMM150 repetitions for X/Y-Axis */
//BMI160.setRegister(BMI160_MAG_IF_4, BMM150_LOWPOWER_REPXY); //Added for BMM150 Support
//BMI160.setRegister(BMI160_MAG_IF_3, BMM150_XY_REP_REG); //Added for BMM150 Support
//delay(BMI160_AUX_COM_DELAY);
///* Set BMM150 repetitions for Z-Axis */
//BMI160.setRegister(BMI160_MAG_IF_4, BMM150_LOWPOWER_REPXY); //Added for BMM150 Support
//BMI160.setRegister(BMI160_MAG_IF_3, BMM150_Z_REP_REG); //Added for BMM150 Support
//delay(BMI160_AUX_COM_DELAY);
//BMI160.setRegister(BMI160_MAG_IF_4, BMM150_DATA_RATE_25HZ);
BMI160.reg_write_bits(BMI160_MAG_IF_4, BMM150_DATA_RATE_10HZ, BMM150_DATA_RATE_BIT, BMM150_DATA_RATE_LEN);
BMI160.setRegister(BMI160_MAG_IF_3, BMM150_OP_MODE_ADDR);
delay(BMI160_AUX_COM_DELAY);
//BMI160.setRegister(BMI160_MAG_IF_4, BMM150_FORCED_MODE);
BMI160.reg_write_bits(BMI160_MAG_IF_4, BMM150_FORCED_MODE, BMM150_OP_MODE_BIT, BMM150_OP_MODE_LEN);
BMI160.setRegister(BMI160_MAG_IF_3, BMM150_OP_MODE_ADDR);
delay(BMI160_AUX_COM_DELAY);
// Setup the BMI160 AUX
// Set the auto mode address
BMI160.setRegister(BMI160_MAG_IF_2, BMM150_DATA_X_LSB);
delay(BMI160_AUX_COM_DELAY);
// Set the AUX ODR
BMI160.setMagRate(BMI160MagRate::BMI160_MAG_RATE_100HZ);
// Disable manual mode (i.e. enable auto mode)
BMI160.setRegister(BMI160_MAG_IF_1, BMI160_DISABLE, BMI160_MANUAL_MODE_EN_MSK);
// Set the burst length
BMI160.setRegister(BMI160_MAG_IF_1, BMI160_AUX_READ_BURST_MSK, BMI160_AUX_READ_BURST_MSK); // MAG data mode 8 byte burst
delay(BMI160_AUX_COM_DELAY);
// Bosch code sets the I2C register again here for an unknown reason
BMI160.setRegister(BMI160_MAG_IF_0, BMM150_BASED_I2C_ADDR, BMM150_BASED_I2C_MASK); // I2C MAG
delay(BMI160_AUX_COM_DELAY);
// Setup the FIFO
BMI160.setAccelFIFOEnabled(true);
_imuFifoFrameLen += 6;
BMI160.setGyroFIFOEnabled(true);
_imuFifoFrameLen += 6;
BMI160.setMagFIFOEnabled(true);
_imuFifoFrameLen += 8;
BMI160.setFIFOHeaderModeEnabled(false);
if (_imuFifoFrameLen > _maxImuFifoFrameLen)
{
// ToDo: handle _imuFifoFrameLen > _maxImuFifoFrameLen
Serial.println("UNHANDLED CASE: _imuFifoFrameLen > _maxImuFifoFrameLen");
while (true);
}
chipBegun.BMI160 = true;
chipBegun.BMM150 = true;
}
else
{
if (testingMode == TestingMode::FACTORY_TEST)
{
// Add FAIL
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::ACCEL_GYRO, EmotiBitFactoryTest::TypeTag::TEST_FAIL);
Serial.println(factoryTestSerialOutput);
}
setupFailed("IMU");
}
if ((int)_hwVersion == (int)EmotiBitVersionController::EmotiBitVersion::V03B)
{
_enableDigitalFilter.mx = true;
_enableDigitalFilter.my = true;
_enableDigitalFilter.mz = true;
Serial.println("Enabling digital filtering for magnetometer");
}
Serial.println(" ... Completed");
// ToDo: Add interrupts to accurately record timing of data capture
//BMI160.detachInterrupt();
//BMI160.setRegister()
if ((int)_hwVersion <= (int)EmotiBitVersionController::EmotiBitVersion::V03B)
{
// Setup Temperature / Humidity Sensor
Serial.print("Initializing SI-7013");
// moved the macro definition from EdaCorrection to EmotiBitVersionController
#ifdef USE_ALT_SI7013
status = tempHumiditySensor.setup(*_EmotiBit_i2c, 0x41);
#else
status = tempHumiditySensor.setup(*_EmotiBit_i2c);
#endif
if (status)
{
if (testingMode == TestingMode::FACTORY_TEST)
{
// Add PASS
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::TEMP_SENSOR, EmotiBitFactoryTest::TypeTag::TEST_PASS);
}
// Si-7013 detected on the EmotiBit
tempHumiditySensor.changeSetting(Si7013::Settings::RESOLUTION_H11_T11);
tempHumiditySensor.changeSetting(Si7013::Settings::ADC_NORMAL);
tempHumiditySensor.changeSetting(Si7013::Settings::VIN_UNBUFFERED);
tempHumiditySensor.changeSetting(Si7013::Settings::VREFP_VDDA);
tempHumiditySensor.changeSetting(Si7013::Settings::ADC_NO_HOLD);
tempHumiditySensor.readSerialNumber();
Serial.print("\tSi7013 Electronic Serial Number: ");
Serial.print(tempHumiditySensor.sernum_a);
Serial.print(", ");
Serial.print(tempHumiditySensor.sernum_b);
// update the device ID for V3 and lower
emotibitDeviceId = String(tempHumiditySensor.sernum_a) + "-" + String(tempHumiditySensor.sernum_b);
//Serial.print("\n");
Serial.print("\tModel: ");
Serial.print(tempHumiditySensor._model);
chipBegun.SI7013 = true;
tempHumiditySensor.startHumidityTempMeasurement();
}
else
{
if (testingMode == TestingMode::FACTORY_TEST)
{
// Add fail
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::TEMP_SENSOR, EmotiBitFactoryTest::TypeTag::TEST_FAIL);
Serial.println(factoryTestSerialOutput);
}
setupFailed("TEMP/HUMIDITY");
}
Serial.println(" ... Completed");
}
if (emotiBitSku.equals(EmotiBitVariants::EMOTIBIT_SKU_MD))
{
// Thermopile
Serial.print("Initializing MLX90632... ");
MLX90632::status returnError; // Required as a parameter for begin() function in the MLX library
status = thermopile.begin(deviceAddress.MLX, *_EmotiBit_i2c, returnError);
if (status)
{
if (testingMode == TestingMode::FACTORY_TEST)
{
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::THERMOPILE, EmotiBitFactoryTest::TypeTag::TEST_PASS);
}
Serial.println("Success");
thermopile.setMeasurementRate(thermopileFs);
thermopile.setMode(thermopileMode);
uint8_t thermMode = thermopile.getMode();
if (thermMode == MODE_CONTINUOUS)
{
Serial.print("MODE_CONTINUOUS");
}
if (thermMode == MODE_STEP)
{
Serial.print("MODE_STEP");
}
if (thermMode == MODE_SLEEP)
{
Serial.print("MODE_SLEEP");
}
chipBegun.MLX90632 = true;
}
else
{
if (testingMode == TestingMode::FACTORY_TEST)
{
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::THERMOPILE, EmotiBitFactoryTest::TypeTag::TEST_FAIL);
}
Serial.println("Failed");
setupFailed("THERMOPILE");
}
}
#ifdef ADAFRUIT_FEATHER_M0
// ADC Correction
Serial.println("Checking for ADC Correction...");
analogReadResolution(_adcBits);
if (!adcCorrectionValues.valid)
{
// Instantiate the ADC Correction class to read data from the AT-Winc flash to calculate the correction values
AdcCorrection adcCorrection(AdcCorrection::AdcCorrectionRigVersion::UNKNOWN, adcCorrectionValues._gainCorrection, adcCorrectionValues._offsetCorrection, adcCorrectionValues.valid, adcCorrectionValues._isrOffsetCorr);
if (adcCorrection.atwincAdcDataCorruptionTest != AdcCorrection::Status::FAILURE && adcCorrection.atwincAdcMetaDataCorruptionTest != AdcCorrection::Status::FAILURE)
{
emotibitEda.setAdcIsrOffsetCorr(adcCorrectionValues._isrOffsetCorr);
Serial.print("Gain Correction:"); Serial.print(adcCorrectionValues._gainCorrection); Serial.print("\toffset correction:"); Serial.print(adcCorrectionValues._offsetCorrection);
Serial.print("\tisr offset Corr: "); Serial.println(adcCorrectionValues._isrOffsetCorr, 2);
analogReadCorrection(adcCorrectionValues._offsetCorrection, adcCorrectionValues._gainCorrection);
}
}
// using correction values generated in AdcCorrectionMode
else
{
Serial.println("ADC correction already enabled in correction test mode");
Serial.print("Gain Correction:"); Serial.print(adcCorrectionValues._gainCorrection);
Serial.print("\toffset correction:"); Serial.println(adcCorrectionValues._offsetCorrection);
}
#endif
// Setup EDA
Serial.println("\nInitializing EDA... ");
if (emotibitEda.setup(_hwVersion, _samplingRates.eda / ((float)_samplesAveraged.eda), &eda, &edl, &edr, _EmotiBit_i2c, &edlBuffer, &edrBuffer))
{
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::ADC_INIT, EmotiBitFactoryTest::TypeTag::TEST_PASS);
Serial.println("Completed");
}
else
{
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::ADC_INIT, EmotiBitFactoryTest::TypeTag::TEST_FAIL);
Serial.println(factoryTestSerialOutput);
Serial.println("failed");
}
Serial.println("\nLoading EDA calibration... ");
if (emotibitEda.stageCalibLoad(&_emotibitNvmController, true))
{
Serial.println("Completed");
}
else
{
Serial.println("failed");
}
// Sensor setup complete
Serial.println("Sensor setup complete");
// EDL Filter Parameters
//edaCrossoverFilterFreq = emotiBitVersionController.getMathConstant(MathConstants::EDA_CROSSOVER_FILTER_FREQ);
/*
if (edaCrossoverFilterFreq > 0)// valid assignment of constant
{
_edlDigFiltAlpha = pow(M_E, -2.f * PI * edaCrossoverFilterFreq / (_samplingRates.eda / _samplesAveraged.eda));
}*/
/*
if (_version == EmotiBitVersionController::EmotiBitVersion::V02H)
{
edaCrossoverFilterFreq = 1.f / (2.f * PI * 200000.f * 0.0000047f);
_edlDigFiltAlpha = pow(M_E, -2.f * PI * edaCrossoverFilterFreq / (_samplingRates.eda / _samplesAveraged.eda));
}
*/
led.setState(EmotiBitLedController::Led::RED, true,true);
status = setupSdCard();
if (status)
{
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::SD_CARD, EmotiBitFactoryTest::TypeTag::TEST_PASS);
// Give a brief delay to signify to the user "config file is being loaded"
delay(2000);
led.setState(EmotiBitLedController::Led::RED, false, true);
}
// ToDo: verify if this else is ever reached.
else
{
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::SD_CARD, EmotiBitFactoryTest::TypeTag::TEST_FAIL);
Serial.println(factoryTestSerialOutput);
sleep(true);
}
//WiFi Setup;
Serial.print("\nSetting up WiFi\n");
#if defined(ADAFRUIT_FEATHER_M0)
WiFi.setPins(8, 7, 4, 2);
WiFi.lowPowerMode();
#endif
printEmotiBitInfo();
// turn BLUE on to signify we are trying to connect to WiFi
led.setState(EmotiBitLedController::Led::BLUE, true, true);
uint16_t attemptDelay = 20000; // in mS. ESP32 has been observed to take >10 seconds to resolve an enterprise connection
uint8_t maxAttemptsPerCred = 1;
uint32_t timeout = attemptDelay * maxAttemptsPerCred * _emotiBitWiFi.getNumCredentials() * 2; // Try cycling through all credentials at least 2x before giving up and trying a restart
if (_emotiBitWiFi.isEnterpriseNetworkListed())
{
// enterprise network is listed in network credential list.
// restart MCU after timeout
_emotiBitWiFi.begin(timeout, maxAttemptsPerCred, attemptDelay);
}
else
{
// only personal networks listed in credentials list.
// keep trying to connect to networks without any timeout
_emotiBitWiFi.begin(-1, maxAttemptsPerCred, attemptDelay);
}
if (_emotiBitWiFi.status(false) != WL_CONNECTED)
{
// Could not connect to network. software restart and begin setup again.
restartMcu();
}
led.setState(EmotiBitLedController::Led::BLUE, false, true);
if (testingMode == TestingMode::FACTORY_TEST)
{
// Add Pass or fail
// ToDo: add mechanism to detect fail/pass
EmotiBitFactoryTest::updateOutputString(factoryTestSerialOutput, EmotiBitFactoryTest::TypeTag::WIFI, EmotiBitFactoryTest::TypeTag::TEST_PASS);
}
Serial.println(" WiFi setup Completed");
#ifdef ARDUINO_FEATHER_ESP32
Serial.println("Setting up FTP");
Serial.println("Setting Protocol");
_fileTransferManager.setProtocol(FileTransferManager::Protocol::FTP);
Serial.println("Setting Auth");
_fileTransferManager.setFtpAuth("ftp", "ftp");
#endif
setPowerMode(PowerMode::NORMAL_POWER);