forked from Protonerd/FX-SaberOS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FX-SaberOS.ino
1642 lines (1488 loc) · 61.4 KB
/
FX-SaberOS.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
/*
FX-SaberOS V1.0
released on: 7 October 2017
author: Sebastien CAPOU ([email protected]) and Andras Kun ([email protected])
Source : https://github.com/Protonerd/FX-SaberOS
Description: Operating System for Arduino based LightSaber
This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/.
*/
/***************************************************************************************************/
#include <Arduino.h>
#include <I2Cdev.h>
#include <MPU6050_6Axis_MotionApps20.h>
#include <EEPROMex.h>
#include <OneButton.h>
#include <avr/wdt.h>
#include "Buttons.h"
#include "Config_HW.h"
#include "Config_SW.h"
#include "ConfigMenu.h"
#include "Light.h"
#include "Soundfont.h"
/*
* DFPLAYER variables
*/
#include <DFPlayer.h>
DFPlayer dfplayer;
SoundFont soundFont;
unsigned long sndSuppress = millis();
unsigned long sndSuppress2 = millis();
unsigned long clashSndSuppress = millis();
#ifdef SMOOTH_SWING
unsigned long ssStart;
unsigned long ssEnd = millis();
unsigned long ssVolRevisionMs;
uint8_t ssVolIncrease;
#endif
#ifdef LS_LOOPLENGHT
unsigned long loopcurrenttime;
#endif
#ifdef DEEP_SLEEP
unsigned long sleepTimer = millis();
#endif
bool hum_playing = false; // variable to store whether hum is being played
#ifdef JUKEBOX
bool jukebox_play = false; // indicate whether a song is being played in JukeBox mode
uint8_t jb_track; // sound file track number in the directory designated for music playback
#endif
#ifdef CROSSGUARDSABER
bool mainignition_done=false;
#endif
/***************************************************************************************************
* Saber Finite State Machine Custom Type and State Variable
*/
// global Saber state and Sub State variables
extern SaberStateEnum SaberState;
extern SaberStateEnum PrevSaberState;
extern ActionModeSubStatesEnum ActionModeSubStates;
extern ConfigModeSubStatesEnum ConfigModeSubStates;
extern ActionModeSubStatesEnum PrevActionModeSubStates;
extern ConfigModeSubStatesEnum PrevConfigModeSubStates;
//extern SubStateEnum SubState;
/***************************************************************************************************
* Motion detection Variables
*/
MPU6050 mpu;
#ifdef CLASH_DET_MPU_INT
I2Cdev i2ccomm;
#endif
// MPU control/status vars
volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high
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)
uint8_t fifoBuffer[64]; // FIFO storage buffer
uint16_t mpuFifoCount; // count of all bytes currently in FIFO
// orientation/motion vars
Quaternion curRotation; // [w, x, y, z] quaternion container
Quaternion prevRotation; // [w, x, y, z] quaternion container
static Quaternion prevOrientation; // [w, x, y, z] quaternion container
static Quaternion curOrientation; // [w, x, y, z] quaternion container
VectorInt16 curAccel;
VectorInt16 prevAccel;
VectorInt16 curDeltAccel;
VectorInt16 prevDeltAccel;
/***************************************************************************************************
* LED String variables
*/
cRGB currentColor;
#if defined LEDSTRINGS
#ifdef DIYINO_PRIME
uint8_t ledPins[] = {LS1, LS2, LS3, LS4, LS5, LS6};
#else if defined DIYINO_STARDUST_V2 or defined DIYINO_STARDUST_V3
uint8_t ledPins[] = {LS1, LS2, LS3};
#endif
uint8_t blasterPin;
#endif
#if defined STAR_LED
uint8_t ledPins[] = {LED_RED, LED_GREEN, LED_BLUE};
#endif
extern bool fireblade;
#if defined PIXELBLADE or defined ADF_PIXIE_BLADE
#ifdef DIYINO_PRIME
uint8_t ledPins[] = {LS1, LS2, LS3, LS4, LS5, LS6};
#else if defined DIYINO_STARDUST_V2 or defined DIYINO_STARDUST_V3
uint8_t ledPins[] = {LS1, LS2, LS3};
#endif
WS2812 pixels(NUMPIXELS);
cRGB color;
uint8_t blasterPixel;
#endif
#ifdef PIXEL_ACCENT
WS2812 accentPixels(NUM_ACCENT_PIXELS);
#endif
uint8_t clash = 0;
bool lockuponclash = false;
bool tipmeltonclash = false;
long tipmeltStart;
uint8_t randomBlink = 0;
/***************************************************************************************************
* Buttons variables
*/
OneButton mainButton(MAIN_BUTTON, true);
#ifndef SINGLEBUTTON
OneButton lockupButton(AUX_BUTTON, true);
#endif
/***************************************************************************************************
* ConfigMode Variables
*/
int8_t modification = 0;
int8_t prev_modification = 0;
int16_t value = 0;
uint8_t menu = 0;
bool enterMenu = false;
bool changeMenu = false;
bool play = false;
unsigned int configAdress = 0;
volatile uint8_t portbhistory = 0xFF; // default is high because the pull-up
struct StoreStruct {
// This is for mere detection if they are our settings
char version[5];
// The settings
uint8_t volume;// 0 to 31
uint8_t soundFont;// as many as Sound font you have defined in Soundfont.h Max:253
struct Profile {
cRGB mainColor;
cRGB clashColor;
cRGB blasterboltColor;
uint16_t swingSensitivity;
uint8_t flickerType;
uint8_t poweronoffType;
}sndProfile[SOUNDFONT_QUANTITY];
}storage;
/***************************************************************************************************
* Function Prototypes
* The following prototypes are not correctly generated by Arduino IDE 1.6.5-r5 or previous
*/
inline void printQuaternion(Quaternion quaternion, long multiplier);
inline void printAcceleration(VectorInt16 aaWorld);
// ====================================================================================
// === SETUP ROUTINE ===
// ====================================================================================
void setup() {
#ifdef PIXEL_ACCENT
accentPixels.setOutput(PIXEL_ACCENT_DATA);
#ifdef ACCENT_SWAP_RG
accentPixels.setColorOrderRGB();
#endif
#endif
// join I2C bus (I2Cdev library doesn't do this automatically)
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
Wire.begin();
TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz). Comment this line if having compilation difficulties with TWBR.
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
Fastwire::setup(400, true);
#endif
// Serial line for debug
Serial.begin(115200);
#ifdef INCLUDE_COMPILE_INFO
const char compile_date[] = __DATE__ " " __TIME__;
const char version_file[] = __FILE__;
Serial.print(F("version file: "));Serial.println(version_file);
Serial.print(F("compiled on: "));Serial.println(compile_date);Serial.println("");
#endif
/***** LOAD CONFIG *****/
// Get config from EEPROM if there is one
// or initialise value with default ones set in StoreStruct
EEPROM.setMemPool(MEMORYBASE, EEPROMSizeATmega328); //Set memorypool base to 32, assume Arduino Uno board
configAdress = EEPROM.getAddress(sizeof(StoreStruct)); // Size of config object
Serial.print("size of StoreStruct: ");Serial.println(sizeof(StoreStruct));
Serial.println(configAdress);
if (!loadConfig()) {
for (uint8_t i = 0; i <= 2; i++) {
storage.version[i] = CONFIG_VERSION[i];
}
storage.soundFont = 0;
storage.volume = 15;
for (uint8_t i=0; i<SOUNDFONT_QUANTITY;i++){
storage.sndProfile[i].swingSensitivity=1000;
storage.sndProfile[i].flickerType=0;
storage.sndProfile[i].poweronoffType=0;
}
for (uint8_t i=0; i<SOUNDFONT_QUANTITY;i++){
storage.sndProfile[i].mainColor.r=MAX_BRIGHTNESS;
storage.sndProfile[i].mainColor.g=0;
storage.sndProfile[i].mainColor.b=0;
storage.sndProfile[i].clashColor.r=0;
storage.sndProfile[i].clashColor.g=MAX_BRIGHTNESS;
storage.sndProfile[i].clashColor.b=0;
storage.sndProfile[i].blasterboltColor.r=0;
storage.sndProfile[i].blasterboltColor.g=0;
storage.sndProfile[i].blasterboltColor.b=MAX_BRIGHTNESS;
}
saveConfig();
#if defined LS_INFO
Serial.println(F("DEFAULT VALUE"));
#endif
}
#if defined LS_INFO
else {
Serial.println(F("EEPROM LOADED"));
}
#endif
// retreive the sound font ID stored in the EEPROM (last configured)
soundFont.setID(storage.soundFont);
// in case a fireblade flicker type is selected for the active sound font, set the bool variable
// in case a fireblade flicker type is selected for the active sound font, set the bool variable
if (CS_FLICKERTYPE < CS_LASTMEMBER and (storage.sndProfile[storage.soundFont].flickerType==2 or storage.sndProfile[storage.soundFont].flickerType==3 or storage.sndProfile[storage.soundFont].flickerType==4)) {
fireblade=true;
}
else {
fireblade=false;
}
/* CONFIG ITEMS PRESETS */
/* Set default values to parameters which can be modified in config menu, if the corresponding config menu item is disabled */
// if the config menu does not contain a menu item to define swing sensitivity, default it to 1000 (works very well, mid sensitivity)
if (CS_SWINGSENSITIVITY > CS_LASTMEMBER) {
for (uint8_t i=0; i<SOUNDFONT_QUANTITY;i++){
storage.sndProfile[i].swingSensitivity=SWING_THRESHOLD;
}
}
if (CS_VOLUME > CS_LASTMEMBER) {
storage.volume=31;
}
// enable watchdog to avoid system hang
wdt_reset();
wdt_enable(WDTO_8S);
//WDTCSR = (1<<WDCE) | (1<<WDE) | (1<<WDP3) | (1<<WDP0);
wdt_reset();
/***** LOAD CONFIG *****/
/***** MP6050 MOTION DETECTOR INITIALISATION *****/
// initialize device
#if defined LS_INFO
Serial.println(F("Initializing I2C devices..."));
#endif
mpu.initialize();
// verify connection
#if defined LS_INFO
Serial.println(F("Testing device connections..."));
Serial.println(
mpu.testConnection() ?
F("MPU6050 connection successful") :
F("MPU6050 connection failed"));
// load and configure the DMP
Serial.println(F("Initializing DMP..."));
#endif
devStatus = mpu.dmpInitialize();
/*
Those offsets are specific to each MPU6050 device.
they are found via calibration process.
See this script http://www.i2cdevlib.com/forums/index.php?app=core&module=attach§ion=attach&attach_id=27
*/
#ifdef MPUCALOFFSETEEPROM
// retreive MPU6050 calibrated offset values from EEPROM
EEPROM.setMemPool(MEMORYBASEMPUCALIBOFFSET, EEPROMSizeATmega328);
int addressInt = MEMORYBASEMPUCALIBOFFSET;
mpu.setXAccelOffset(EEPROM.readInt(addressInt));
#ifdef LS_INFO
int16_t output;
output = EEPROM.readInt(addressInt);
Serial.print("address: "); Serial.println(addressInt); Serial.print("output: "); Serial.println(output); Serial.println("");
#endif
addressInt = addressInt + 2; //EEPROM.getAddress(sizeof(int));
mpu.setYAccelOffset(EEPROM.readInt(addressInt));
#ifdef LS_INFO
output = EEPROM.readInt(addressInt);
Serial.print("address: "); Serial.println(addressInt); Serial.print("output: "); Serial.println(output); Serial.println("");
#endif
addressInt = addressInt + 2; //EEPROM.getAddress(sizeof(int));
mpu.setZAccelOffset(EEPROM.readInt(addressInt));
#ifdef LS_INFO
output = EEPROM.readInt(addressInt);
Serial.print("address: "); Serial.println(addressInt); Serial.print("output: "); Serial.println(output); Serial.println("");
#endif
addressInt = addressInt + 2; //EEPROM.getAddress(sizeof(int));
mpu.setXGyroOffset(EEPROM.readInt(addressInt));
#ifdef LS_INFO
output = EEPROM.readInt(addressInt);
Serial.print("address: "); Serial.println(addressInt); Serial.print("output: "); Serial.println(output); Serial.println("");
#endif
addressInt = addressInt + 2; //EEPROM.getAddress(sizeof(int));
mpu.setYGyroOffset(EEPROM.readInt(addressInt));
#ifdef LS_INFO
output = EEPROM.readInt(addressInt);
Serial.print("address: "); Serial.println(addressInt); Serial.print("output: "); Serial.println(output); Serial.println("");
#endif
addressInt = addressInt + 2; //EEPROM.getAddress(sizeof(int));
mpu.setZGyroOffset(EEPROM.readInt(addressInt));
#ifdef LS_INFO
output = EEPROM.readInt(addressInt);
Serial.print("address: "); Serial.println(addressInt); Serial.print("output: "); Serial.println(output); Serial.println("");
#endif
#else // assign calibrated offset values here:
/* UNIT1 */
mpu.setXAccelOffset(46);
mpu.setYAccelOffset(-4942);
mpu.setZAccelOffset(4721);
mpu.setXGyroOffset(23);
mpu.setYGyroOffset(-11);
mpu.setZGyroOffset(44);
#endif
// make sure it worked (returns 0 if so)
if (devStatus == 0) {
// turn on the DMP, now that it's ready
#if defined LS_INFO
Serial.println(F("Enabling DMP..."));
#endif
mpu.setDMPEnabled(true);
// enable Arduino interrupt detection
#if defined LS_INFO
Serial.println(
F(
"Enabling interrupt detection (Arduino external interrupt 0)..."));
#endif
// attachInterrupt(0, dmpDataReady, RISING);
mpuIntStatus = mpu.getIntStatus();
// set our DMP Ready flag so the main loop() function knows it's okay to use it
#if defined LS_INFO
Serial.println(F("DMP ready! Waiting for first interrupt..."));
#endif
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)
#if defined LS_INFO
Serial.print(F("DMP Initialization failed (code "));
Serial.print(devStatus);
Serial.println(F(")"));
#endif
}
// configure the motion interrupt for clash recognition
// INT_PIN_CFG register
// in the working code of MPU6050_DMP all bits of the INT_PIN_CFG are false (0)
mpu.setDLPFMode(3);
mpu.setDHPFMode(0);
//mpu.setFullScaleAccelRange(3);
mpu.setIntMotionEnabled(true); // INT_ENABLE register enable interrupt source motion detection
mpu.setIntZeroMotionEnabled(false);
mpu.setIntFIFOBufferOverflowEnabled(false);
mpu.setIntI2CMasterEnabled(false);
mpu.setIntDataReadyEnabled(false);
// mpu.setMotionDetectionThreshold(10); // 1mg/LSB
mpu.setMotionDetectionThreshold(CLASH_THRESHOLD); // 1mg/LSB
mpu.setMotionDetectionDuration(2); // number of consecutive samples above threshold to trigger int
Serial.println("checkpoint 0");
#ifdef CLASH_DET_MPU_INT
// configure Interrupt with:
// int level active low
// int driver open drain
// interrupt latched until read out (not 50us pulse)
i2ccomm.writeByte(MPU6050_DEFAULT_ADDRESS, 0x37, 0xF0);
// enable only Motion Interrut
i2ccomm.writeByte(MPU6050_DEFAULT_ADDRESS, 0x38, 0x40);
#endif
mpuIntStatus = mpu.getIntStatus();
#ifdef CLASH_DET_MPU_INT
// define D2 (interrupt0) as input
pinMode(2, INPUT_PULLUP);
// enable Arduino interrupt detection
Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
// define Interrupt Service for aux. switch
attachInterrupt(0, ISR_MPUInterrupt, FALLING); // int.0 is the pin2 on the Atmega328P
#endif
/***** MP6050 MOTION DETECTOR INITIALISATION *****/
/***** LED SEGMENT INITIALISATION *****/
// initialize ledstrings segments
DDRD |= B01101000;
DDRB |= B00101110;
//We shut off all pins that could wearing leds,just to be sure
PORTD &= B10010111;
PORTB &= B11010001;
#if defined STAR_LED
//initialise start color
getColor(storage.sndProfile[storage.soundFont].mainColor);
#endif
#if defined PIXELBLADE
pixels.setOutput(DATA_PIN); // This initializes the NeoPixel library.
/*pixelblade_KillKey_Disable();
currentColor.r = 0;
currentColor.g = 0;
currentColor.b = 0;
lightOn(ledPins, -1, currentColor);
delay(300);
lightOff();*/
getColor(storage.sndProfile[storage.soundFont].mainColor);
pixelblade_KillKey_Enable();
#endif
#if defined FoCSTRING
pinMode(FoCSTRING, OUTPUT);
FoCOff(FoCSTRING);
#endif
#ifdef HARD_ACCENT
pinMode(ACCENT_LED, OUTPUT);
#endif
//Randomize randomness (no really that's what it does)
randomSeed(analogRead(2));
/***** LED SEGMENT INITIALISATION *****/
/***** BUTTONS INITIALISATION *****/
// link the Main button functions.
pinMode(MAIN_BUTTON, INPUT_PULLUP);
mainButton.setClickMs(CLICK);
mainButton.setPressMs(PRESS_CONFIG);
mainButton.attachClick(mainClick);
mainButton.attachDoubleClick(mainDoubleClick);
mainButton.attachMultiClick(mainMultiClick);
mainButton.attachLongPressStart(mainLongPressStart);
mainButton.attachLongPressStop(mainLongPressStop);
mainButton.attachDuringLongPress(mainLongPress);
#ifndef SINGLEBUTTON
// link the Lockup button functions.
pinMode(AUX_BUTTON, INPUT_PULLUP);
lockupButton.setClickMs(CLICK);
lockupButton.setPressMs(PRESS_CONFIG);
lockupButton.attachClick(lockupClick);
lockupButton.attachDoubleClick(lockupDoubleClick);
lockupButton.attachLongPressStart(lockupLongPressStart);
lockupButton.attachLongPressStop(lockupLongPressStop);
lockupButton.attachDuringLongPress(lockupLongPress);
#endif
#ifdef DEEP_SLEEP
/************ DEEP_SLEEP MODE SETTINGS **********/
pinMode(MP3_PSWITCH, OUTPUT);
pinMode(FTDI_PSWITCH, OUTPUT);
digitalWrite(MP3_PSWITCH, LOW); // enable MP3 player
digitalWrite(FTDI_PSWITCH, LOW); // enable FTDI player
// pin change interrupt masks (see below list)
PCMSK2 |= bit (PCINT20); // pin 4 Aux button
PCMSK0 |= bit (PCINT4); // pin 12 Main button
delay(300);
#endif // DEEP_SLEEP
/***** DF PLAYER INITIALISATION *****/
InitDFPlayer();
delay(200);
#ifdef DFPLAYER_CLONE
delay(800); // clone chip requires more time to initialize
#endif
// according to debug on 3.11.2017, these 2 lines below cause the sporadic disable of sound. For audio tracker they are not strictly needed.
//pinMode(SPK1, INPUT);
//pinMode(SPK2, INPUT);
SinglePlay_Sound(soundFont.getBoot((storage.soundFont)*NR_FILE_SF));//11);
#ifdef ADF_PIXIE_BLADE
InitAdafruitPixie(ledPins);
#endif
//SinglePlay_Sound(11);
//delay(850);
/***** Quick Mute *****/
if (digitalRead(MAIN_BUTTON) == LOW) {
Set_Volume(0);
//Serial.println("Muted");
}
else {
Set_Volume(storage.volume);
//Serial.println("Unmuted");
}
/****** INIT SABER STATE VARIABLE *****/
SaberState = S_STANDBY;
PrevSaberState = S_SLEEP;
ActionModeSubStates = AS_HUM;
#ifdef DEEP_SLEEP
sleepTimer = millis();
#endif
} // end setup
// ====================================================================================
// === LOOP ROUTINE ===
// ====================================================================================
void loop() {
// pat the dog
wdt_reset(); // do not remove!!!
// if MPU6050 DMP programming failed, don't try to do anything : EPIC FAIL !
if (!dmpReady) {
return;
}
mainButton.tick();
#ifndef SINGLEBUTTON
lockupButton.tick();
#endif
#ifdef LS_LOOPLENGHT
Serial.println(millis()-loopcurrenttime);
loopcurrenttime=millis();
#endif
/*//////////////////////////////////////////////////////////////////////////////////////////////////////////
ACTION MODE HANDLER
*/ /////////////////////////////////////////////////////////////////////////////////////////////////////////
if (SaberState == S_SABERON) {
/*
// In case we want to time the loop
Serial.print(F("Action Mode"));
Serial.print(F(" time="));
Serial.println(millis());
*/
if (ActionModeSubStates != AS_HUM) { // needed for hum relauch only in case it's not already being played
hum_playing = false;
}
else { // AS_HUM
if ((millis() - sndSuppress > HUM_RELAUNCH and not hum_playing)) {
HumRelaunch();
}
}
if (ActionModeSubStates == AS_IGNITION) {
/*
This is the very first loop after Action Mode has been turned on
*/
#ifndef SINGLEBUTTON
lockupButton.setPressTicks(PRESS_ACTION);
#endif
#if defined PIXELBLADE or defined ADF_PIXIE_BLADE
pixelblade_KillKey_Disable();
#endif
#if defined LS_INFO
Serial.println(F("START ACTION"));
#endif
//Play powerons wavs
SinglePlay_Sound(soundFont.getPowerOn((storage.soundFont)*NR_FILE_SF));
// Light up the blade
pixelblade_KillKey_Disable();
#ifdef CROSSGUARDSABER
lightIgnition(ledPins, soundFont.getPowerOnTime(), storage.sndProfile[storage.soundFont].poweronoffType, storage.sndProfile[storage.soundFont].mainColor, MAINBLADE_OFFSET, MAINBLADE_OFFSET+MAINBLADE_LENGTH);
mainignition_done=true;
#else // single blade or saber staff
lightIgnition(ledPins, soundFont.getPowerOnTime(), storage.sndProfile[storage.soundFont].poweronoffType, storage.sndProfile[storage.soundFont].mainColor);
#endif
sndSuppress = millis()+soundFont.getPowerOnTime()+1000;
sndSuppress2 = millis()+soundFont.getPowerOnTime()+1000;
#ifdef CROSSGUARDSABER
// ignite the crossguard after the defined wat time or latest when a new hum shall be relaunched
while (millis() > sndSuppress2 and millis()-sndSuppress2<STAGGERED_IGNITION_DELAY and millis()-sndSuppress2<HUM_RELAUNCH) {
lightFlicker(ledPins, storage.sndProfile[storage.soundFont].flickerType, 0, storage.sndProfile[storage.soundFont].mainColor, storage.sndProfile[storage.soundFont].clashColor, ActionModeSubStates, MAINBLADE_OFFSET, MAINBLADE_OFFSET+MAINBLADE_LENGTH);
}
SinglePlay_Sound(soundFont.getClash((storage.soundFont)*NR_FILE_SF));
lightIgnition(ledPins, CLASH_SUPRESS, storage.sndProfile[storage.soundFont].poweronoffType, storage.sndProfile[storage.soundFont].mainColor, CROSSGUARD_OFFSET, CROSSGUARD_LENGTH);
sndSuppress2=millis();
mainignition_done=false; // reset flag for next power up
#endif
// Get the initial position of the motion detector
//motionEngine();
//ActionModeSubStates = AS_HUM;
#if defined ACCENT_LED
// turns accent LED On
accentLEDControl(AL_ON);
#endif
}
// ************************* blade movement detection ************************************
//Let's get our values !
motionEngine();
/*
CLASH DETECTION :
A clash is a violent deceleration when 2 blades hit each other
For a realistic clash detection it's imperative to detect
such a deceleration instantenously, which is only feasible
using the motion interrupt feature of the MPU6050.
*/
#ifdef CLASH_DET_MPU_POLL
if (mpuIntStatus > 60 and mpuIntStatus < 70 and ActionModeSubStates != AS_BLADELOCKUP and ActionModeSubStates != AS_TIPMELT) {
FX_Clash();
}
#endif // CLASH_DET_MPU_POLL
/*
SIMPLE BLADE MOVEMENT DETECTION FOR MOTION TRIGGERED BLASTER FEDLECT
We detect swings as hilt's orientation change
since IMUs sucks at determining relative position in space
*/
// movement of the hilt while blaster move deflect is activated can trigger a blaster deflect
#ifdef CLASH_DET_MPU_POLL
else if ((ActionModeSubStates == AS_BLASTERDEFLECTPRESS or (ActionModeSubStates == AS_BLASTERDEFLECTMOTION and (abs(curDeltAccel.y) > storage.sndProfile[storage.soundFont].swingSensitivity // and it has suffisent power on a certain axis
#endif
#ifdef CLASH_DET_MPU_INT
if ((ActionModeSubStates == AS_BLASTERDEFLECTPRESS or (ActionModeSubStates == AS_BLASTERDEFLECTMOTION and (abs(curDeltAccel.y) > storage.sndProfile[storage.soundFont].swingSensitivity // and it has suffisent power on a certain axis
#endif
or abs(curDeltAccel.z) > storage.sndProfile[storage.soundFont].swingSensitivity
or abs(curDeltAccel.x) > storage.sndProfile[storage.soundFont].swingSensitivity))) and (millis() - sndSuppress >= BLASTERBLOCK_SUPRESS)) {
FX_BlasterBlock();
}
// CLASH state, flicker with clash color/brightness for the duration of CLASH_FX_DURATION
else if (ActionModeSubStates==AS_CLASH){
// check if duration expired
if (millis() > sndSuppress and millis()-sndSuppress < CLASH_FX_DURATION) {
lightFlicker(ledPins, storage.sndProfile[storage.soundFont].flickerType, 0, storage.sndProfile[storage.soundFont].mainColor, storage.sndProfile[storage.soundFont].clashColor, ActionModeSubStates);
}
else {
ActionModeSubStates=AS_HUM;
sndSuppress=millis();
}
}
/*
SWING DETECTION
We detect swings as hilt's orientation change
since IMUs sucks at determining relative position in space
*/
else if (
(not fireblade) and ((ActionModeSubStates != AS_BLADELOCKUP and ActionModeSubStates != AS_TIPMELT)
#ifdef SWING_QUATERNION
or lockuponclash // end lockuponclash and tipmeltonclash events on a swing, but only if swings are calculated based on quaternions, otherwise swings will
or tipmeltonclash // interrut the lockup/tipmelt uncontrollably
#endif
)
#ifndef SWING_QUATERNION
and (abs(curDeltAccel.y) > storage.sndProfile[storage.soundFont].swingSensitivity // and it has suffisent power on a certain axis
or abs(curDeltAccel.z) > storage.sndProfile[storage.soundFont].swingSensitivity
or abs(curDeltAccel.x) > storage.sndProfile[storage.soundFont].swingSensitivity)
and (millis() > sndSuppress and millis() - sndSuppress > SWING_SUPPRESS)
#else // SWING_QUATERNION is defined
and abs(curRotation.w * 1000) < 999 // some rotation movement have been initiated
and (
(
(millis() > sndSuppress and millis() - sndSuppress > SWING_SUPPRESS) // The movement doesn't follow another to closely
and (abs(curDeltAccel.x) > storage.sndProfile[storage.soundFont].swingSensitivity // and it has suffisent power on a certain axis
or abs(curDeltAccel.z) > storage.sndProfile[storage.soundFont].swingSensitivity
or abs(curDeltAccel.y) > storage.sndProfile[storage.soundFont].swingSensitivity * 10)
)
or (// A reverse movement follow a first one
(millis() > sndSuppress2 and millis() - sndSuppress2 > SWING_SUPPRESS) // The reverse movement doesn't follow another reverse movement to closely
// and it must be a reverse movement on Vertical axis
and (
abs(curDeltAccel.x) > abs(curDeltAccel.z)
and abs(prevDeltAccel.x) > storage.sndProfile[storage.soundFont].swingSensitivity
and (
(prevDeltAccel.x > 0
and curDeltAccel.x < -storage.sndProfile[storage.soundFont].swingSensitivity)
or (
prevDeltAccel.x < 0
and curDeltAccel.x > storage.sndProfile[storage.soundFont].swingSensitivity
)
)
)
)
or (// A reverse movement follow a first one
(millis() > sndSuppress2 and millis() - sndSuppress2 > SWING_SUPPRESS) // The reverse movement doesn't follow another reverse movement to closely
and ( // and it must be a reverse movement on Horizontal axis
abs(curDeltAccel.z) > abs(curDeltAccel.x)
and abs(prevDeltAccel.z) > storage.sndProfile[storage.soundFont].swingSensitivity
and (
(prevDeltAccel.z > 0
and curDeltAccel.z < -storage.sndProfile[storage.soundFont].swingSensitivity)
or (
prevDeltAccel.z < 0
and curDeltAccel.z > storage.sndProfile[storage.soundFont].swingSensitivity
)
)
)
)
)
// the movement must not be triggered by pure blade rotation (wrist rotation)
and not (
abs(prevRotation.y * 1000 - curRotation.y * 1000) > abs(prevRotation.x * 1000 - curRotation.x * 1000)
and
abs(prevRotation.y * 1000 - curRotation.y * 1000) > abs(prevRotation.z * 1000 - curRotation.z * 1000)
)
#endif // SWING_QUATERNION
)
{ // end of the condition definition for swings
if ( ActionModeSubStates != AS_BLASTERDEFLECTMOTION and ActionModeSubStates != AS_BLASTERDEFLECTPRESS) {
/*
THIS IS A SWING !
*/
prevDeltAccel = curDeltAccel;
#if defined LS_SWING_DEBUG
Serial.print(F("SWING\ttime="));
Serial.println(millis() - sndSuppress);
Serial.print(F("\t\tcurRotation\tw="));
Serial.print(curRotation.w * 1000);
Serial.print(F("\t\tx="));
Serial.print(curRotation.x);
Serial.print(F("\t\ty="));
Serial.print(curRotation.y);
Serial.print(F("\t\tz="));
Serial.print(curRotation.z);
Serial.print(F("\t\tAcceleration\tx="));
Serial.print(curDeltAccel.x);
Serial.print(F("\ty="));
Serial.print(curDeltAccel.y);
Serial.print(F("\tz="));
Serial.println(curDeltAccel.z);
#endif
#ifdef CLASH_DET_MPU_POLL
motionEngine();
if (mpuIntStatus > 60 and mpuIntStatus < 70 and ActionModeSubStates != AS_BLADELOCKUP and ActionModeSubStates != AS_TIPMELT) {
SinglePlay_Sound(soundFont.getClash((storage.soundFont)*NR_FILE_SF));
sndSuppress = millis();
sndSuppress2 = millis();
/*
THIS IS A CLASH !
*/
ActionModeSubStates = AS_CLASH;
lightClashEffect(ledPins, storage.sndProfile[storage.soundFont].clashColor);
if (!fireblade) {
delay(CLASH_FX_DURATION); // clash duration
}
}
else {
#endif // CLASH_DET_MPU_POLL
ActionModeSubStates = AS_SWING;
SinglePlay_Sound(soundFont.getSwing((storage.soundFont)*NR_FILE_SF));
/* NORMAL SWING */
#ifdef SWING_COLORCHANGE
lightSwingEffect(ledPins);
if (!fireblade) {
delay(SWING_FX_DURATION); // swing duration
}
#endif // SWING_COLORCHANGE
if (millis() > sndSuppress and millis() - sndSuppress > SWING_SUPPRESS) {
sndSuppress = millis();
}
if (millis() > sndSuppress2 and millis() - sndSuppress2 > SWING_SUPPRESS) {
sndSuppress2 = millis();
}
#ifdef CLASH_DET_MPU_POLL
}
#endif // CLASH_DET_MPU_POLL
}
}
else { // simply flicker
if (ActionModeSubStates != AS_BLASTERDEFLECTMOTION and ActionModeSubStates != AS_BLADELOCKUP and ActionModeSubStates != AS_TIPMELT) { // do not deactivate blaster move deflect mode in case the saber is idling
ActionModeSubStates = AS_HUM;
}
else if (ActionModeSubStates == AS_BLASTERDEFLECTMOTION) {
accentLEDControl(AL_PULSE);
}
// relaunch hum if more than HUM_RELAUNCH time elapsed since entering AS_HUM state
if (millis() > sndSuppress and millis() - sndSuppress > HUM_RELAUNCH and (not hum_playing) and ActionModeSubStates != AS_BLADELOCKUP and ActionModeSubStates != AS_TIPMELT) {
HumRelaunch();
}
#ifdef SMOOTH_SWING
uint8_t minVolRevisionInterval = 150; // revise volume every 150ms
#ifdef DFPLAYER_CLONE
minVolRevisionInterval = max(minVolRevisionInterval, DFPLAYER_OPERATING_DELAY); // don't change volume more frequently than DFPlayer can handle
#endif
uint8_t maxCurRotation = max(abs(curRotation.x*1000),max(abs(curRotation.y*1000),abs(curRotation.z*1000)));
bool modulate = maxCurRotation > 1 // some rotation initiated
and millis() - sndSuppress > SWING_SUPPRESS + SMOOTH_SWING_SUPRESS // and not following a swing or reverse swing too closely
and millis() - sndSuppress2 > SWING_SUPPRESS + SMOOTH_SWING_SUPRESS;
if (ssEnd >= ssStart and modulate and millis() - ssEnd > SMOOTH_SWING_SUPRESS) { // SMOOTH SWING START
ssStart=millis();
Set_Equalizer(4); // change pitch
ssVolIncrease=0;
ssVolRevisionMs=millis();
} else if (ssEnd < ssStart and !modulate and millis() - ssStart > SMOOTH_SWING_FX_DURATION and millis() - ssVolRevisionMs > minVolRevisionInterval) { // SMOOTH SWING END (PHASE 1)
Set_Equalizer(0); // reset equalizer
ssVolRevisionMs=millis();
ssEnd=millis();
} else if (ssEnd < ssStart and millis() - ssVolRevisionMs > minVolRevisionInterval) { // SMOOTH SWING ONGOING
ssVolIncrease = constrain(maxCurRotation,max(0,ssVolIncrease-1),min(5,ssVolIncrease+1)); // revise volume (up to 5 levels)
Set_Volume(constrain(storage.volume+ssVolIncrease,storage.volume,30));
ssVolRevisionMs=millis();
} else if (ssEnd >= ssStart and ssVolIncrease>0 and millis() - ssVolRevisionMs > minVolRevisionInterval) { // SMOOTH SWING END (PHASE 2)
Set_Volume(storage.volume); // reset volume
ssVolIncrease=0;
ssEnd=millis();
}
#endif
getColor(storage.sndProfile[storage.soundFont].mainColor);
lightFlicker(ledPins, storage.sndProfile[storage.soundFont].flickerType, 0, storage.sndProfile[storage.soundFont].mainColor, storage.sndProfile[storage.soundFont].clashColor, ActionModeSubStates);
if (lockuponclash or tipmeltonclash) {
accentLEDControl(AL_PULSE);
}
}
// ************************* blade movement detection ends***********************************
} ////END ACTION MODE HANDLER///////////////////////////////////////////////////////////////////////////////////////
/*//////////////////////////////////////////////////////////////////////////////////////////////////////////
CONFIG MODE HANDLER
*//////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (SaberState == S_CONFIG) {
// read out the motion sensor in order to be able to detect clashes in Config Mode for the "Hit-and-Run"
motionEngine();
if ((mpuIntStatus > 60 and mpuIntStatus < 70) and (millis() - sndSuppress >= CLASH_SUPRESS)) {
sndSuppress = millis();
// define what shall happen in each Config Sub-State if the Escape Path is activated
#if defined LS_INFO
Serial.println("Hit-and-Run is activated");
#endif
#ifdef SINGLEBUTTON
// In case a clash is detected, move to the next menu item in single button mode
NextConfigState();
#else
// in two button mode, activate different Hit-and-Run functions depending on the config state
// for all other states:
switch(ConfigModeSubStates) {
default:
NextConfigState();
case CS_VOLUME:
// turn on the volume full
storage.volume = 30; //MAX
BladeMeter(ledPins, storage.volume*100/30);
Set_Volume(storage.volume); // Too Slow: we'll change volume on exit
delay(50);
#if defined LS_INFO
Serial.println(storage.volume);
#endif
break;
case CS_SOUNDFONT:
break;
case CS_FLICKERTYPE:
break;
case CS_POWERONOFFTYPE:
break;
case CS_SWINGSENSITIVITY:
// upon clash increase swing sensitivity by 1/10th of a g (1g=16384)
if (storage.sndProfile[storage.soundFont].swingSensitivity <= 14400 ) {
storage.sndProfile[storage.soundFont].swingSensitivity=storage.sndProfile[storage.soundFont].swingSensitivity+1600;
}
else {
storage.sndProfile[storage.soundFont].swingSensitivity=0;
}
BladeMeter(ledPins, (storage.sndProfile[storage.soundFont].swingSensitivity)/100);
break;
case CS_SLEEPINIT:
break;
}
#endif // SINGLEBUTTON
}
if (PrevSaberState == S_STANDBY) { // entering config mode
PrevSaberState = S_CONFIG;
if (storage.volume <= 15) {
Set_Volume(15);
delay(200);
}
SinglePlay_Sound(3);
delay(600);
#if defined PIXELBLADE or defined ADF_PIXIE_BLADE
pixelblade_KillKey_Disable();
#endif
#if defined LS_INFO
Serial.println(F("START CONF"));
#endif
enterMenu = true;
ConfigModeSubStates=-1;
NextConfigState();
}
#if defined PIXELBLADE or defined STAR_LED or defined ADF_PIXIE_BLADE
if (ConfigModeSubStates == CS_MAINCOLOR or ConfigModeSubStates == CS_CLASHCOLOR or ConfigModeSubStates == CS_BLASTCOLOR) {
#ifdef GRAVITY_COLOR
modification = GravityVector();
switch (modification) {
case (0): // red +
currentColor.r = 100; currentColor.g = 0; currentColor.b = 0;
break;
case (1): // red -
currentColor.r = 20; currentColor.g = 0; currentColor.b = 0;
break;
case (2): // green +
currentColor.r = 0; currentColor.g = 100; currentColor.b = 0;
break;
case (3): // green -
currentColor.r = 0; currentColor.g = 20; currentColor.b = 0;
break;
case (4): // blue +
currentColor.r = 0; currentColor.g = 0; currentColor.b = 100;
break;
case (5): // blue -
currentColor.r = 0; currentColor.g = 0; currentColor.b = 20;
break;
}
// in case of a neopixel blade, show the gravity color on the last 5 pixel of the blade tip
#ifdef PIXELBLADE
lightOn(ledPins, -1, currentColor, NUMPIXELS - 5, NUMPIXELS);
#else if STAR_LED
#endif
#ifdef ADF_PIXIE_BLADE
if (ConfigModeSubStates == CS_MAINCOLOR) {
lightOn(ledPins, -1, storage.sndProfile[storage.soundFont].mainColor);
}
else if (ConfigModeSubStates == CS_CLASHCOLOR) {
lightOn(ledPins, -1, storage.sndProfile[storage.soundFont].clashColor);
}
else if (ConfigModeSubStates == CS_BLASTCOLOR) {
lightOn(ledPins, -1, storage.sndProfile[storage.soundFont].blasterboltColor);
}
#endif
#endif // GRAVITY_COLOR
}
#endif // color configuration for PIXELBLADE or STAR_LED or ADF_PIXIE_BLADE
if (ConfigModeSubStates == CS_FLICKERTYPE or ConfigModeSubStates==CS_SOUNDFONT) {
lightFlicker(ledPins, storage.sndProfile[storage.soundFont].flickerType, 0, storage.sndProfile[storage.soundFont].mainColor, storage.sndProfile[storage.soundFont].clashColor, ActionModeSubStates);
}
else if (ConfigModeSubStates == CS_SWINGSENSITIVITY and (abs(curDeltAccel.y) > storage.sndProfile[storage.soundFont].swingSensitivity // and it has suffisent power on a certain axis
or abs(curDeltAccel.z) > storage.sndProfile[storage.soundFont].swingSensitivity
or abs(curDeltAccel.x) > storage.sndProfile[storage.soundFont].swingSensitivity)) {
SinglePlay_Sound(soundFont.getSwing((storage.soundFont)*NR_FILE_SF));
}
#ifdef BATTERY_CHECK
else if (ConfigModeSubStates == CS_BATTERYLEVEL) {
MonitorBattery();
}
#endif
} //END CONFIG MODE HANDLER
/*//////////////////////////////////////////////////////////////////////////////////////////////////////////
STANDBY MODE
*//////////////////////////////////////////////////////////////////////////////////////////////////////////
else if (SaberState == S_STANDBY) {
if (PrevSaberState==S_SABERON and ActionModeSubStates == AS_RETRACTION) { // we just leaved Action Mode
//detachInterrupt(0);
ActionModeSubStates = AS_HUM;
PrevSaberState = S_STANDBY;
#if defined DEEP_SLEEP
sleepTimer=millis(); // reset sleep time counter
#endif
SinglePlay_Sound(soundFont.getPowerOff((storage.soundFont)*NR_FILE_SF));
changeMenu = false;