-
Notifications
You must be signed in to change notification settings - Fork 2
/
OPL3box.ino
610 lines (447 loc) · 15.1 KB
/
OPL3box.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
// OPL3box. Allows to control an OPL3 chip via MIDI using Arduino.
// Copyright (C) 2018, Aleh Dzenisiuk.
//
// This is made for Arduino Pro Micro, so MIDI over USB can be used, but Uno/Nano will work with pin number changes.
#include "MIDIUSB.h"
#include <a21.hpp>
using namespace a21;
/**
* Low level wrapper for an OPL3 chip (YM262).
* Parameters:
* - `dataIO` should be `a21::PinBus<>` grouping 8 data pins of OPL3.
* - the pins should be `a21::FastPin<>` or similar wrapping the control pins.
*/
template<
typename dataIO,
typename pinIC,
typename pinCS, typename pinRD, typename pinWR, typename pinA0, typename pinA1
>
class YM262 {
protected:
static const int delayMultiple = 2;
static inline void _writePulse() {
// Start the write pulse.
pinWR::setLow();
// Write pulse width, Tww = 100ns. Covers the data setup time as well (Twds = 10ns).
_delay_us(delayMultiple * 0.100);
// End of the write pulse.
pinWR::setHigh();
// Write data hold time, Twdh = 20ns. Also covers address hold time (Tah = 10ns). Again, this is too short, but let's keep it.
_delay_us(delayMultiple * 0.020);
}
public:
static void write(uint16_t reg, uint8_t data) {
// Always assuming that the bus is in inactive state.
// Address mode.
pinA0::setLow();
// Select register set 0 or 1.
pinA1::write((reg >> 8) & 1);
// Address setup time, Tas = 10ns. (This is too short, but let's put it here just in case and for documentation.)
_delay_us(delayMultiple * 0.010);
// Chip select. Chip select write width, Tcsw = 100ns will be ensured by the width of the write pulse.
pinCS::setLow();
// Set up the register address. (Write data setup time, Twds=10ns, will be a part of the larger write pulse width.)
dataIO::write(reg);
_writePulse();
// Set up the register data.
dataIO::write(data);
// Switch into the data mode.
pinA0::setHigh();
// Address setup time, Tas = 10ns.
_delay_us(delayMultiple * 0.010);
_writePulse();
}
public:
/** The clock frequency of the chip, Hz. */
static const uint32_t F = 14318180;
static void reset() {
if (!pinIC::unused) {
// We are assuming reset is HIGH now, but if it is LOW for some reason already, then not a problem,
// we'll just keep it it LOW for some more time and then release to complete the reset.
pinIC::setOutput();
pinIC::setLow();
// The minimum reset pulse width is (400 / F) seconds, but we want a bit more just in case.
_delay_ms(16 * 1000L * 400 / F);
// The chip should have its own pull-up to drive the reset signal HIGH, so we could switch to hi-Z here,
// but don't want to rely on it, as it seemed too weak on the scope.
pinIC::setInput(true);
} else {
// IC pin is not attached, let's clean the registers one by one.
// Wipe OPL2 regs first.
for (uint16_t reg = 0x01; reg <= 0xF5; reg++) {
write(reg, 0);
}
// Now OPL3 ones, but need to have OPL3 mode enabled first, the regs are not writable otherwise.
write(0x105, _BV(0));
// Disable 4 operator modes for now.
write(0x104, 0);
// And wipe the test reg just in case.
write(0x101, 0);
for (uint16_t reg = 0x120; reg <= 0x1F5; reg++) {
write(reg, 0);
}
}
}
static void begin() {
dataIO::setOutput();
pinCS::setOutput();
pinCS::setHigh();
pinRD::setOutput();
pinRD::setHigh();
pinWR::setOutput();
pinWR::setHigh();
pinA0::setOutput();
pinA0::setHigh();
pinA1::setOutput();
pinA1::setHigh();
reset();
// Set Waveform Select Enable bit, so Waveform Select registers work.
write(0x01, _BV(5));
// Set the Keyboard Split bit to 1, so Key Scale Number is determined by the block number together with the bit 9 of the f-number (instead of bit 8).
// The Key Scale Numbers are used with Key Scale Rate parameter.
write(0x08, _BV(6));
// Set OPL3 Mode Enable bit, so we are not in OPL2 compatibility mode.
write(0x105, _BV(0));
// Enable 4 operator mode for all possible 6 channels (bits 0-5).
//! write(0x104, 0x3F);
}
protected:
/** Register offset for the given zero-based OPL2 operator index (0-17), i.e. offset for operators within the register set 0. */
static inline uint8_t _offsetForOPL2Operator(uint8_t op) {
if (op < 6)
return op;
else if (op < 12)
return op - 6 + 0x08;
else
return op - 12 + 0x10;
}
public:
/**
* Register offset for the given zero-based OPL3 operator index (0-35).
* This function automatically distiniguishes between register sets 0 and 1, so you can just add
* the returned value to your base register (e.g. 0x80 for sustain/release), and you'll get a register
* suitable for write() function.
*/
static uint16_t offsetForOperator(uint8_t op) {
if (op < 18) {
return _offsetForOPL2Operator(op);
} else {
return 0x100 + _offsetForOPL2Operator(op - 18);
}
}
/**
* Offset for a register corresponding to one of the 18 OPL3 channels (0-17).
* Again, the returned value added to channel's register base (e.g. 0xA0 for f-numbers)
* is directly suitable for write() function.
*/
static uint16_t offsetForChannel(uint8_t channel) {
return (channel < 9) ? channel : 0x100 + channel - 9;
}
union __attribute__((packed)) ChannelSetup {
uint8_t regs[3];
struct __attribute__((packed)) {
// A0+ and B0+
uint16_t fnumber : 10;
uint16_t block : 3;
uint16_t kon : 1;
uint16_t unused : 2;
// C0+
uint8_t cnt : 1;
uint8_t fb : 3;
uint8_t cha : 1;
uint8_t chb : 1;
uint8_t chc : 1;
uint8_t chd : 1;
};
};
static void setChannelFrequency(ChannelSetup& ch, uint16_t freq) {
uint8_t b = 0;
uint32_t f = ((uint32_t)freq << 20) / (F / 288);
while (f >= (1 << 10)) {
f >>= 1;
b++;
}
ch.fnumber = f;
ch.block = b;
}
static void channelKeyOn(uint8_t index, const ChannelSetup& ch) {
uint16_t offset = offsetForChannel(index);
write(0xA0 + offset, ch.regs[0]);
write(0xC0 + offset, ch.regs[2]);
write(0xB0 + offset, ch.regs[1]);
}
static void channelKeyOff(uint8_t index, const ChannelSetup& ch) {
uint16_t offset = offsetForChannel(index);
write(0xB0 + offset, ch.regs[1]);
}
enum Waveform : uint8_t {
WaveformSine = 0,
WaveformHalfSine = 1,
WaveformAbsSine = 2,
WaveformPulseSine = 3
};
union __attribute__((packed)) OperatorSetup {
uint8_t regs[5];
struct __attribute__((packed)) {
// 20+
uint8_t mult : 4; // freq mult
uint8_t ksr : 1; // envelope scaling
uint8_t egt : 1; // sustain
uint8_t vib : 1; // vibrato
uint8_t am : 1; // tremolo
// 40+
uint8_t tl : 6; // output level
uint8_t ksl : 2; // keyboard scale level
// 60+
uint8_t dr : 4;
uint8_t ar : 4;
// 80+
uint8_t rr : 4;
uint8_t sl : 4;
// E0
Waveform waveform; // WS
};
};
static void updateOperator(uint8_t index, const OperatorSetup& op) {
uint16_t offset = offsetForOperator(index);
write(0x20 + offset, op.regs[0]);
write(0x40 + offset, op.regs[1]);
write(0x60 + offset, op.regs[2]);
write(0x80 + offset, op.regs[3]);
write(0xE0 + offset, op.regs[4]);
}
public:
/** Channels in 4 op melodic + percussion mode. */
enum Channel : uint8_t {
ChannelFourOp0,
ChannelFourOp1,
ChannelFourOp2,
ChannelBD,
ChannelSD,
ChannelTT,
ChannelCY,
ChannelHH,
ChannelFourOp3,
ChannelFourOp4,
ChannelFourOp5,
ChannelTwoOp0,
ChannelTwoOp1,
ChannelTwoOp2
};
};
// Instantiating it as OPL3 in this project.
typedef YM262<
PinBus< FastPin<14>, FastPin<10>, FastPin<9>, FastPin<8>, FastPin<7>, FastPin<6>, FastPin<5>, FastPin<4> >, // 8 pins for the data bus bits 0-7.
UnusedPin<>, // IC# (reset), not using it on this board. The pin is connected to GND via a capacitor, so together with a built-in pull-up it will delay reset rising time.
UnusedPin<>, // CS#, always LOW on this board, i.e. the chip is selected.
UnusedPin<>, // RD#, always HIGH on this board, we never read from the chip.
FastPin<15>, // WR#.
FastPin<A1>, // A0 of the chip.
FastPin<A0> // A1 of the chip.
> OPL3;
// On the Pro Micro the debug LED is attached to D5, which is a pin with internal number 30.
// It is also connected to VCC, so the pin level should be LOW in order to light it, thus inversion.
typedef InvertedPin< FastPin<30> > DebugLED;
// We want to use a little OLED screen here and talk to it via I2C.
// TODO: it would be better to use a hardware I2C.
typedef SoftwareI2C<
FastPin<2>, // SCK
FastPin<3>, // SDA
true // If true, then use built-in pull-ups on the pins.
> I2C;
// 128x32 (i.e. 4 "pages" high).
typedef SSD1306<I2C, 4> LCD;
typedef FastPin<A2> encoder1PinA;
typedef FastPin<A3> encoder1PinB;
EC11 encoder1;
typedef FastPin<16> encoderButton;
#include "UI.h"
class OPL3box : protected a21::MIDIParser<OPL3box> {
protected:
friend a21::MIDIParser<OPL3box>;
typedef OPL3box Self;
OPL3::OperatorSetup testOperator1;
OPL3::OperatorSetup testOperator2;
OPL3::ChannelSetup testChannel;
static Self& getSelf() {
static Self self = Self();
return self;
}
/** @{ */
/** MIDI */
// TODO: use a table
static uint16_t frequencyForNote(uint8_t note) {
return (220.0 / 8) * pow(pow(2, 1.0 / 12), (note - 21));
}
void handleNoteOn(uint8_t channel, uint8_t note, uint8_t velocity) {
DebugLED::setHigh();
// Used this to test the channel mask as well.
//~ testChannel.regs[2]++;
OPL3::setChannelFrequency(testChannel, frequencyForNote(note));
testChannel.kon = 1;
OPL3::channelKeyOn(0, testChannel);
}
void handleNoteOff(uint8_t channel, uint8_t note, uint8_t velocity) {
DebugLED::setLow();
testChannel.kon = 0;
OPL3::channelKeyOff(0, testChannel);
}
void handlePolyAftertouch(uint8_t channel, uint8_t note, uint8_t velocity) {
}
void handleControlChange(uint8_t channel, uint8_t control, uint8_t value) {
}
void handleProgramChange(uint8_t channel, uint8_t program) {
}
void handleAftertouch(uint8_t channel, uint8_t value) {
}
void handlePitchBend(uint8_t channel, uint16_t value) {
}
/** @} */
uint16_t prevTickMillis;
void tick() {
}
public:
static void begin() {
Self& self = getSelf();
DebugLED::setOutput();
DebugLED::setHigh();
OPL3::begin();
Serial1.begin(31250);
static_cast< MIDIParser<OPL3box>& >(self).begin();
I2C::begin();
LCD::begin();
LCD::setFlippedVertically(false);
LCD::setContrast(10);
self.page0 = true;
LCD::setDisplayStartLine(0);
LCD::clear();
LCD::drawTextCentered(Font8Console::data(), 0, 1, LCD::Cols, "OPL3 BOX", Font8::DrawingScale2);
LCD::turnOn();
self.prevTickMillis = millis();
self.tick();
// Test operators.
self.testChannel.cnt = 0;
self.testChannel.fb = 0;
self.testChannel.cha = true;
self.testChannel.chb = true;
self.testOperator1.egt = true;
self.testOperator1.tl = 0;
self.testOperator1.ar = 0x5;
self.testOperator1.dr = 0x5;
self.testOperator1.sl = 0;
self.testOperator1.rr = 0x3;
self.testOperator1.mult = 0;
self.testOperator1.waveform = OPL3::WaveformSine;
self.testOperator2 = self.testOperator1;
self.testOperator2.tl = 1;
self.testOperator2.mult = 1;
for (int i = 0; i < 18; i++) {
OPL3::updateOperator(i + 0, self.testOperator1);
OPL3::updateOperator(i + 3, self.testOperator2);
}
DebugLED::setLow();
}
uint8_t value;
bool buttonPressed;
static void check() {
Self& self = getSelf();
// Calling the tick handler without a dedicated timer for now.
uint16_t now = millis();
if ((uint16_t)(now - getSelf().prevTickMillis) >= 20) {
self.prevTickMillis = now;
self.tick();
}
// Classic MIDI on the serial port.
if (Serial1.available()) {
self.handleByte(Serial1.read());
}
// Simplified USB MIDI for now.
midiEventPacket_t event = MidiUSB.read();
if (event.header != 0) {
self.handleByte(event.byte1);
self.handleByte(event.byte2);
self.handleByte(event.byte3);
}
bool needsRedraw = false;
bool buttonPressedNow = !encoderButton::read();
if (self.buttonPressed && !buttonPressedNow) {
self.onEncoderButton();
needsRedraw = true;
}
self.buttonPressed = buttonPressedNow;
EC11Event e;
if (encoder1.read(&e)) {
// Need to use 'count' instead of 1 as there can be multiple turns accumulated when the encoder is fed from an interrupt handler.
self.onEncoderDelta(e.type == EC11Event::StepCW ? e.count : -e.count);
needsRedraw = true;
}
if (needsRedraw) {
self.draw();
}
}
// - //
OperatorValues operator1Values = OperatorValues(testOperator1, 1);
OperatorValues operator2Values = OperatorValues(testOperator2, 2);
int valuesCount() {
return operator1Values.valuesCount + operator2Values.valuesCount;
}
OperatorValue * valueAt(int i) {
if (i < operator1Values.valuesCount) {
return operator1Values.valueAt(i);
}
else {
return operator2Values.valueAt(i - operator1Values.valuesCount);
}
}
int uiCaret = 0;
int uiMenu = 0;
bool titleRow() { return uiCaret == 0; }
bool valueRow() { return uiCaret == 1; }
void onEncoderButton() {
uiCaret = (uiCaret + 1) % 2;
}
void onEncoderDelta(int delta) {
if (titleRow()) {
int count = valuesCount();
uiMenu = max(0, min(count - 1, uiMenu + delta));
}
if (valueRow()) {
valueAt(uiMenu)->onEncoderDelta(delta);
// Assuming something about operators has changed and updating them here for now.
OPL3::updateOperator(0, testOperator1);
OPL3::updateOperator(3, testOperator2);
}
}
bool page0;
void draw() {
// Drawing in the invisible half of the video memory.
page0 = !page0;
uint8_t pageOffset = page0 ? 0 : 4;
LCD::clear(
0, pageOffset + 0,
LCD::Cols - 1, pageOffset + LCD::Pages - 1
);
OperatorValue * value = valueAt(uiMenu);
char str[50];
str[0] = titleRow() ? '>' : ' ';
str[1] = ' ';
value->getParamString(str + 2, sizeof(str) - 2);
LCD::drawText(Font8Console::data(), 0, pageOffset + 0, str, Font8::DrawingScale2);
str[0] = valueRow() ? '>' : ' ';
str[1] = ' ';
value->getValueString(str + 2, sizeof(str) - 2);
LCD::drawText(Font8Console::data(), 0, pageOffset + 2, str, Font8::DrawingScale2);
// Flipping the visible and invisible parts.
LCD::setDisplayStartLine(page0 ? 0 : 32);
}
};
void setup() {
encoder1PinA::setInput(true);
encoder1PinB::setInput(true);
encoderButton::setInput(true);
OPL3box::begin();
}
void loop() {
encoder1.checkPins(encoder1PinA::read(), encoder1PinB::read());
OPL3box::check();
}