Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
2270 lines (2090 loc) · 86.3 KB
/
Copy pathmain.cpp
File metadata and controls
2270 lines (2090 loc) · 86.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
GateXtal — monophonic FM synth + sequencer (Mozzi)
ESP32-S3 SuperMini port of the original ATmega32u4 version.
By Daniel Lacey a.k.a. Captain Credible
PINOUT (GPIO numbers as printed on the SuperMini):
A button ..... 11 (all buttons to GND, internal pullups)
B button ..... 12
SHIFT button . 13 (held = alternate knob functions on every page)
PAGE button .. 1 (single button, cycles the 7 pages:
MAIN / AMPENV / LFO / VERB / H4XX / SEQ / PERF)
ARCADE button .. 43 (the "TX" pin — plain GPIO once booted; the boot ROM
chatters on it for ~100ms at reset, harmless for a
button. A 470R-1k series resistor is cheap insurance
against holding it during reset.)
POTS ....... 2,3,4,5 (FM / haxx / attack / release — all ADC1)
MIDI DIN in .... 44 (the "RX" pin, optional — RX only, TX stays free)
PCM5102A:
BCK ... 10
LCK .... 8 (word select / LRCLK)
DIN .... 9
SCK .... GND (DAC generates its own master clock from BCK)
SSD1306 OLED (I2C, 128x64, addr 0x3C):
SDA .... 7
SCL .... 6
Changes from the 32u4 version:
- Audio out via I2S to the PCM5102A instead of PWM (16-bit now!)
- One PAGE button instead of +/- page buttons
- SSD1306 OLED shows the current page + its four knob values. It is
drawn by a FreeRTOS task pinned to core 0 (Arduino/Mozzi run on
core 1), so the ~23ms I2C framebuffer push never blocks the DSP.
- No LEDs, so the LED-pin external gate sync input is gone. Ext-clock
mode = MIDI clock or stepping manually with the arcade button, as before.
- USB-MIDI via the S3's native USB (enumerates as "GateXtal"); DIN MIDI in kept.
Needs ARDUINO_USB_MODE=0 (USB-OTG/TinyUSB) — set in platformio.ini.
- EEPROM is flash-emulated on ESP32: begin() + commit() required.π
*/
#include <Arduino.h>
// ------- Mozzi configuration: must come before any Mozzi include -------
#include <MozziConfigValues.h>
#define MOZZI_AUDIO_MODE MOZZI_OUTPUT_I2S_DAC
#define MOZZI_AUDIO_BITS 16
#define MOZZI_AUDIO_CHANNELS MOZZI_STEREO // stereo out: dry stays centred, reverb is widened
#define MOZZI_I2S_PIN_BCK 10
#define MOZZI_I2S_PIN_WS 8
#define MOZZI_I2S_PIN_DATA 9
// (note: tried MOZZI_AUDIO_RATE 65536 to push Nyquist up for less FM aliasing,
// but Oscil's UPDATE_RATE template parameter is uint16_t, so 32768 is Mozzi's hard
// cap. 44100 is also out: MOZZI_CHECK_POW2 rejects non-power-of-2 rates.)
#define MOZZI_CONTROL_RATE 256 // powers of 2 please. 256 halves the MIDI-scan wait
// (~3.9ms) vs 128; seq tempo maths below are scaled to match
// Latency fix: Mozzi creates its I2S channel with IDF's stock
// I2S_CHANNEL_DEFAULT_CONFIG = 6 DMA buffers x 240 frames = 1440 samples,
// i.e. ~44ms of output latency at 32768Hz. Mozzi's implementation is
// header-compiled into this very translation unit (MozziGuts.h includes
// internal/MozziGuts.hpp), so redefining the macro here before <Mozzi.h>
// is enough. 4 x 64 = 256 samples ~= 8ms at 32768Hz. Field list must match
// the IDF original in driver/i2s_common.h exactly.
#include <driver/i2s_common.h>
#undef I2S_CHANNEL_DEFAULT_CONFIG
#define I2S_CHANNEL_DEFAULT_CONFIG(i2s_num, i2s_role) { \
.id = i2s_num, \
.role = i2s_role, \
.dma_desc_num = 4, \
.dma_frame_num = 64, \
.auto_clear_after_cb = false, \
.auto_clear_before_cb = false, \
.intr_priority = 0, \
}
#include <Mozzi.h>
#include <Oscil.h>
#include <mozzi_midi.h>
#include <ADSR.h>
#include <ResonantFilter.h> // LowPassFilter lives here in Mozzi 2.x
#include <mozzi_rand.h>
#include <mozzi_fixmath.h>
#include <Line.h>
#include <EEPROM.h>
#include <MIDI.h>
#include <USB.h>
#include <USBMIDI.h>
#include "esp32-hal-tinyusb.h" // usb_persist_restart(): reboot into the ROM bootloader
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// TABLES
#include <tables/sin1024_int8.h> // sine for oscillator
#include <tables/saw2048_int8.h> // saw table for oscillator
#include <tables/triangle2048_int8.h> // triangle table for oscillator
#include <tables/square_analogue512_int8.h> // square table for oscillator
#include <tables/sin512_int8.h> // lofi sine for LFO
#include "Freeverb.h" // needs MOZZI_AUDIO_RATE, so must come after Mozzi.h
#include "CCLOGO_bitmap.h" // Captain Credible logo, shown before the gateXtal splash
// ------- PINS -------
#define PIN_ARCADE 43
#define PIN_MIDI_RX 44
#define PIN_OLED_SDA 7
#define PIN_OLED_SCL 6
#define OLED_ADDR 0x3C
Adafruit_SSD1306 oled(128, 64, &Wire, -1);
int BUTTONS[4] = { 11, 12, 13, 1 }; // index -> GPIO
#define BTN_A 0 // pin 11
#define BTN_B 1 // pin 12
#define BTN_SHIFT 2 // pin 13 — held = alt knob functions
#define BTN_PAGE 3 // pin 1 — cycles pages
int KNOBS[4] = { 2, 3, 4, 5 };
#define FMknob 0
#define h4xxKnob 1
#define attackKnob 2
#define releaseKnob 3
// ------- EEPROM layout (flash-emulated) -------
#define EEPROM_SIZE 2560 // 10 sound presets + 4 sequencer-setup slots
// bytes 0..259 held the old single-sequence dump; abandoned by the sequencer
// revamp but left reserved so the preset slots above keep their addresses
#define EE_PRESET_ADDR 260 // preset slots live above the sequence
#define EE_PRESET_STRIDE 96 // bytes per slot (struct is ~72, rounded up for future fields)
#define NUM_PRESETS 10 // 260 + 10*96 = 1220, fits EEPROM_SIZE with room to spare
#define PRESET_MAGIC 0x48 // bumped when the struct layout changes: old presets read as empty
struct Preset { // everything that makes the sound; saved/loaded on the SET page
byte magic;
byte carWave, modWave;
byte lpfCutoff, lpfRes;
byte mod_ratio;
byte lfoDest, lfoWaveSelect;
byte bitDepth; // 1 = extreme crush .. 16 = full resolution
byte env2FM, env2Filt, env2Ratio; // ENV2 routing amounts (FM / filter / ratio)
byte polyFilt; // 0 = PARA (one filter on the sum), 1 = POLY (filter per voice)
int32_t fmIntensity;
int16_t attack, decay, sustain, release; // ENV1 (amp)
int16_t e2Attack, e2Decay, e2Sustain, e2Release; // ENV2 (mod)
float lfoRate, modDepth;
float rvSize, rvDamp, rvMix;
float oscVol, limThresh;
float rvSpread; // reverb stereo width
byte polyphony; // 1..8 max simultaneous voices
uint16_t srDiv; // sample-rate reduction divisor, 1 (32768Hz) .. MAX_SR_DIV (256 = 128Hz)
};
static_assert(sizeof(Preset) <= EE_PRESET_STRIDE, "Preset struct outgrew its EEPROM slot");
// ------- SEQUENCER STATE -------
// Two monophonic note sequencers (A/B, both always playing) plus a transpose
// sequencer stepping semitone offsets over them. Each has two switchable
// parts; part changes queue until the sequence wraps. One global scale/tempo.
#define SEQ_MAX_STEPS 32
#define NUM_NOTE_SEQS 2
#define NUM_SCALES 5
#define SEQ_BASE_NOTE 36 // scale degree 1 at octave 0 = C2
const byte SEQ_DIVS[5] = { 1, 3, 4, 6, 8 }; // per-seq clock divider (SHIFT+K3)
// note step encoding, packed in one byte for EEPROM friendliness:
// low nibble 0 = rest, 1..12 = scale degree, 13 = tie; high nibble = octave 0..4
#define STEP_REST 0
#define STEP_TIE 13
// each scale is 12 knob positions worth of semitone offsets from the root
// (they span 1.5-3 octaves, so degree order = the note lists in the spec)
const int8_t SCALES[NUM_SCALES][12] = {
{ 0, 3, 7, 9,10,12,15,19,21,22,24,27 }, // Minor C D# G A A# C2 D#2 G2 A2 A#2 C3 D#3
{ 0, 4, 7,11,12,16,19,23,24,28,31,35 }, // Major C E G B C2 E2 G2 B2 C3 E3 G3 B3
{ 0, 1, 4, 5, 6, 9,10,12,13,16,17,18 }, // Oriental C C# E F F# A A# C2 C#2 E2 F2 F#2
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11 }, // Chromatic
{ 0, 3, 5, 7,10,12,15,17,19,22,24,27 }, // Pentatonic C D# F G A# C2 D#2 F2 G2 A#2 C3 D#3
};
const char* SCALE_NAMES[NUM_SCALES] = { "MINOR", "MAJOR", "ORIENT", "CHROM", "PENTA" };
struct NotePart { byte steps[SEQ_MAX_STEPS]; byte length; }; // length 4..32
struct TransPart { int8_t steps[SEQ_MAX_STEPS]; byte length; }; // semitones -12..+12
struct NoteSeq {
NotePart part[2];
byte curPart = 0, pendingPart = 0; // pendingPart applied when playStep wraps to 0
byte gatePct = 60; // gate 0..100% of a step (SHIFT+K1), global per sequencer
byte divIdx = 0; // index into SEQ_DIVS (SHIFT+K3)
byte playStep = 0, editStep = 0; // playhead / knob-4 edit cursor
byte divCount = 0; // global steps until this seq advances again
int8_t soundingVoice = -1; // voice index sounding our note, -1 = none
byte soundingNote = 0; // the MIDI note that voice is playing (steal guard)
unsigned int gateTicks = 0; // control ticks until gate-off; 0 = idle or held into a tie
};
struct TransSeq {
TransPart part[2];
byte curPart = 0, pendingPart = 0;
byte divIdx = 0; // divides the 1-per-16-global-steps base rate further
byte playStep = 0, editStep = 0;
byte divCount = 0; // global steps until the next transpose step (mod 16*div)
int8_t curVal = 0; // transpose currently applied to both note seqs
};
NoteSeq noteSeqs[NUM_NOTE_SEQS];
TransSeq transSeq;
byte selSeq = 0; // editing focus (button A cycles): 0 = A, 1 = B, 2 = transpose
byte scaleIdx = 0; // global scale (SHIFT+K2)
unsigned int bpm = 120; // global tempo (K3), 40..240; steps are 16ths
uint32_t clockAcc = 0; // 8.8 fixed-point control-tick accumulator for the step clock
bool seqPlaying = false; // transport: SHIFT+arcade toggles, MIDI start/stop follows.
// boots stopped
bool midiClockRunning = false; // external MIDI clock overrides the internal one
unsigned long lastMidiTickMs = 0; // for the clock timeout in handleSequencer()
byte midiClockTicks = 0; // 0..5, 24ppqn = 6 ticks per 16th step
NotePart noteClip; bool noteClipValid = false; // SHIFT+A/B copy/paste clipboards,
TransPart transClip; bool transClipValid = false; // one per part type so paste can't mix them
// ------- sequencer-setup slots (SET page, SHIFT+A/B) -------
#define EE_SEQSET_ADDR 1280 // above the preset slots (260 + 10*96 = 1220)
#define EE_SEQSET_STRIDE 320
#define NUM_SEQ_SLOTS 4
#define SEQSET_MAGIC 0x53 // bumped when the struct layout changes
struct SeqSetup { // the entire sequencer state worth persisting, flat POD
byte magic;
NotePart noteParts[NUM_NOTE_SEQS][2];
byte curPart[NUM_NOTE_SEQS];
byte gatePct[NUM_NOTE_SEQS];
byte divIdx[NUM_NOTE_SEQS];
TransPart transParts[2];
byte transCurPart;
byte transDivIdx;
byte scale;
uint16_t tempo;
};
static_assert(sizeof(SeqSetup) <= EE_SEQSET_STRIDE, "SeqSetup outgrew its EEPROM slot");
static_assert(EE_SEQSET_ADDR + NUM_SEQ_SLOTS * EE_SEQSET_STRIDE <= EEPROM_SIZE, "seq slots past EEPROM end");
bool seqSlotUsed[NUM_SEQ_SLOTS] = { false }; // which slots hold a setup (scanned at boot)
// ------- PERFORM page state -------
// knobs 3/4 play scale notes live (like the sequencer's step preview) without
// touching any stored steps; knobs 1/2 mirror MAIN's FM/RATIO and CUT/RES
byte perfDeg = 0; // 0 = silent, 1..12 = scale degree being played (K3)
byte perfOct = 2; // octave 0..4 (K4)
byte perfGatePct = 50; // SHIFT+K3: performed-note length (~50ms..2s)
bool perfHold = false; // K3 at max: sustain until the knob moves away
int8_t perfVoice = -1; // voice we lit up, -1 = none
byte perfNote = 0; // MIDI note that voice is playing (steal guard)
unsigned int perfGateTicks = 0; // control ticks left before the note gates off
Line <Q16n16> aInterpolate;
int mozziRaw[4] = { 0,0,0,0 };
int oldMozziRaw[4] = { 0,0,0,0 };
bool buttStates[4] = { false, false, false, false };
bool oldButtStates[4] = { false, false, false, false };
bool ArcadeState = false;
bool oldArcadeState = false;
bool noteIsOn = false; // keep track of number of playing notes
byte pageState = 0;
// page order (the PAGE button cycles these). Reorder the whole UI by renumbering
// here — every switch/if below keys off these names, not raw case numbers.
enum Page { PG_MAIN = 0, PG_ENV, PG_LFO, PG_VERB, PG_HAXX, PG_SEQ, PG_PERF, PG_COUNT };
int8_t lfoOutput = 0; // value to store current offset from root
int mod_ratio = 3;
// ceiling for mod_ratio (MAIN/PERF SHIFT+K1) and the ratioNow it feeds into below.
// Was hardwired to 15 (-> an 8x max FM multiplier, see ratioNow in updateControl);
// raise this to unlock steeper ratios. No UI control for it on purpose — it's a
// source-level tuning knob, edit and reflash to try a new ceiling.
byte maxRatio = 32;
long fm_intensity = 0;
byte waveformselect = 0;
byte lastNote = 0;
float modDepth = 0;
float freeq = 0;
bool offsetOn = false;
byte lfoDest = 0;
byte lpfCutoff = 100;
byte lfoMode = 0; // LFO shape (A cycles): 0 = sine..saw morph,
// 1 = RND (slewed random), 2 = STAT (silence + crackle)
int statVal = 128; // STAT mode running level, 0..255 (128 = centre/silence)
unsigned long rndTimer = 0;
long int rndFreq = 0;
Q16n16 HDlfoOutputBuffer = 0; // this is a big type for slew manipulation
bool knobLock[4] = { true, true, true, true };
int lockAnchor[4] = { -99,-99,-99,-99 };
int lockThresh = 50;
float knobSmooth[4] = { 0, 0, 0, 0 }; // adaptive-EMA state for the pot filter, in raw ADC units
// shadow copies for the OLED of settings that otherwise only live inside the
// Mozzi objects (initialised to the values set in setup())
int dispAttack = 100, dispDecay = 200, dispSustain = 240, dispRelease = 200;
float lfoRate = 1;
byte lpfRes = 200;
byte carWave = 0, modWave = 0;
MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, MIDI);
USBMIDI usbMIDI; // native USB-MIDI (global: registers the TinyUSB interface early)
USBCDC SerialCDC(0); // USB serial port for debugging + upload auto-reset
// (the core's USBSerial global only exists with CDC_ON_BOOT=1,
// which we avoid so USB.productName() can apply)
// ------- VOICES (up to 8-voice polyphony, one shared LFO) -------
// NUM_VOICES is the hard array size; `polyphony` (H4XX page knob 1, 1..NUM_VOICES)
// is the runtime limit — allocVoice()/allocVoiceFree() only ever pick voices below
// it, so idle voices above the limit just sit there costing nothing (updateAudio's
// per-voice loop already skips any voice that isn't active/releasing).
#define NUM_VOICES 8
byte polyphony = 4; // default matches the original 4-voice build
struct Voice {
Oscil <SIN1024_NUM_CELLS, MOZZI_AUDIO_RATE> car{ SIN1024_DATA }; // carrier
Oscil <SIN1024_NUM_CELLS, MOZZI_AUDIO_RATE> mod{ SIN1024_DATA }; // FM modulator
ADSR <MOZZI_CONTROL_RATE, MOZZI_AUDIO_RATE> env; // amp envelope (ENV1)
ADSR <MOZZI_CONTROL_RATE, MOZZI_CONTROL_RATE> env2; // mod envelope (ENV2), per note
LowPassFilter16 lpf; // own filter, used in POLY filter mode
byte note = 0; // MIDI note this voice is sounding (as received, pre-transpose)
bool active = false; // gate: noteOn seen, no noteOff yet (env may still be releasing)
float freq = 0; // base carrier freq incl. oct transpose
unsigned long age = 0; // allocation order, for voice stealing
long fmNow = 0; // fm_intensity + this voice's ENV2 FM contribution
};
Voice voices[NUM_VOICES];
unsigned long voiceAge = 0;
Oscil <SIN512_NUM_CELLS, MOZZI_CONTROL_RATE> LFO(SIN512_DATA); // one LFO shared by all voices
LowPassFilter16 lpf; // the shared filter, used in PARA filter mode (16-bit variant so it
// doesn't crush the wide path; lpfCutoff/lpfRes stay 0-255, applied <<8)
bool polyFilter = false; // VERB page knob 4: PARA = one filter on the sum (classic paraphonic
// squelch), POLY = each voice through its own filter (per-note plucks)
Freeverb reverb; // ~37KB of delay lines, lives in .bss
float rvSize = 0.72f, rvDamp = 0.45f; // VERB page values (defaults match Freeverb ctor)
float rvMix = 0.5f; // VERB page knob 3: single wet/dry crossfade (dry full below center, wet full above)
float rvSpread = 1.0f; // VERB page knob 4: reverb stereo width (0 = mono, 1 = natural, up to 8 = absurd)
float dryNow = 1.0f; // effective dry gain this tick, from the rvMix law
float wetBase = 1.0f; // base reverb input gain, from the rvMix law (ENV2 sends ride on top)
// ENV2: per-voice modulation envelope, triggered/released with each voice's own gate.
// Edited on the ENV page via B2 (all voices in lockstep, like ENV1); B3 opens the
// routing view where the knobs set the four destination amounts.
byte envSelect = 0; // ENV page: 0 = knobs edit ENV1 (amp), 1 = knobs edit ENV2
bool envRouteView = false; // ENV page: B3 toggles the ENV2 routing view
byte env2FM = 0, env2Filt = 0, env2Ratio = 0; // routing amounts, 0-255 (reverb send removed)
int e2Attack = 100, e2Decay = 200, e2Sustain = 240, e2Release = 200; // OLED shadows for ENV2
// H4XX page: bit-depth crush (1 = extreme .. 16 = full resolution, knob left->right)
// and a sample-rate reducer (decimator — see updateAudio), both lo-fi output effects
// rather than real DAC/ADC reconfiguration: Mozzi's audio rate is a compile-time
// constant baked into every Oscil's phase math, so it can't change at runtime.
// Decimating the finished output (holding samples for `sampleRateDiv` ticks) is the
// standard way synths fake a lower rate — same aliased, gritty result a real rate
// change would give, and unlike the old power-of-two-only version any integer
// divisor works, so every intermediate rate is reachable, not just octave steps.
byte bitDepth = 16;
#define MAX_SR_DIV 256 // knob's far left = 32768/256 = 128Hz
#define SR_DEADZONE 102 // ~10% of travel at the knob's far right,
// pinned to divisor 1 (32768Hz, uncrushed)
unsigned int sampleRateDiv = 1;
// output stage (post reverb mix): peak limiter into a tanh-shaped saturator.
// Single notes pass untouched, stacked voices get transparently ducked, and
// whatever is driven past that bends smoothly instead of clipping hard.
float limEnv = 0; // peak envelope follower
float limGain = 1.0f; // smoothed applied gain (slewn so it never steps audibly)
uint16_t limHold = 0; // samples left of peak hold before the release starts
float limThresh = 44000.0f; // limit level (SET page knob 4), of the ±65536 output range
float oscVol = 1.0f; // pre-filter voice-mix gain (SET page knob 3): >1 = drive
#define LIM_RELEASE 0.99969f // per-sample release: falls to 37% in ~100ms at 32768Hz
#define LIM_HOLD 512 // ~15ms peak hold: stops the envelope rippling (and thus
// distorting) at the note's own frequency between wave peaks
#define LIM_GAIN_SLEW 0.03f // ~1ms gain smoothing: no per-sample gain jumps on attack
// (softClip below bends the brief overshoot while it settles)
byte presetMsg = 0; // 1 = saved, 2 = loaded, 3 = no preset found
unsigned long presetMsgUntil = 0; // OLED shows the message until this millis()
byte presetSelMode = 0; // 0 = closed, 1/2 = preset save/load slot picker,
// 3/4 = sequencer-setup save/load slot picker
byte presetSelSlot = 0; // slot the selector is pointing at
bool presetUsed[NUM_PRESETS] = { false }; // which slots hold a patch (scanned at boot)
// ------- forward declarations (this is a .cpp, no .ino magic prototypes) -------
void HandleNoteOn(byte note, byte velocity);
void HandleNoteOff(byte note, byte velocity);
void seqNoteOn(NoteSeq& s, byte midiNote);
void seqNoteOff(NoteSeq& s);
void seqAllNotesOff();
void perfPlay();
void perfNoteOff();
void doGlobalStep();
void resetAllSeqs();
void auditionStep(byte i);
void seqCheckButts();
void handleSequencer();
void saveSeqSetup(byte slot);
bool loadSeqSetup(byte slot);
void initSeqDefaults();
void lockKnobs();
///////////////////////
// VOICE / MIDI HANDLING
///////////////////////
// Note/MIDI activity light on the SuperMini's onboard neopixel (GPIO48).
// rgbLedWrite() drives it via RMT, same as digitalWrite(LED_BUILTIN) in the
// Arduino IDE; RGB_BUILTIN comes from the esp32s3 board variant.
void writeNoteLED(byte note) { // color the LED by the pressed note's pitch class:
// red (C) ramping through orange to yellow (B),
// one full red->yellow sweep per octave
#ifdef RGB_BUILTIN
byte g = (uint16_t)(note % 12) * RGB_BRIGHTNESS / 11; // green rises 0..full
rgbLedWrite(RGB_BUILTIN, RGB_BRIGHTNESS, g, 0);
#endif
}
void writeLED(bool state) { // used for note-off (green kept for any non-note use)
#ifdef RGB_BUILTIN
rgbLedWrite(RGB_BUILTIN, 0, state ? RGB_BRIGHTNESS : 0, 0);
#endif
}
Voice* allocVoiceFree() { // pick a voice without note-matching (sequencers use this
// directly so two seqs on the same pitch never share a voice)
// only ever hand out voices within the current polyphony limit — voices above
// it stay silent (any note already ringing there just finishes on its own)
byte n = polyphony;
// a completely idle voice (envelope finished)
for (int i = 0; i < n; i++) {
if (!voices[i].active && !voices[i].env.playing()) return &voices[i];
}
// otherwise the oldest released-but-still-ringing tail
Voice* best = NULL;
for (int i = 0; i < n; i++) {
if (!voices[i].active && (!best || voices[i].age < best->age)) best = &voices[i];
}
if (best) return best;
// every voice in the limit is gated: steal the oldest
best = &voices[0];
for (int i = 1; i < n; i++) {
if (voices[i].age < best->age) best = &voices[i];
}
return best;
}
Voice* allocVoice(byte note) {
// same note still sounding: retrigger that voice instead of doubling it
for (int i = 0; i < polyphony; i++) {
if (voices[i].active && voices[i].note == note) return &voices[i];
}
return allocVoiceFree();
}
void HandleNoteOn(byte note, byte velocity) {
if (note != 0) { // if not zero
Voice* v = allocVoice(note);
v->note = note;
v->active = true;
v->age = ++voiceAge;
v->freq = mtof(float(note));
v->car.setFreq(v->freq);
v->env.noteOn();
v->env2.noteOn(); // this voice's own mod envelope
noteIsOn = true;
writeNoteLED(note);
lastNote = note;
}
}
void HandleNoteOff(byte note, byte velocity) {
bool anyHeld = false;
for (int i = 0; i < NUM_VOICES; i++) {
if (voices[i].active && voices[i].note == note) {
voices[i].active = false;
voices[i].env.noteOff();
voices[i].env2.noteOff(); // both envelopes follow this voice's gate
}
anyHeld |= voices[i].active;
}
noteIsOn = anyHeld;
if (!anyHeld) writeLED(false);
}
// --- SysEx protocol -------------------------------------------------------
// All GateXtal SysEx shares the header F0 7D 47 58 <cmd> ... F7
// 7D = the educational / non-commercial manufacturer ID
// 47 58 = "GX"
// <cmd> = one ASCII byte selecting the operation:
// 'B' 0x42 reboot to bootloader F0 7D 47 58 42 F7 (host->dev)
// 'D' 0x44 dump request F0 7D 47 58 44 <slot> F7 (host->dev)
// slot 0..9 dumps that slot; 0x7F dumps every used slot.
// 'P' 0x50 preset payload F0 7D 47 58 50 <slot> <nibbles..> F7
// sent by the device in reply to a dump, or by the host to
// store a preset into a slot. The Preset struct is carried
// low-nibble-first: each raw byte becomes two 4-bit data
// bytes so everything stays inside SysEx's 7-bit limit.
const byte GX_ID0 = 0x7D, GX_ID1 = 0x47, GX_ID2 = 0x58;
#define GX_CMD_BOOT 0x42
#define GX_CMD_DUMPREQ 0x44
#define GX_CMD_PRESET 0x50
#define GX_DUMP_ALL 0x7F
// backwards-compatible name for the old 6-byte bootloader magic
const byte BOOT_SYSEX[6] = { 0xF0, GX_ID0, GX_ID1, GX_ID2, GX_CMD_BOOT, 0xF7 };
void rebootToBootloader() {
usb_persist_restart(RESTART_BOOTLOADER); // keeps USB alive across the reboot
}
// Send a raw SysEx byte stream (F0..F7) out over USB-MIDI, packed into the
// standard 4-byte USB-MIDI packets (CIN 4 = mid-stream, 5/6/7 = final 1/2/3
// bytes). Spins briefly if the TinyUSB FIFO is full rather than dropping data.
void sendSysExOut(const byte* d, int len) {
int i = 0;
while (i < len) {
int rem = len - i;
midiEventPacket_t p = { 0, 0, 0, 0 };
if (rem > 3) { p.header = 0x04; p.byte1 = d[i]; p.byte2 = d[i + 1]; p.byte3 = d[i + 2]; i += 3; }
else if (rem == 3) { p.header = 0x07; p.byte1 = d[i]; p.byte2 = d[i + 1]; p.byte3 = d[i + 2]; i += 3; }
else if (rem == 2) { p.header = 0x06; p.byte1 = d[i]; p.byte2 = d[i + 1]; i += 2; }
else { p.header = 0x05; p.byte1 = d[i]; i += 1; }
for (int tries = 0; !usbMIDI.writePacket(&p) && tries < 20000; tries++) delayMicroseconds(50);
}
}
// Read slot `slot` from EEPROM and, if it holds a patch, dump it as a 'P'
// message. Empty slots are silently skipped.
void dumpPreset(byte slot) {
if (slot >= NUM_PRESETS) return;
Preset p;
EEPROM.get(EE_PRESET_ADDR + slot * EE_PRESET_STRIDE, p);
if (p.magic != PRESET_MAGIC) return; // nothing saved in this slot
const byte* raw = (const byte*)&p;
byte out[7 + 2 * sizeof(Preset)];
int n = 0;
out[n++] = 0xF0; out[n++] = GX_ID0; out[n++] = GX_ID1; out[n++] = GX_ID2;
out[n++] = GX_CMD_PRESET; out[n++] = slot;
for (size_t k = 0; k < sizeof(Preset); k++) {
out[n++] = raw[k] & 0x0F;
out[n++] = (raw[k] >> 4) & 0x0F;
}
out[n++] = 0xF7;
sendSysExOut(out, n);
}
// Decode a 'P' message and store the carried preset into its slot. Rejects
// wrong sizes / bad magic so a truncated or foreign SysEx can't corrupt a slot.
void storePresetFromSysEx(const byte* buf, int len) {
byte slot = buf[5];
if (slot >= NUM_PRESETS) return;
int nib = len - 7; // strip F0 + 3 ID + cmd + slot + F7
if (nib != (int)(2 * sizeof(Preset))) return;
Preset p;
byte* raw = (byte*)&p;
for (size_t k = 0; k < sizeof(Preset); k++) {
raw[k] = (buf[6 + 2 * k] & 0x0F) | ((buf[6 + 2 * k + 1] & 0x0F) << 4);
}
if (p.magic != PRESET_MAGIC) return; // not one of ours / stale layout
EEPROM.put(EE_PRESET_ADDR + slot * EE_PRESET_STRIDE, p);
EEPROM.commit();
presetUsed[slot] = true;
presetMsg = 4; // "SYSEX RX" footer hint
presetMsgUntil = millis() + 1200;
}
// Dispatch a complete SysEx message (framing included) to the right handler.
void handleSysExMessage(const byte* buf, int len) {
if (len == sizeof(BOOT_SYSEX) && memcmp(buf, BOOT_SYSEX, len) == 0) {
rebootToBootloader();
return;
}
if (len < 6) return;
if (buf[0] != 0xF0 || buf[1] != GX_ID0 || buf[2] != GX_ID1 || buf[3] != GX_ID2) return;
switch (buf[4]) {
case GX_CMD_DUMPREQ:
if (buf[5] == GX_DUMP_ALL) { for (byte s = 0; s < NUM_PRESETS; s++) dumpPreset(s); }
else dumpPreset(buf[5]);
break;
case GX_CMD_PRESET:
storePresetFromSysEx(buf, len);
break;
}
}
byte syxBuf[208]; // header(6) + slot + 2*sizeof(Preset) nibbles + F7, with headroom
byte syxLen = 0;
void syxByte(byte b) { // feed one byte of a USB-MIDI SysEx stream
if (b == 0xF0) syxLen = 0; // message start
if (syxLen < sizeof(syxBuf)) syxBuf[syxLen++] = b;
if (b == 0xF7) { // message end: dispatch what we buffered
handleSysExMessage(syxBuf, syxLen);
syxLen = 0;
}
}
void HandleDINSysEx(byte* data, unsigned length) { // includes the F0/F7 framing
handleSysExMessage(data, (int)length);
}
// ---------------------------------------------------------------------------
void HandleDINNoteOn(byte channel, byte note, byte velocity) {
HandleNoteOn(note, velocity);
}
void HandleDINNoteOff(byte channel, byte note, byte velocity) {
HandleNoteOff(note, velocity);
}
void handleMidiClockTicks() { // 24ppqn: every 6th tick is one global 16th step
midiClockRunning = true; // external clock present: it owns the step timing now
lastMidiTickMs = millis();
if (midiClockTicks == 0 && seqPlaying) doGlobalStep(); // transport still gates playback
midiClockTicks = (midiClockTicks + 1) % 6;
}
void externalClockStart() { // MIDI start/continue: play from the top
seqPlaying = true;
resetAllSeqs();
}
void externalClockStop() {
midiClockRunning = false;
seqPlaying = false;
seqAllNotesOff();
}
void handleMIDIClock() { handleMidiClockTicks(); }
void handleMIDIClockStart() { externalClockStart(); }
void handleMIDIClockStop() { externalClockStop(); }
void usbmidiprocessing() {
midiEventPacket_t e;
while (usbMIDI.readPacket(&e)) {
byte cin = e.header & 0x0F; // code index number, same as the old MIDIUSB e.type
// NOTE ON WITH VELOCITY GREATER THAN ZERO
if (cin == 0x09 && e.byte3 > 0) {
HandleNoteOn(e.byte2, e.byte3);
}
// USB NOTE OFF (real note-off or running-status note-on with velocity 0)
else if (cin == 0x08 || (cin == 0x09 && e.byte3 == 0)) {
HandleNoteOff(e.byte2, e.byte3);
}
// sysex stream: CIN 4 = continue (3 bytes), 5/6/7 = end with 1/2/3 bytes
else if (cin >= 0x04 && cin <= 0x07) {
byte n = (cin == 0x05) ? 1 : (cin == 0x06) ? 2 : 3;
syxByte(e.byte1);
if (n >= 2) syxByte(e.byte2);
if (n >= 3) syxByte(e.byte3);
}
// single-byte system realtime: clock / start / continue / stop
else if (cin == 0x0F) {
if (e.byte1 == 0xF8) { // clock tick
handleMidiClockTicks();
}
else if (e.byte1 == 0xFA || e.byte1 == 0xFB) { // start / continue
externalClockStart();
}
else if (e.byte1 == 0xFC) { // stop
externalClockStop();
}
}
}
}
///////////////////////
// SEQUENCER
///////////////////////
static inline byte stepDeg(byte st) { return st & 0x0F; }
static inline byte stepOct(byte st) { return (st >> 4) & 0x07; }
// scale lookup + per-step octave + the transpose sequencer's running offset
// (scale applied before transposition, as per the spec)
byte stepMidiNote(byte st) {
int n = SEQ_BASE_NOTE + SCALES[scaleIdx][(stepDeg(st) - 1) % 12]
+ 12 * stepOct(st) + transSeq.curVal;
return (byte)constrain(n, 0, 127);
}
// sequencer notes bypass HandleNoteOn/Off: two sequencers may sit on the same
// pitch, and the plain note-off path kills *every* voice holding that note.
// Each sequencer instead remembers exactly which voice it lit up.
void seqNoteOn(NoteSeq& s, byte midiNote) {
Voice* v = allocVoiceFree();
v->note = midiNote;
v->active = true;
v->age = ++voiceAge;
v->freq = mtof(float(midiNote));
v->car.setFreq(v->freq);
v->env.noteOn();
v->env2.noteOn();
noteIsOn = true;
writeNoteLED(midiNote);
s.soundingVoice = (int8_t)(v - voices);
s.soundingNote = midiNote;
}
void seqNoteOff(NoteSeq& s) {
if (s.soundingVoice < 0) return;
Voice& v = voices[s.soundingVoice];
if (v.active && v.note == s.soundingNote) { // still ours (not stolen meanwhile)
v.active = false;
v.env.noteOff();
v.env2.noteOff();
}
s.soundingVoice = -1;
bool anyHeld = false;
for (int i = 0; i < NUM_VOICES; i++) anyHeld |= voices[i].active;
noteIsOn = anyHeld;
if (!anyHeld) writeLED(false);
}
void seqAllNotesOff() { // stop/reset: silence both note sequencers' gates
for (byte i = 0; i < NUM_NOTE_SEQS; i++) {
seqNoteOff(noteSeqs[i]);
noteSeqs[i].gateTicks = 0;
}
}
// PERFORM page notes: same scale/pitch pipeline as the sequencer preview, but
// through their own tracked voice so they never cut a sequencer's note off.
void perfNoteOff() {
if (perfVoice < 0) return;
Voice& v = voices[perfVoice];
if (v.active && v.note == perfNote) { // still ours (not stolen meanwhile)
v.active = false;
v.env.noteOff();
v.env2.noteOff();
}
perfVoice = -1;
bool anyHeld = false;
for (int i = 0; i < NUM_VOICES; i++) anyHeld |= voices[i].active;
noteIsOn = anyHeld;
if (!anyHeld) writeLED(false);
}
void perfPlay() { // (re)trigger the performed note from perfDeg/perfOct
if (!perfDeg) return;
perfNoteOff();
int n = SEQ_BASE_NOTE + SCALES[scaleIdx][(perfDeg - 1) % 12]
+ 12 * perfOct + transSeq.curVal; // rides the transpose seq like everything else
byte note = (byte)constrain(n, 0, 127);
Voice* v = allocVoiceFree();
v->note = note;
v->active = true;
v->age = ++voiceAge;
v->freq = mtof(float(note));
v->car.setFreq(v->freq);
v->env.noteOn();
v->env2.noteOn();
noteIsOn = true;
writeNoteLED(note);
perfVoice = (int8_t)(v - voices);
perfNote = note;
perfGateTicks = perfHold ? 0 : (12 + (unsigned int)perfGatePct * 5); // ~50ms..2s
}
static inline uint32_t stepTicksFP() { // control ticks per global 16th step, 8.8 fixed
return (3840UL << 8) / bpm; // 3840 = 60s * CONTROL_RATE / 4 steps-per-beat
}
unsigned int gateLenTicks(NoteSeq& s) { // gatePct% of this sequencer's own step period
unsigned int full = (unsigned int)((stepTicksFP() * SEQ_DIVS[s.divIdx]) >> 8);
unsigned int g = (unsigned int)((uint32_t)full * s.gatePct / 100);
if (g < 1) g = 1;
if (g > full) g = full;
return g;
}
bool nextStepIsTie(NoteSeq& s) { // look-ahead so a note can hold into a tie
byte next = s.playStep + 1;
byte part = s.curPart;
if (next >= s.part[part].length) { next = 0; part = s.pendingPart; }
return stepDeg(s.part[part].steps[next]) == STEP_TIE;
}
void seqAdvance(NoteSeq& s) {
s.playStep++;
if (s.playStep >= s.part[s.curPart].length) {
s.playStep = 0;
s.curPart = s.pendingPart; // queued part switch lands on the wrap
}
byte st = s.part[s.curPart].steps[s.playStep];
byte deg = stepDeg(st);
if (deg == STEP_REST) {
seqNoteOff(s);
s.gateTicks = 0;
}
else if (deg == STEP_TIE) {
// extend the running note through this step (a tie after the gate already
// closed, or after a rest, is just more silence). gateTicks 0 = keep holding.
if (s.soundingVoice >= 0) s.gateTicks = nextStepIsTie(s) ? 0 : gateLenTicks(s);
}
else {
seqNoteOff(s); // mono: the previous note ends here whatever its gate had left
seqNoteOn(s, stepMidiNote(st));
s.gateTicks = nextStepIsTie(s) ? 0 : gateLenTicks(s);
}
}
void transAdvance() {
transSeq.playStep++;
if (transSeq.playStep >= transSeq.part[transSeq.curPart].length) {
transSeq.playStep = 0;
transSeq.curPart = transSeq.pendingPart;
}
transSeq.curVal = transSeq.part[transSeq.curPart].steps[transSeq.playStep];
}
void doGlobalStep() { // one global 16th step, from the internal or MIDI clock
// transpose first, so a note landing on the same global step picks up the new
// value. Base rate = one transpose step per 16 global steps, times its divider.
if (transSeq.divCount == 0) transAdvance();
transSeq.divCount = (transSeq.divCount + 1) % (16 * SEQ_DIVS[transSeq.divIdx]);
for (byte i = 0; i < NUM_NOTE_SEQS; i++) {
NoteSeq& s = noteSeqs[i];
if (s.divCount == 0) seqAdvance(s);
s.divCount = (s.divCount + 1) % SEQ_DIVS[s.divIdx];
}
}
void resetAllSeqs() { // arcade button / MIDI start: everything restarts from the top
seqAllNotesOff();
for (byte i = 0; i < NUM_NOTE_SEQS; i++) {
NoteSeq& s = noteSeqs[i];
s.curPart = s.pendingPart;
s.playStep = s.part[s.curPart].length - 1; // first advance lands on step 0
s.divCount = 0;
}
transSeq.curPart = transSeq.pendingPart;
transSeq.playStep = transSeq.part[transSeq.curPart].length - 1;
transSeq.divCount = 0;
midiClockTicks = 0;
clockAcc = stepTicksFP(); // internal clock: fire the first step on the next tick
}
void handleSequencer() { // one call per control tick (256Hz)
// gate countdowns always run (they also time the knob-edit auditions)
for (byte i = 0; i < NUM_NOTE_SEQS; i++) {
NoteSeq& s = noteSeqs[i];
if (s.gateTicks && --s.gateTicks == 0) seqNoteOff(s);
}
if (perfGateTicks && --perfGateTicks == 0) perfNoteOff(); // PERFORM page note
if (midiClockRunning) {
// external clock owns the step timing; steps fire in handleMidiClockTicks().
// No tick for 500ms (a real clock ticks every ~21ms at 120bpm): the source
// is gone, fall back to the internal clock instead of hanging silent.
if (millis() - lastMidiTickMs > 500) {
midiClockRunning = false;
clockAcc = 0;
}
return;
}
if (!seqPlaying) return; // transport stopped: hold position, no stepping
clockAcc += 256; // one control tick in 8.8
uint32_t step = stepTicksFP();
if (clockAcc >= step) {
clockAcc -= step;
if (clockAcc >= step) clockAcc = 0; // tempo cranked up mid-run: no burst catch-up
doGlobalStep();
}
}
void auditionStep(byte i) { // preview the edited step while twiddling knobs 1/2/4
NoteSeq& s = noteSeqs[i];
byte st = s.part[s.curPart].steps[s.editStep];
seqNoteOff(s);
s.gateTicks = 0;
byte deg = stepDeg(st);
if (deg >= 1 && deg <= 12) {
seqNoteOn(s, stepMidiNote(st));
s.gateTicks = 64; // ~250ms preview; the running clock overrides at its next step
}
}
///////////////////////
// SEQUENCER SETUP SLOTS (EEPROM, SET page SHIFT+A/B)
///////////////////////
void saveSeqSetup(byte slot) {
SeqSetup q;
q.magic = SEQSET_MAGIC;
for (byte i = 0; i < NUM_NOTE_SEQS; i++) {
q.noteParts[i][0] = noteSeqs[i].part[0];
q.noteParts[i][1] = noteSeqs[i].part[1];
q.curPart[i] = noteSeqs[i].curPart;
q.gatePct[i] = noteSeqs[i].gatePct;
q.divIdx[i] = noteSeqs[i].divIdx;
}
q.transParts[0] = transSeq.part[0];
q.transParts[1] = transSeq.part[1];
q.transCurPart = transSeq.curPart;
q.transDivIdx = transSeq.divIdx;
q.scale = scaleIdx;
q.tempo = bpm;
EEPROM.put(EE_SEQSET_ADDR + slot * EE_SEQSET_STRIDE, q);
EEPROM.commit(); // flash write: expect a tiny audio hiccup, same as a preset save
seqSlotUsed[slot] = true;
}
bool loadSeqSetup(byte slot) {
SeqSetup q;
EEPROM.get(EE_SEQSET_ADDR + slot * EE_SEQSET_STRIDE, q);
if (q.magic != SEQSET_MAGIC) return false; // nothing saved in this slot yet
for (byte i = 0; i < NUM_NOTE_SEQS; i++) {
NoteSeq& s = noteSeqs[i];
s.part[0] = q.noteParts[i][0];
s.part[1] = q.noteParts[i][1];
s.part[0].length = constrain(s.part[0].length, 4, SEQ_MAX_STEPS);
s.part[1].length = constrain(s.part[1].length, 4, SEQ_MAX_STEPS);
s.curPart = q.curPart[i] & 1;
s.pendingPart = s.curPart;
s.gatePct = q.gatePct[i] > 100 ? 100 : q.gatePct[i];
s.divIdx = q.divIdx[i] % 5;
s.editStep = 0;
}
transSeq.part[0] = q.transParts[0];
transSeq.part[1] = q.transParts[1];
transSeq.part[0].length = constrain(transSeq.part[0].length, 4, SEQ_MAX_STEPS);
transSeq.part[1].length = constrain(transSeq.part[1].length, 4, SEQ_MAX_STEPS);
transSeq.curPart = q.transCurPart & 1;
transSeq.pendingPart = transSeq.curPart;
transSeq.divIdx = q.transDivIdx % 5;
transSeq.editStep = 0;
transSeq.curVal = 0;
scaleIdx = q.scale % NUM_SCALES;
bpm = constrain(q.tempo, 40, 240);
resetAllSeqs(); // resync playheads/counters to the loaded lengths
return true;
}
void initSeqDefaults() { // fresh boot: sane lengths + a small pattern in seq A
for (byte i = 0; i < NUM_NOTE_SEQS; i++) {
for (byte p = 0; p < 2; p++) {
memset(noteSeqs[i].part[p].steps, STEP_REST, SEQ_MAX_STEPS);
noteSeqs[i].part[p].length = 16;
}
}
for (byte p = 0; p < 2; p++) {
memset(transSeq.part[p].steps, 0, SEQ_MAX_STEPS);
transSeq.part[p].length = 4;
}
// seq A part A: a little something so a fresh unit makes sound
static const byte patt[16] = { 1,0,5,STEP_TIE, 3,0,8,0, 1,0,5,STEP_TIE, 3,0,10,8 };
for (byte i = 0; i < 16; i++) {
byte deg = patt[i];
noteSeqs[0].part[0].steps[i] = (deg && deg != STEP_TIE) ? ((1 << 4) | deg) : deg;
}
}
void seqCheckButts() { // SEQ page: A = next sequencer, B = part toggle; +SHIFT = copy/paste
// SHIFT changes what every knob on this page means: re-anchor them on both edges
if (buttStates[BTN_SHIFT] != oldButtStates[BTN_SHIFT]) {
lockKnobs();
oldButtStates[BTN_SHIFT] = buttStates[BTN_SHIFT];
}
if (buttStates[BTN_A] && !oldButtStates[BTN_A]) {
if (buttStates[BTN_SHIFT]) { // copy the current part (typed clipboards)
if (selSeq < NUM_NOTE_SEQS) {
noteClip = noteSeqs[selSeq].part[noteSeqs[selSeq].curPart];
noteClipValid = true;
}
else {
transClip = transSeq.part[transSeq.curPart];
transClipValid = true;
}
}
else {
selSeq = (selSeq + 1) % 3; // A -> B -> transpose -> A
lockKnobs(); // knob positions belong to the previous sequencer
}
}
if (buttStates[BTN_B] && !oldButtStates[BTN_B]) {
if (buttStates[BTN_SHIFT]) { // paste (only onto the same part type)
if (selSeq < NUM_NOTE_SEQS && noteClipValid) {
NoteSeq& s = noteSeqs[selSeq];
s.part[s.curPart] = noteClip;
if (s.editStep >= s.part[s.curPart].length) s.editStep = 0;
}
else if (selSeq == 2 && transClipValid) {
transSeq.part[transSeq.curPart] = transClip;
if (transSeq.editStep >= transSeq.part[transSeq.curPart].length) transSeq.editStep = 0;
}
}
else { // part toggle: instant (playhead carries on in the new part)
if (selSeq < NUM_NOTE_SEQS) {
NoteSeq& s = noteSeqs[selSeq];
s.curPart = !s.curPart;
s.pendingPart = s.curPart;
if (s.editStep >= s.part[s.curPart].length) s.editStep = 0;
}
else {