-
Notifications
You must be signed in to change notification settings - Fork 2
/
Functions.ino
3482 lines (2400 loc) · 129 KB
/
Functions.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
// Debug
void printStuff(void) {
//static float CPUtemp = readCPUTemperature(); // If needed for something like calibrating sensors. Can also use IMU temp. The CPU is in the middle of the PCB and the IMU is near the mouthpiece.
//This can be used to print out the currently selected fingering chart (all 256 possible values) when button 1 is clicked.
/*
static byte printed = 0;
if (digitalRead(4) == 0) {
for (unsigned int i = 0; i < 256; i++) {
Serial.print(getNote(i << 1));
Serial.print(" ");
}
delay(5000);
}
*/
for (byte i = 0; i < 9; i++) {
//Serial.println(toneholeRead[i]);
}
//Serial.println(" ");
}
// Determine how long to sleep each time through the loop.
byte calculateDelayTime(void) {
byte delayCorrection = (millis() - wakeTime); // Include a correction factor to reduce jitter if something else in the loop or the radio interrupt has eaten some time.
// The main thing that adds jitter to the loop is sending lots of data over BLE, i.e. pitchbend, CC, etc. (though it's typically not noticeable). Being connected to the Config Tool is also a significant source of jitter.
// With USB MIDI only there is virtually no jitter with a loop period of 2 ms.
//if (delayCorrection > 3) { Serial.println(delayCorrection); } // Print the amount of time that other things have consumed.
byte delayTime = 3;
if (connIntvl == 0) { // Use a 2 ms sleep instead if we are only using USB MIDI.
delayTime = 2;
}
if (delayCorrection < delayTime) { // If we haven't used up too much time since the last time through the loop, we can sleep for a bit.
delayTime = delayTime - delayCorrection;
return delayTime;
}
return 0;
}
// Read the pressure sensor and get latest tone hole readings from the ATmega.
void getSensors(void) {
analogPressure.update(); // Read the pressure sensor now while the ATmega is still asleep and the board is very quiet.
twelveBitPressure = analogPressure.getRawValue();
smoothed_pressure = analogPressure.getValue(); // Use an adaptively smoothed 12-bit reading to map to CC, aftertouch, poly.
sensorValue = twelveBitPressure >> 2; // Reduce the reading to stable 10 bits for state machine.
// Receive tone hole readings from ATmega32U4. The transfer takes ~ 125 us.
byte toneholePacked[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
SPI.beginTransaction(SPISettings(2000000, MSBFIRST, SPI_MODE0));
digitalWrite(2, LOW); // CS -- Wake up ATmega.
delayMicroseconds(10); // Give it time to wake up.
SPI.transfer(0); // We don't receive anything useful back from the first transfer.
for (byte i = 0; i < 12; i++) {
toneholePacked[i] = SPI.transfer(i + 1);
}
digitalWrite(2, HIGH); //CS
SPI.endTransaction();
// Unpack the readings from bytes to ints.
for (byte i = 0; i < 9; i++) {
toneholeRead[i] = toneholePacked[i]; // Unpack lower 8 bits.
}
for (byte i = 0; i < 4; i++) { // Unpack the upper 2 bits of holes 0-3.
toneholePacked[9] = toneholePacked[9] & 0b11111111, BIN;
toneholeRead[i] = toneholeRead[i] | (toneholePacked[9] << 2) & 0b1100000000;
toneholePacked[9] = toneholePacked[9] << 2;
}
for (byte i = 4; i < 8; i++) { // Unpack the upper 2 bits of holes 4-7.
toneholePacked[10] = toneholePacked[10] & 0b11111111, BIN;
toneholeRead[i] = toneholeRead[i] | (toneholePacked[10] << 2) & 0b1100000000;
toneholePacked[10] = toneholePacked[10] << 2;
}
toneholeRead[8] = toneholeRead[8] | (toneholePacked[11] << 8); // Unpack the upper 2 bits of hole 8.
for (byte i = 0; i < 9; i++) {
if (calibration == 0) { // If we're not calibrating, compensate for baseline sensor offset (the stored sensor reading with the hole completely uncovered).
toneholeRead[i] = toneholeRead[i] - toneholeBaseline[i];
}
if (toneholeRead[i] < 0) { // In rare cases the adjusted readings might end up being negative.
toneholeRead[i] = 0;
}
}
}
void readIMU(void) {
// Note: Gyro is turned off by default to save power unless using roll/pitch/yaw or elevation register (see loadPrefs()).
sensors_event_t accel;
sensors_event_t gyro;
sensors_event_t temp;
sox.getEvent(&accel, &gyro, &temp);
rawGyroX = gyro.gyro.x;
rawGyroY = gyro.gyro.y;
rawGyroZ = gyro.gyro.z;
accelX = accel.acceleration.x;
accelY = accel.acceleration.y;
accelZ = accel.acceleration.z;
IMUtemp = temp.temperature;
// Calibrate gyro
gyroX = rawGyroX - gyroXCalibration;
gyroY = rawGyroY - gyroYCalibration;
gyroZ = rawGyroZ - gyroZCalibration;
float deltat = sfusion.deltatUpdate();
deltat = constrain(deltat, 0.001f, 0.01f); // AM 9/16/23 Enabled DWT to make micros() higher resolution for this calculation. Not sure that it matters.
// Serial.println(deltat, 4);
sfusion.MahonyUpdate(gyroX, gyroY, gyroZ, accelX, accelY, accelZ, deltat);
// Pitch and roll are swapped due to PCB sensor orientation.
roll = sfusion.getPitchRadians();
pitch = sfusion.getRollRadians();
yaw = sfusion.getYawRadians();
#if 0
float * quat = sfusion.getQuat();
for (int i=0; i < 4; ++i) {
Serial.print(quat[i], 4);
Serial.print(", ");
}
Serial.println(" 1.1, -1.1");
#endif
currYaw = yaw; // Needs to be the unadjusted value
yaw += yawOffset;
if (yaw > PI) yaw -= TWO_PI;
else if (yaw < -PI) yaw += TWO_PI;
// Adjust pitch so it makes more sense for way warbl is held, shift it 180 deg
pitch += PI;
if (pitch > PI) pitch -= TWO_PI;
// Invert all three.
roll = -roll;
pitch = -pitch;
yaw = -yaw;
roll = roll * RAD_TO_DEG;
pitch = pitch * RAD_TO_DEG;
yaw = yaw * RAD_TO_DEG;
/*
Serial.print(-180);
Serial.print(" , ");
Serial.print(roll);
Serial.print(" , ");
Serial.print(pitch);
Serial.print(" , ");
Serial.print(yaw);
Serial.print(" , ");
Serial.println(180);
*/
#if 1
// Integrate gyroY without accelerometer to get roll in the local frame (around the long axis of the WARBL regardless of orientation). This seems more useful/intuitive than the "roll" Euler angle.
static float rollLocal = roll; // Initialize using global frame.
static float correctionFactor;
const byte correctionRate = 40; // How quickly we correct to the gravity vector when roll and rollLocal have opposite signs.
static float prevYaw;
static float prevRoll;
if ((signbit(yaw - prevYaw) == signbit(roll - prevRoll) && pitch <= 0) || (signbit(yaw - prevYaw) != signbit(roll - prevRoll) && pitch > 0) || (abs(pitch) >= 85)) { // Only integrate gyro if yaw is changing in the same direction as roll (or at a steep pitch angle). This helps minimize the influence of yaw on rollLocal. This could be improved.
rollLocal += ((gyroY * RAD_TO_DEG) * deltat); // Integrate gyro Y axis.
}
prevYaw = yaw;
prevRoll = roll;
if (signbit(rollLocal) != signbit(roll)) { // If roll and rollLocal have opposite signs, nudge rollLocal towards zero, aligning the zero crossing point with gravity.
correctionFactor = rollLocal / correctionRate;
}
else { // No correction if they have the same sign.
correctionFactor = 0;
}
if (abs(pitch) >= 85) { // Correcting for gravity gets sketchy if pitch is near vertical, so don't apply a correction factor then.
correctionFactor = 0;
}
rollLocal -= correctionFactor;
roll = rollLocal;
#endif
// Drumstick mode: WARBL2 must be held by the USB end, with the button side up. No note off messages are sent.
if (IMUsettings[mode][STICKS_MODE]) {
static bool armed = 0;
static float maxGyro;
static byte LEDCounter = 0; // Time how long the LED is on.
if (LEDCounter > 0) { // Count up if the LED is on.
LEDCounter++;
};
if (LEDCounter > 5) { // Turn off LED after a bit.
analogWrite(LEDpins[GREEN_LED], 0);
analogWrite(LEDpins[BLUE_LED], 0);
LEDCounter = 0;
}
if (gyroX > 0.5f) {
armed = true; // Detect forward rotation above a threshold to prepare for a hit.
if (gyroX > maxGyro) { maxGyro = gyroX; } // Find the fastest X rotation, to use for hit velocity.
else if (maxGyro > 0) {
maxGyro -= 0.7f; // Gradually reduce the velocity analog if the rotation is slowing. This adjusts the velocity and/or prevents a hit if you start out with a fast swing but then slow it before the rebound occurs.
}
if (maxGyro <= 0) {
armed = false;
}
}
if (gyroX < 0 && armed == true) { // A hit occurs if we are armed and the X gyro goes negative (indicating a slight rebound).
byte hitVelocity = 12 * (constrain(maxGyro + 1, 1.0f, 10.58f)); // Scale the velocity up to 0-127.
// Just in case
sendMIDI(NOTE_ON, mainMidiChannel, yawOutput, hitVelocity); // Use yawOutput for MIDI note.
analogWrite(LEDpins[GREEN_LED], hitVelocity << 3); // Fire teal LED to indicate a hit, with brightness based on note velocity.
analogWrite(LEDpins[BLUE_LED], hitVelocity << 1);
LEDCounter = 1; // Start counting to turn the LED off again.
armed = false; // Don't allow another hit until we've passed the threshold again.
maxGyro = 0;
powerDownTimer = pitchBendTimer; // Reset the powerDown timer because we're sending notes.
}
}
}
// Calibrate the IMU when the command is received from the Config Tool.
void calibrateIMU() {
sox.setGyroDataRate(LSM6DS_RATE_208_HZ); // Make sure the gyro is on.
delay(50); // Give it a bit of time.
readIMU(); // Get a reading in case we haven't been reading it.
delay(50); // Give it a bit of time.
readIMU(); // Another reading seems to be necessary after turning the gyro on.
gyroXCalibration = rawGyroX;
gyroYCalibration = rawGyroY;
gyroZCalibration = rawGyroZ;
putEEPROM(1975, gyroXCalibration); // Put the current readings into EEPROM.
putEEPROM(1979, gyroYCalibration);
putEEPROM(1983, gyroZCalibration);
writeEEPROM(36, 3); // Remember that we have saved a calibration.
}
// Reset heading 0 to current heading
void centerIMU() {
yawOffset = -currYaw;
}
// Map IMU to CC and send
void sendIMU() {
static byte prevRollCC = 0;
static byte prevPitchCC = 0;
static byte prevYawCC = 0;
// The min and max settings from the Config Tool range from 0-36 and are scaled up to the maximum range of angles for each DOF.
if (IMUsettings[mode][SEND_ROLL]) {
byte lowerConstraint;
byte upperConstraint;
if (IMUsettings[mode][ROLL_OUTPUT_MIN] > IMUsettings[mode][ROLL_OUTPUT_MAX]) { // Flip the constraints if the lower output is greater than the upper output, so the output can be inverted.
lowerConstraint = IMUsettings[mode][ROLL_OUTPUT_MAX];
upperConstraint = IMUsettings[mode][ROLL_OUTPUT_MIN];
}
else {
lowerConstraint = IMUsettings[mode][ROLL_OUTPUT_MIN];
upperConstraint = IMUsettings[mode][ROLL_OUTPUT_MAX];
}
byte rollOutput = constrain(map((roll + 90) * 1000, IMUsettings[mode][ROLL_INPUT_MIN] * 5000, IMUsettings[mode][ROLL_INPUT_MAX] * 5000, IMUsettings[mode][ROLL_OUTPUT_MIN], IMUsettings[mode][ROLL_OUTPUT_MAX]), lowerConstraint, upperConstraint);
//Serial.println(pitchOutput);
if (prevRollCC != rollOutput) {
sendMIDI(CONTROL_CHANGE, IMUsettings[mode][ROLL_CC_CHANNEL], IMUsettings[mode][ROLL_CC_NUMBER], rollOutput);
prevRollCC = rollOutput;
}
}
if (IMUsettings[mode][SEND_PITCH]) {
byte lowerConstraint;
byte upperConstraint;
if (IMUsettings[mode][PITCH_OUTPUT_MIN] > IMUsettings[mode][PITCH_OUTPUT_MAX]) { // Flip the constraints if the lower output is greater than the upper output, so the output can be inverted.
lowerConstraint = IMUsettings[mode][PITCH_OUTPUT_MAX];
upperConstraint = IMUsettings[mode][PITCH_OUTPUT_MIN];
}
else {
lowerConstraint = IMUsettings[mode][PITCH_OUTPUT_MIN];
upperConstraint = IMUsettings[mode][PITCH_OUTPUT_MAX];
}
byte pitchOutput = constrain(map((pitch + 90) * 1000, IMUsettings[mode][PITCH_INPUT_MIN] * 5000, IMUsettings[mode][PITCH_INPUT_MAX] * 5000, IMUsettings[mode][PITCH_OUTPUT_MIN], IMUsettings[mode][PITCH_OUTPUT_MAX]), lowerConstraint, upperConstraint);
//Serial.println(pitchOutput);
if (prevPitchCC != pitchOutput) {
sendMIDI(CONTROL_CHANGE, IMUsettings[mode][PITCH_CC_CHANNEL], IMUsettings[mode][PITCH_CC_NUMBER], pitchOutput);
prevPitchCC = pitchOutput;
}
}
if (IMUsettings[mode][SEND_YAW] || IMUsettings[mode][STICKS_MODE]) {
byte lowerConstraint;
byte upperConstraint;
if (IMUsettings[mode][YAW_OUTPUT_MIN] > IMUsettings[mode][YAW_OUTPUT_MAX]) { // Flip the constraints if the lower output is greater than the upper output, so the output can be inverted.
lowerConstraint = IMUsettings[mode][YAW_OUTPUT_MAX];
upperConstraint = IMUsettings[mode][YAW_OUTPUT_MIN];
}
else {
lowerConstraint = IMUsettings[mode][YAW_OUTPUT_MIN];
upperConstraint = IMUsettings[mode][YAW_OUTPUT_MAX];
}
yawOutput = constrain(map((yaw + 180) * 1000, IMUsettings[mode][YAW_INPUT_MIN] * 10000, IMUsettings[mode][YAW_INPUT_MAX] * 10000, IMUsettings[mode][YAW_OUTPUT_MIN], IMUsettings[mode][YAW_OUTPUT_MAX]), lowerConstraint, upperConstraint);
//Serial.println(yawOutput);
if (prevYawCC != yawOutput && IMUsettings[mode][SEND_YAW]) {
sendMIDI(CONTROL_CHANGE, IMUsettings[mode][YAW_CC_CHANNEL], IMUsettings[mode][YAW_CC_NUMBER], yawOutput);
prevYawCC = yawOutput;
}
}
}
// Use the Y accelerometer axis with gravity removed for vibrato.
void shakeForVibrato() {
static float accelFilteredOld;
const float timeConstant = 0.1f;
float accelFiltered = timeConstant * accelY + (1.0f - timeConstant) * accelFilteredOld; // Low-pass filter to isolate gravity from the Y accelerometer axis.
accelFilteredOld = accelFiltered;
float highPassY = accelY - accelFiltered; // Subtract gravity to high-pass Y.
static float accelFilteredBOld;
const float timeConstant2 = 0.5f;
float accelFilteredB = timeConstant2 * highPassY + (1.0f - timeConstant2) * accelFilteredBOld; // A second low pass filter to minimize spikes from tapping the tone holes.
float lastFilteredB = accelFilteredBOld;
accelFilteredBOld = accelFilteredB;
//accelFilteredB = highPassY; // (Don't) temporarily eliminate this lowpass to see if speeds up response noticeably.
const float shakeBendDepth = 4.0f * IMUsettings[mode][Y_PITCHBEND_DEPTH] / 100; // Adjust the vibrato depth range based on the Config Tool setting.
const float kShakeStartThresh = 0.5f;
const float kShakeFinishThresh = 0.35f;
const long kShakeFinishTimeMs = 400;
const long ktapFilterTimeMs = 12; // ms window for further filtering out taps on the tone holes
static bool shakeActive = false;
static bool tapFilterActive = false;
static long lastThreshExceedTime = 0;
static long tapFilterStartTime = 0;
static bool preTrigger = false;
const float kShakeGestureThresh = 20.0f; // Theshold for shake gesture
unsigned long nowtime = millis();
if (abs(accelFilteredB) > kShakeGestureThresh) {
shakeDetected = true;
} else {
shakeDetected = false;
}
if (IMUsettings[mode][Y_SHAKE_PITCHBEND]) { // Do this part ony if shake pitchbend is turned on.
shakeVibrato = 0;
if (tapFilterActive == false && abs(accelFilteredB) > kShakeStartThresh) {
tapFilterActive = true;
tapFilterStartTime = nowtime;
// Serial.println("Shake Tap Filt");
}
if ((nowtime - tapFilterStartTime) < ktapFilterTimeMs) { // Return if we haven't waited long enough after crossing the shake threshold, for further filtering brief tone hole taps.
return;
}
if (!preTrigger && abs(accelFilteredB) > kShakeStartThresh) {
preTrigger = true;
// Serial.println("Pre Shake Trigger");
}
if (!shakeActive && preTrigger // Start shake vib only when doing a zero crossing after threshold has been triggered.
// Comment out next line to test without the zero crossing requirement
//&& ((lastFilteredB <= 0.0f && accelFilteredB > 0.0f) || (lastFilteredB > 0.0f && accelFilteredB <= 0.0f))
) {
shakeActive = true;
lastThreshExceedTime = nowtime;
// Serial.println("Start ShakeVib");
} else if (abs(accelFilteredB) > kShakeFinishThresh) {
lastThreshExceedTime = nowtime;
}
if ((shakeActive || tapFilterActive) && (nowtime - lastThreshExceedTime) > kShakeFinishTimeMs) {
// Stop shake vibrato.
shakeActive = false;
tapFilterActive = false;
preTrigger = false;
}
if (shakeActive) { // Normalize and clip, +/-15 input seems to be reasonably realistic max accel while still having it in the mouth!
float normshake = constrain(accelFilteredB * 0.06666f, -1.0f, 1.0f);
if (IMUsettings[mode][Y_PITCHBEND_MODE] == Y_PITCHBEND_MODE_UPDOWN) {
normshake *= -1.0f; // reverse phase
} else if (IMUsettings[mode][Y_PITCHBEND_MODE] == Y_PITCHBEND_MODE_DOWNONLY) {
normshake = constrain(normshake, -1.0f, 0.0f);
} else if (IMUsettings[mode][Y_PITCHBEND_MODE] == Y_PITCHBEND_MODE_UPONLY) {
normshake = constrain(-1.0f * normshake, 0.0f, 1.0f);
}
shakeVibrato = (int)(normshake * shakeBendDepth * pitchBendPerSemi);
}
if (pitchBendMode == kPitchBendNone) { // If we don't have finger vibrato and/or slide turned on, we need to send the pitchbend now.
sendPitchbend();
}
}
}
// Return number of registers to jump based on IMU pitch (elevation).
int pitchRegister() {
for (byte i = 1; i < IMUsettings[mode][PITCH_REGISTER_NUMBER] + 1; i++) {
if (pitch < pitchRegisterBounds[i] || (i == IMUsettings[mode][PITCH_REGISTER_NUMBER] && pitch >= pitchRegisterBounds[i])) { // See if IMU pitch is within the bounds for each register.
return i - 1;
}
}
return 0;
}
// Read incoming messages
void readMIDI(void) {
MIDI.read(); // Read any new USBMIDI messages.
if (Bluefruit.connected()) { // Don't read if we aren't connected to BLE.
if (blemidi.notifyEnabled()) { // ...and ready to receive messages.
BLEMIDI.read(); // Read new BLEMIDI messages.
}
}
}
// Monitor the status of the 3 buttons. The integrating debouncing algorithm is taken from debounce.c, written by Kenneth A. Kuhn:http://www.kennethkuhn.com/electronics/debounce.c
// NOTE: Button array is zero-indexed, so "button 1" in all documentation is button 0 here.
void checkButtons() {
static byte integrator[] = { 0, 0, 0 }; // When this reaches MAXIMUM, a button press is registered. When it reaches 0, a release is registered.
static bool prevOutput[] = { 0, 0, 0 }; // Previous state of button.
bool buttonUsed = 0; // Flag any button activity, so we know to handle it.
static unsigned int longPressCounter[] = { 0, 0, 0 }; // For counting how many readings each button has been held, to indicate a long button press
for (byte j = 0; j < 3; j++) {
if (digitalRead(buttons[j]) == 0) { // If the button reads low, reduce the integrator by 1
if (integrator[j] > 0) {
integrator[j]--;
}
} else if (integrator[j] < MAXIMUM) { // If the button reads high, increase the integrator by 1
integrator[j]++;
}
if (integrator[j] == 0) { // The button is pressed.
pressed[j] = 1; // We make the output the inverse of the input so that a pressed button reads as a "1".
buttonUsed = 1;
if (prevOutput[j] == 0 && !longPressUsed[j]) {
justPressed[j] = 1; // The button has just been pressed
}
else {
justPressed[j] = 0;
}
if (prevOutput[j] == 1) { // Increase a counter so we know when a button has been held for a long press.
longPressCounter[j]++;
}
}
else if (integrator[j] >= MAXIMUM) { // The button is not pressed.
pressed[j] = 0;
integrator[j] = MAXIMUM; // Defensive code if integrator got corrupted
if (prevOutput[j] == 1 && !longPressUsed[j]) {
released[j] = 1; // The button has just been released.
buttonUsed = 1;
}
longPress[j] = 0;
longPressUsed[j] = 0; // If a button is not pressed, reset the flag that tells us it's been used for a long press.
longPressCounter[j] = 0;
}
if (longPressCounter[j] > 300 && !longPressUsed[j]) { // If the counter gets to a certain level, it's a long press.
longPress[j] = 1;
longPressCounter[j] = 0;
buttonUsed = 1;
}
prevOutput[j] = pressed[j]; // Keep track of state for next time around.
}
if (millis() < 1000) { // Ignore button 3 for the first bit after powerup in case it was only being used to power on the device. ToDo?: Make it so the first release after startup isn't registered because if you hold 3 longer than 1 second it will still register.
pressed[2] = 0;
released[2] = 0;
}
if (buttonUsed) {
handleButtons(); // If a button had been used, process the command. We only do this when we need to, so we're not wasting time.
}
buttonUsed = 0; // Now that we've handled any important button activity, clear the flag until there's been new activity.
}
// Determine which holes are covered.
void getFingers() {
for (byte i = 0; i < 9; i++) {
if ((toneholeRead[i]) > (toneholeCovered[i] - 50)) {
bitWrite(holeCovered, i, 1); // Use the tonehole readings to decide which holes are covered
} else if ((toneholeRead[i]) <= (toneholeCovered[i] - 54)) {
bitWrite(holeCovered, i, 0); // Decide which holes are uncovered -- the "hole uncovered" reading is a little less then the "hole covered" reading, to prevent oscillations.
}
}
}
// This should be called right after a new hole state change, before sending out any new note.
bool isMaybeInTransition() {
// Look at all finger hole state to see if there might be other
// fingers in motion (partial hole covered) which means this
// might be a multi-finger note transition and we may want to wait
// a bit to see if the pending fingers land before triggering the new note.
int pendingHoleCovered = holeCovered;
unsigned long now = millis();
int otherholes = 0;
for (byte i = 0; i < 9; i++) {
int thresh = senseDistance; // ((toneholeCovered[i] - 50) - senseDistance) / 2;
if (toneholeRead[i] > thresh) {
if (bitRead(holeCovered, i) != 1) {
bitWrite(pendingHoleCovered, i, 1);
++otherholes;
/*
Serial.print("offs: ");
Serial.print(offsetSteps);
Serial.print(" tscale: ");
Serial.print(toneholeScale[i]);
Serial.print(" bend: ");
Serial.println(iPitchBend[i]);
*/
}
}
}
if (pendingHoleCovered != holeCovered) {
// See if the pending is a new note.
int tempNewNote = getNote(holeCovered);
int pendingNote = getNote(pendingHoleCovered);
if (pendingNote >= 0 && pendingNote != tempNewNote) {
#if DEBUG_TRANSITION_FILTER
Serial.print(now);
Serial.print(" : Maybe: ");
Serial.print(pendingNote);
Serial.print(" wait on: ");
Serial.println(tempNewNote);
#endif
return true;
}
}
return false;
}
// Key delay feature for delaying response to tone holes and filtering out transient notes, originally by Louis Barman, but reworked by Jesse Chappell
void debounceFingerHoles() {
static unsigned long debounceTimer;
unsigned long now = millis();
static bool timing;
if (prevHoleCovered != holeCovered) {
prevHoleCovered = holeCovered;
debounceTimer = now;
timing = 1;
if (transientFilterDelay > 0 && isMaybeInTransition()) {
transitionFilter = transientFilterDelay; // ms timeout for transition to fail out
} else {
transitionFilter = 0;
}
}
long debounceDelta = now - debounceTimer;
if (transitionFilter > 0 && (debounceDelta >= transitionFilter || !isMaybeInTransition())) {
// reset it if necessary
#if DEBUG_TRANSITION_FILTER
Serial.print(now);
Serial.println(" canceltrans");
#endif
transitionFilter = 0;
}
if (debounceDelta >= transitionFilter
&& timing == 1) { // The fingering pattern has changed.
timing = 0;
fingersChanged = 1;
tempNewNote = getNote(holeCovered); // Get the next MIDI note from the fingering pattern if it has changed. 3us.
sendToConfig(true, false); // Put the new pattern into a queue to be sent later so that it's not sent during the same connection interval as a new note (to decrease BLE payload size).
if (tempNewNote != -1 && newNote != tempNewNote) { // If a new note has been triggered,
if (pitchBendMode != kPitchBendNone) {
holeLatched = holeCovered; // remember the pattern that triggered it (it will be used later for vibrato).
for (byte i = 0; i < 9; i++) {
iPitchBend[i] = 0; // Reset pitchbend.
pitchBendOn[i] = 0;
}
}
}
#if DEBUG_TRANSITION_FILTER
Serial.print(now);
Serial.print(" : Commit: ");
Serial.println(tempNewNote);
#endif
newNote = tempNewNote;
tempNewNote = -1;
getState(); // Get state again if the note has changed.
fingeringChangeTimer = millis(); // Start timing after the fingering pattern has changed.
}
}
// Send the finger pattern and pressure to the Configuration Tool after a delay to prevent sending during the same connection interval as a new MIDI note.
void sendToConfig(bool newPattern, bool newPressure) {
static bool patternChanged = false;
static bool pressureChanged = false;
static unsigned long patternSendTimer;
static unsigned long pressureSendTimer;
unsigned long nowtime = millis();
if (communicationMode) {
if (newPattern && patternChanged == false) { // If the fingering pattern has changed, start a timer.
patternChanged = true;
patternSendTimer = nowtime;
}
if (newPressure && pressureChanged == false) { // If the pressure has changed, start a timer.
pressureChanged = true;
pressureSendTimer = nowtime;
}
if (patternChanged && (nowtime - patternSendTimer) > 25) { // If some time has past, send the new pattern to the Config Tool.
sendMIDI(CONTROL_CHANGE, 7, 114, holeCovered >> 7); // Because it's MIDI we have to send it in two 7-bit chunks.
sendMIDI(CONTROL_CHANGE, 7, 115, lowByte(holeCovered));
patternChanged = false;
}
if (pressureChanged && (nowtime - pressureSendTimer) > 25) { // If some time has past, send the new pressure to the Config Tool.
sendMIDI(CONTROL_CHANGE, 7, 116, sensorValue & 0x7F); // Send LSB of current pressure to Configuration Tool.
sendMIDI(CONTROL_CHANGE, 7, 118, sensorValue >> 7); // Send MSB of current pressure.
pressureChanged = false;
}
}
}
// Return a MIDI note number (0-127) based on the current fingering.
int getNote(unsigned int fingerPattern) {
int ret = -1; // Default for unknown fingering
uint8_t tempCovered = fingerPattern >> 1; // Bitshift once to ignore bell sensor reading.
// Read the MIDI note for the current fingering (all charts except the custom ones).
if (modeSelector[mode] < kWARBL2Custom1) {
ret = charts[modeSelector[mode]][tempCovered];
} else {
ret = WARBL2CustomChart[tempCovered]; // Otherwise read from the currently selected custom chart.
}
// For whistle and uilleann also read the vibrato flag for the current fingering.
if (modeSelector[mode] == kModeWhistle || modeSelector[mode] == kModeChromatic) {
vibratoEnable = whistleVibrato[tempCovered];
}
if (modeSelector[mode] == kModeUilleann || modeSelector[mode] == kModeUilleannStandard) {
vibratoEnable = uilleannVibrato[tempCovered];
}
return ret;
}
// Add up any transposition based on key and register.
void getShift() {
byte pitchShift;
if (IMUsettings[mode][PITCH_REGISTER] == true) {
pitchShift = pitchRegister();
}
shift = ((octaveShift * 12) + noteShift + (pitchShift * 12)); // Adjust for key and octave shift.
// Overblow if allowed.
if (newState == 3 && !(modeSelector[mode] == kModeEVI || (modeSelector[mode] == kModeSax && newNote < 58) || (modeSelector[mode] == kModeSaxBasic && newNote < 70) || (modeSelector[mode] == kModeRecorder && newNote < 74)) && !(newNote == 62 && (modeSelector[mode] == kModeUilleann || modeSelector[mode] == kModeUilleannStandard))) { // If overblowing (except EVI, sax and recorder in the lower register, and low D with uilleann fingering, which can't overblow)
shift = shift + 12; // Add a register jump to the transposition if overblowing.
if (modeSelector[mode] == kModeKaval) { // Kaval only plays a fifth higher in the second register.
shift = shift - 5;
}
}
// Use the bell sensor to control register if desired.
if (breathMode == kPressureBell && modeSelector[mode] != kModeUilleann && modeSelector[mode] != kModeUilleannStandard) {
if (bitRead(holeCovered, 0) == switches[mode][INVERT]) {
shift = shift + 12;
if (modeSelector[mode] == kModeKaval) {
shift = shift - 5;
}
}
}
// ToDo: Are there any others that don 't use the thumb that can be added here? For custom charts the thumb needs to hard-coded instead.
else if ((breathMode == kPressureThumb && (modeSelector[mode] == kModeWhistle || modeSelector[mode] == kModeChromatic || modeSelector[mode] == kModeNAF))) { // If we're using the left thumb to control the regiser with a fingering patern that doesn't normally use the thumb
if (bitRead(holeCovered, 8) == switches[mode][INVERT]) {
shift = shift + 12; // Add an octave jump to the transposition if necessary.
}
}
}
// State machine that models the way that a tinwhistle etc. begins sounding and jumps octaves in response to breath pressure.
// The current jump/drop behavior is from Louis Barman
void getState() {
byte scalePosition; // ScalePosition is used to tell where we are on the scale, because higher notes are more difficult to overblow.
unsigned int tempHoleCovered = holeCovered;
bitSet(tempHoleCovered, 8); // Ignore thumb hole.
scalePosition = findleftmostunsetbit(tempHoleCovered) + 62; // Use the highest open hole to calculate.
if (scalePosition > 69) {
scalePosition = 70;
}
if (ED[mode][DRONES_CONTROL_MODE] == 3) { // Use pressure to control drones if that option has been selected. There's a small amount of hysteresis added.
if (!dronesOn && sensorValue > 5 + (ED[mode][DRONES_PRESSURE_HIGH_BYTE] << 7 | ED[mode][DRONES_PRESSURE_LOW_BYTE])) {
startDrones();
}
else if (dronesOn && sensorValue < (ED[mode][DRONES_PRESSURE_HIGH_BYTE] << 7 | ED[mode][DRONES_PRESSURE_LOW_BYTE])) {
stopDrones();
}
}
upperBound = (sensorThreshold[1] + ((scalePosition - 60) * multiplier)); // Calculate the threshold between state 2 (bottom register) and state 3 (top register). This will also be used to calculate expression.
newState = currentState;
if (sensorValue <= sensorThreshold[0]) {
newState = SILENCE;
holdoffActive = false; // No need to wait for jump/drop if we've already crossed the threshold for silence
} else if (sensorValue > sensorThreshold[0] + SILENCE_HYSTERESIS) {
if (currentState == SILENCE) {
newState = BOTTOM_REGISTER;
}
if (breathMode == kPressureBreath) { // If overblowing is enabled
upperBoundHigh = calcHysteresis(upperBound, true);
upperBoundLow = calcHysteresis(upperBound, false);
if (sensorValue > upperBoundHigh) {
newState = TOP_REGISTER;
holdoffActive = false;
} else if (sensorValue <= upperBoundLow) {
newState = BOTTOM_REGISTER;
}
// Wait to decide about jump or drop if necessary.
if (currentState == SILENCE && newState == BOTTOM_REGISTER) {
newState = delayStateChange(JUMP, sensorValue, upperBoundHigh);
} else if (currentState == TOP_REGISTER && newState == BOTTOM_REGISTER && (millis() - fingeringChangeTimer) > 20) { // Only delay for drop if the note has been playing for a bit. This fixes erroneous high-register notes.
newState = delayStateChange(DROP, sensorValue, upperBoundLow);
}
}
}
currentState = newState;
if (switches[mode][SEND_VELOCITY]) { // If we're sending NoteOn velocity based on pressure,
if (prevState == SILENCE && newState != SILENCE) {
velocityDelayTimer = millis(); // reset the delay timer used for calculating velocity when a note is turned on after silence.
}
prevState = newState;
}
}
// Delay the overblow state until either it has timed out or the pressure has leveled off.
byte delayStateChange(byte jumpDrop, int pressure, int upper) {
static unsigned long holdOffTimer;
unsigned long now = millis();
bool exitEarly = false;
int rateChange;
if (!holdoffActive) { // Start our timer if we haven't already.
holdoffActive = true;
holdOffTimer = now;
rateChangeIdx = 0;
previousPressure = 0;
}
if ((jumpDrop == JUMP && (now - holdOffTimer) < jumpTime) || (jumpDrop == DROP && (now - holdOffTimer) < dropTime)) { // If we haven't paused long enough, check the pressure rate change to see if it has leveled off.
rateChange = pressureRateChange(pressure);
if (rateChange != 2000) { // Make sure it's valid
if (jumpDrop == JUMP && rateChange <= 0) {
exitEarly = true;
} else if (jumpDrop == DROP && rateChange >= 0) {
exitEarly = true;
}
}
}