-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.cpp
628 lines (568 loc) · 20.5 KB
/
main.cpp
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
#include "Arduino.h"
#include "MIDIUSB.h"
#include "Timer.h"
#include "DriverMatrix.h"
#include "DriverLEDs.h"
#include "DrumKit.h"
#include "DriverVolume.h"
#include "DriverLCD.h"
// DEFINICION DE VARIABLES ====================================================
#define VELOCITY 127 // velocidad/volumen de notas por defecto
typedef struct _instrument {
bool mute; // mute on/off
int kitSound; // instrumento del kit correspondiente
uint8_t pattern; // patron de sonido (usar uint16_t para 16 botones)
} instrument;
enum operationModes {
live, // reproduce el patron de cada instrumento los botones generan sonido en cuanto se presionan (en vivo)
patternEditor, // editor de patrones de cada instrumento
instrumentEditor, // editor de set de instrumentos
mute // permite mutear temporalmente cada instrumento
};
const int matrixSize = 8; // numero de botones en la matriz (actualizar driver ante cambio)
instrument myInstrumentSet[matrixSize];
int defaultInstrumentSet[] = {
BASS_DRUM_2,
SNARE_DRUM_1,
SIDE_STICK,
CLOSED_HI_HAT,
CHINESE_CYMBAL,
HIGH_AGOGO,
SHORT_GUIRO,
CLAVES };
int midiChannel = 10; // canal por defecto (es el que se suele usar p/percusion)
int bpm = 200; // tempo por defecto
int bpmStep = 10; // tamaño del incremento/decremento de BPMs
int currentStep = -1; // paso actual (va de 0 a matrixSize - 1)
long currentLEDPattern = 0; // estado actual de los LEDs de la matriz
int minVolumeValidChange = 5;
int lastValidVolume = 0;
int currentVolume = 127;
bool paused = false;
enum operationModes currentMode = live;
rgb_lcd LCD;
bool printLCD = true;
byte pauseIcon[8] = {0b00000,0b11011,0b11011,0b11011,0b11011,0b11011,0b11011,0b00000};
byte playIcon[8] = {0b00000,0b11000,0b11110,0b11111,0b11111,0b11110,0b11000,0b00000};
// auxiliares varios para LCD
bool firstLoop = true;
bool modeChanged = true;
bool bpmChanged = false;
bool playPauseChanged = false;
bool volumeChanged = false;
long checkPointQuickMessage = 0;
int quickMessageDelay = 500;
// auxiliares varios para editor de patrones
int instrumentChosen = -1;
// auxiliares para manejo de LEDs
long LEDsPatternAux;
// SETUP & LOOP ===============================================================
void setup() {
buttonsInit('B', PB4, PB5, PB6);
timerInit(stepActions);
LEDsInit();
volumeInit(0,0,127);
setTimerBPM(bpm);
// inicializo LCD y caracteres custom
LCD.begin(16, 2);
LCD.createChar(0,pauseIcon);
LCD.createChar(1,playIcon);
setDefaultIntrumentSet();
setButtonsAction();
// p/debugging (patrones sencillos) █ ░
myInstrumentSet[0].pattern = 0b00010101;
// patron de LEDs por defecto
setLEDsPattern(0b10101010);
// p/debugging
// Serial.begin(9600);
// me aseguro de que el puerto este abierto antes de empezar a tirarle que imprima
// while (!Serial);
// [!] OJO: hace que no sea plug and play, si no esta el monitor del puerto serie
// abierto no va a arrancar
// Serial.println("Status ║ Actions");
// Serial.println("═════════════════════════════════╩════════════════════════════════════════════");
}
void loop() {
timerScan(); // ejecuta stepActions (cuando corresponda)
buttonsScan(); // ejecuta funcion de botones de la matriz (cuando corresponda)
volumeScan();
updateLCD();
updateLEDs();
updateVolume();
firstLoop = false;
}
// METODOS VARIOS =============================================================
// configura accion correspondiente a cada boton en la matriz
void setButtonsAction() {
// Botones de Matriz
// Boton 0
buttonPressCallback(matrixButtonPress, BUTTON_0);
buttonReleaseCallback(matrixButtonRelease, BUTTON_0);
// Boton 1
buttonPressCallback(matrixButtonPress, BUTTON_1);
buttonReleaseCallback(matrixButtonRelease, BUTTON_1);
// Boton 2
buttonPressCallback(matrixButtonPress, BUTTON_2);
buttonReleaseCallback(matrixButtonRelease, BUTTON_2);
// Boton 3
buttonPressCallback(matrixButtonPress, BUTTON_3);
buttonReleaseCallback(matrixButtonRelease, BUTTON_3);
// Boton 4
buttonPressCallback(matrixButtonPress, BUTTON_4);
buttonReleaseCallback(matrixButtonRelease, BUTTON_4);
// Boton 5
buttonPressCallback(matrixButtonPress, BUTTON_5);
buttonReleaseCallback(matrixButtonRelease, BUTTON_5);
// Boton 6
buttonPressCallback(matrixButtonPress, BUTTON_6);
buttonReleaseCallback(matrixButtonRelease, BUTTON_6);
// Boton 7
buttonPressCallback(matrixButtonPress, BUTTON_7);
buttonReleaseCallback(matrixButtonRelease, BUTTON_7);
// Botones de Control
// Boton 8
buttonPressCallback(increaseBPM, BUTTON_8);
// Boton 9
buttonPressCallback(decreaseBPM, BUTTON_9);
// Boton 10
buttonPressCallback(previousInstrument, BUTTON_10);
// Boton 11
buttonPressCallback(nextInstrument, BUTTON_11);
// Boton 12
buttonPressCallback(previousMode, BUTTON_12);
// Boton 13
buttonPressCallback(nextMode, BUTTON_13);
// Boton 14
buttonPressCallback(done, BUTTON_14);
// Boton 15
buttonPressCallback(playPause, BUTTON_15);
}
// configura un set de intrumentos por defecto
void setDefaultIntrumentSet() {
for (int i = 0; i < matrixSize; i++) {
myInstrumentSet[i].mute = false;
myInstrumentSet[i].kitSound = defaultInstrumentSet[i];
myInstrumentSet[i].pattern = 0;
}
}
// ejecuta acciones que se dan con cada step: reproducir sonidos, led del tempo, etc
void stepActions() {
// si estoy en pausa me quedo en el paso en el que estoy
if (!paused) {
currentStep = (currentStep + 1) % matrixSize;
switch (currentMode) {
case live:
playPatterns();
break;
case mute:
playPatterns();
break;
case patternEditor:
playPatterns();
break;
case instrumentEditor:
playPatterns();
break;
default:
// switchDefault("stepActions");
break;
}
}
}
// reproduce todos los sonidos habilitados para el step actual
void playPatterns() {
// miro el patron de cada instrumento y chequeo si corresponde tocar su nota
for (int i = 0; i < matrixSize; i++) {
if (!myInstrumentSet[i].mute) {
if (bitRead(myInstrumentSet[i].pattern, (matrixSize - 1) - currentStep)) { // lee el patron de MSB a LSB
noteOff(midiChannel, getInstrumentNote(myInstrumentSet[i].kitSound), VELOCITY);
noteOn(midiChannel, getInstrumentNote(myInstrumentSet[i].kitSound), VELOCITY);
MidiUSB.flush();
}
}
}
}
// actualiza el texto y color del LCD segun el modo en el que este
void updateLCD() {
if (modeChanged) {
switch (currentMode) {
case live:
LCD.setRGB(100,204,204); //turquesa o algo asi
printLinesLCD("LIVE ","play something ");
// p/debugging
// Serial.println("LCD: | LIVE |");
// Serial.println(" | play something |");
break;
case patternEditor:
if (instrumentChosen < 0) {
LCD.setRGB(220,100,50);
// todavia no elegi instrumento
printLinesLCD("PATTERN EDITOR ","select inst. ");
// p/debugging
// Serial.println("LCD: | PATTERN EDITOR |");
// Serial.println(" | select inst |");
} else {
LCD.setRGB(220,100,50);
// ya elegi instrumento, estoy editando su patron
printLinesLCD("PATTERN EDITOR ","editing inst. ");
// p/debugging
// Serial.println("LCD: | PATTERN EDITOR |");
// Serial.print (" | editing inst ");
// Serial.print (instrumentChosen);
// Serial.println(" |");
// [!] ojo con que sea de dos digitos el numero de instrumento
}
break;
case instrumentEditor:
if (instrumentChosen < 0) {
LCD.setRGB(129,218,70); //verdecito o algo asi
// todavia no elegi instrumento
printLinesLCD("SET EDITOR ","select inst. ");
// p/debugging
// Serial.println("LCD: | SET EDITOR |");
// Serial.println(" | select inst |");
} else {
LCD.setRGB(129,218,70); //verdecito o algo asi
// ya elegi instrumento, estoy editando su patron
printLinesLCD("SET EDITOR ","editing inst. ");
// p/debugging
// Serial.println("LCD: | SET EDITOR |");
// Serial.print (" | editing inst ");
// Serial.print (instrumentChosen);
// Serial.println(" |");
// [!] ojo con que sea de dos digitos el numero de instrumento
}
break;
case mute:
LCD.setRGB(240,229,59); //turquesa o algo asi
printLinesLCD("MUTE ","select inst. ");
// p/debugging
// Serial.println("LCD: | MUTE |");
// Serial.println(" | select inst |");
break;
default:
// switchDefault("updateLCD");
break;
}
modeChanged = false;
}
if (playPauseChanged) {
// p/debugging
// Serial.println(paused ? "Paused ◦" : "Playing •");
playPauseChanged = false;
}
if (bpmChanged) {
// p/debuggin
// Serial.print("BPM: ");
// Serial.println(bpm);
bpmChanged = false;
}
// cambiar!
if (volumeChanged) {
if (millis() - checkPointQuickMessage > quickMessageDelay) {
volumeChanged = false;
modeChanged = true;
} else {
printVolumeLCD();
}
} else {
printPausePlayLCD();
}
}
void updateLEDs() {
// inicializo variable auxiliar
LEDsPatternAux = 0;
// actualizo LEDs segun modo
switch (currentMode) {
case live:
setLEDsPattern((1 << currentStep) | getMatrixButtonsState());
break;
case patternEditor:
if (instrumentChosen < 0) {
// todavia no elegi instrumento
runLEDs();
} else {
// ya elegi instrumento, estoy editando su patron
for (int i = 0; i < matrixSize; i++) {
if (bitRead(myInstrumentSet[instrumentChosen].pattern, (matrixSize - 1) - i)) {
LEDsPatternAux |= (1 << i);
}
}
// si esta pausado solo muestra el patron, para que no se confunda que LEDs son del patron y el del Step actual
if (paused) {
setLEDsPattern(LEDsPatternAux);
} else {
setLEDsPattern(LEDsPatternAux | (1 << currentStep));
}
}
break;
case instrumentEditor:
if (instrumentChosen < 0) {
// todavia no elegi instrumento
runLEDsReverse();
} else {
// ya elegi instrumento, estoy editando su patron
setLEDsPattern((1 << instrumentChosen));
}
break;
case mute:
for (int i = 0; i < matrixSize; i++) {
// activo los LEDs a cada paso segun le corresponde sonar o este muteado
if (myInstrumentSet[i].mute || bitRead(myInstrumentSet[i].pattern, (matrixSize - 1) - currentStep)) {
LEDsPatternAux |= (1 << i);
}
}
setLEDsPattern(LEDsPatternAux);
break;
default:
// p/debugging
// switchDefault("updateLEDs");
blinkLEDs();
break;
}
showLEDsPattern();
}
void updateVolume() {
currentVolume = getVolume();
// la primera vez hago un ajuste para no tomar la dif. entre valor previo y actual como intencional
if (firstLoop) {
lastValidVolume = currentVolume;
}
// filtro cambios esporadicos por variaciones leves en durante sensado
if ((currentVolume > lastValidVolume + minVolumeValidChange) || (currentVolume < lastValidVolume - minVolumeValidChange)) {
// si esta a +- cierta tolerancia, tomo el cambio de volumen como valido
lastValidVolume = currentVolume;
volumeChange(midiChannel,lastValidVolume);
checkPointQuickMessage = millis();
volumeChanged = true;
}
}
// LCD ========================================================================
void printLinesLCD(char* line1, char* line2) {
LCD.setCursor(0,0);
LCD.print(line1);
LCD.setCursor(0,1);
LCD.print(line2);
}
void printVolumeLCD() {
LCD.setCursor(0,0);
LCD.print("VOLUME ");
LCD.setCursor(0,1);
// mapeo aprox del volumen a los 16 lugares en el LCD
for (int i = 0; i < lastValidVolume/7; i++) {
LCD.write((char)0b11111111); // cuadrado negro
}
for (int i = 0; i < 16 - lastValidVolume/7; i++) {
LCD.write((char)0b10100101); // punto centrado
}
}
void printBpmLCD() {
printLinesLCD(" BPM "," test ");
}
void printPausePlayLCD() {
LCD.setCursor(15,0);
if (paused) {
LCD.write((byte)0);
} else {
LCD.write((byte)1);
}
}
// MIDI =======================================================================
void noteOn(byte channel, byte note, byte velocity) {
midiEventPacket_t noteOn = {0x09, 0x90 | channel, note, velocity};
MidiUSB.sendMIDI(noteOn);
}
void noteOff(byte channel, byte note, byte velocity) {
midiEventPacket_t noteOff = {0x08, 0x80 | channel, note, velocity};
MidiUSB.sendMIDI(noteOff);
}
void volumeChange(byte channel, byte value) {
midiEventPacket_t ctrlChange = {0x0B, 0xB0 | channel, 7, value};
MidiUSB.sendMIDI(ctrlChange);
}
// Acciones de los botones de la matriz =======================================
void matrixButtonPress(int n) {
// p/debugging
// Serial.print(" [Button ");
// Serial.print(n);
// Serial.println(": ↓]");
switch (currentMode) {
case live:
// envio mensaje MIDI
noteOn(midiChannel, getInstrumentNote(myInstrumentSet[n].kitSound), VELOCITY);
MidiUSB.flush();
// p/debugging
// Serial.print("Played: INST_");
// Serial.println(n);
break;
case patternEditor:
if (instrumentChosen < 0) {
// todavia no elegi -> marco como elegido al boton presionado
instrumentChosen = n;
modeChanged = true;
} else {
// ya fue elegido el instrumento -> edito su patron
// toggle del bit en la posicion n (ojo, de adelante hacia atras, que es como se reproduce el patron)
// quedaria mal si el boton 0 hiciera toggle al bit 0 del patron
myInstrumentSet[instrumentChosen].pattern ^= (1 << (matrixSize - 1) - n);
// p/debugging
// Serial.print("New pattern: ");
// for(int i = matrixSize - 1; i >= 0; i--) {
// Serial.print(bitRead(myInstrumentSet[instrumentChosen].pattern,i) ? "▇ " : "▁ ");
// }
// Serial.println("");
}
break;
case instrumentEditor:
if (instrumentChosen < 0) {
// todavia no elegi -> marco como elegido al boton presionado
instrumentChosen = n;
modeChanged = true;
}
break;
case mute:
myInstrumentSet[n].mute = !myInstrumentSet[n].mute;
// p/debugging
// Serial.print(myInstrumentSet[n].mute ? "Mute ON: INST_" : "Mute OFF: INST_");
// Serial.println(n);
break;
default:
// switchDefault("matrixButtonPress");
break;
}
}
void matrixButtonRelease(int n) {
// p/debugging
// Serial.print(" [Button ");
// Serial.print(n);
// Serial.println(": ↑]");
switch (currentMode) {
case live:
noteOff(midiChannel, getInstrumentNote(myInstrumentSet[n].kitSound), VELOCITY);
MidiUSB.flush();
// p/debugging
// Serial.print("Played: INST_");
// Serial.println(n);
break;
case mute:
case patternEditor:
case instrumentEditor:
break;
default:
// switchDefault("matrixButtonRelease");
break;
}
}
// Acciones de los botones de control =========================================
void nextMode() {
// habilito cambio de modo siempre que no este en el medio de una edicion
if (instrumentChosen < 0) {
switch (currentMode) {
case live:
currentMode = patternEditor;
break;
case patternEditor:
currentMode = instrumentEditor;
break;
case instrumentEditor:
currentMode = mute;
break;
case mute:
currentMode = live;
break;
default:
// switchDefault("nextMode");
break;
}
modeChanged = true;
// p/debugging
// Serial.println(" [Command: Mode >]");
}
}
void previousMode() {
// habilito cambio de modo siempre que no este en el medio de una edicion
if (instrumentChosen < 0) {
switch (currentMode) {
case live:
currentMode = mute;
break;
case patternEditor:
currentMode = live;
break;
case instrumentEditor:
currentMode = patternEditor;
break;
case mute:
currentMode = instrumentEditor;
break;
default:
// switchDefault("previousMode");
break;
}
modeChanged = true;
// p/debugging
// Serial.println(" [Command: Mode <]");
}
}
void increaseBPM() {
bpm = (bpm + bpmStep > 300)? 300 : bpm + bpmStep;
setTimerBPM(bpm);
bpmChanged = true;
// p/debugging
// Serial.println(" [Command: BPM +]");
}
void decreaseBPM() {
bpm = (bpm - bpmStep < 0 )? 0 : bpm - bpmStep;
setTimerBPM(bpm);
checkPointQuickMessage = millis();
bpmChanged = true;
// p/debugging
// Serial.println(" [Command: BPM -]");
}
void nextInstrument() {
// si estaba en modo edicion de instrumento y ya habia elegido instrumento -> salgo de la edicion de ese instrumento
if ((currentMode == instrumentEditor) && (instrumentChosen >= 0)) {
myInstrumentSet[instrumentChosen].kitSound = getNextInstrument(myInstrumentSet[instrumentChosen].kitSound);
// preview de sonido
noteOff(midiChannel, getInstrumentNote(myInstrumentSet[instrumentChosen].kitSound), VELOCITY);
noteOn(midiChannel, getInstrumentNote(myInstrumentSet[instrumentChosen].kitSound), VELOCITY);
MidiUSB.flush();
// p/debugging
// Serial.println(" [Command: Next Instrument >]");
}
}
void previousInstrument() {
// si estaba en modo edicion de instrumento y ya habia elegido instrumento -> salgo de la edicion de ese instrumento
if ((currentMode == instrumentEditor) && (instrumentChosen >= 0)) {
myInstrumentSet[instrumentChosen].kitSound = getPreviousInstrument(myInstrumentSet[instrumentChosen].kitSound);
// preview de sonido
noteOff(midiChannel, getInstrumentNote(myInstrumentSet[instrumentChosen].kitSound), VELOCITY);
noteOn(midiChannel, getInstrumentNote(myInstrumentSet[instrumentChosen].kitSound), VELOCITY);
MidiUSB.flush();
// p/debugging
// Serial.println(" [Command: Previous Instrument <]");
}
}
void playPause() {
paused = !paused;
playPauseChanged = true;
// p/debugging
// Serial.println(" [Command: Pause/Play]");
}
void done() {
// si estaba en modo edicion y ya habia elegido instrumento -> salgo de la edicion de ese instrumento
if ((currentMode == patternEditor || currentMode == instrumentEditor) && (instrumentChosen >= 0)) {
instrumentChosen = -1;
// [!] HORRIBLE OTRA VEZ
modeChanged = true;
// p/debugging
// Serial.println(" [Command: Editing done]");
}
}
// PARA DEBUGGING =============================================================
// void switchDefault(char* str) {
// p/debugging
// Serial.print(" [!: Switch Default - ");
// Serial.print(str);
// Serial.println("]");
// }