-
Notifications
You must be signed in to change notification settings - Fork 5
/
MusicEngine.cpp
421 lines (371 loc) · 14.9 KB
/
MusicEngine.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
// MusicEngine class
// Retro Music Engine
// Author: Chris Taylor (taylorza)
// see https://developer.mbed.org/users/taylorza/code/MusicEngine/
// Ported from mBed to ESP8266/Arduino by MMOLE ([email protected])
/** MusicEngine provides a means to play Music Macro Language sequences asynchronously.
* Learn more about Music Macro Language (MML) on wikipedia
* http://en.wikipedia.org/wiki/Music_Macro_Language
* For music see http://www.archeagemmllibrary.com/
*/
#include "MusicEngine.h"
//#include <Arduino.h>
#if defined (ARDUINO_ARCH_ESP8266)
#include <cctype>
#endif
const float MusicEngine::WHOLE_NOTE_DURATION = 1.0f;
const float MusicEngine::QUARTER_NOTE_DURATION = MusicEngine::WHOLE_NOTE_DURATION / 4.0f;
const float MusicEngine::QUARTER_NOTES_PER_MINUTE = 60.0f / MusicEngine::QUARTER_NOTE_DURATION;
const float MusicEngine::DEFAULT_TIMING = 7.0f / 8.0f;
const float MusicEngine::LEGATO_TIMING = 1.0f;
const float MusicEngine::STACCATO_TIMING = 3.0f / 4.0f;
const int MusicEngine::NOTE_REST = 0;
const int MusicEngine::NOTE_C = 1;
const int MusicEngine::NOTE_CS = 2;
const int MusicEngine::NOTE_D = 3;
const int MusicEngine::NOTE_DS = 4;
const int MusicEngine::NOTE_E = 5;
const int MusicEngine::NOTE_F = 6;
const int MusicEngine::NOTE_FS = 7;
const int MusicEngine::NOTE_G = 8;
const int MusicEngine::NOTE_GS = 9;
const int MusicEngine::NOTE_A = 10;
const int MusicEngine::NOTE_AS = 11;
const int MusicEngine::NOTE_B = 12;
MusicEngine::MusicEngine(int pin)
: _pinPwm(pin)
, _isPlaying(false)
, _completionCallback(NULL)
{
pinMode(_pinPwm, OUTPUT);
this->noTone();
}
void MusicEngine::tone(unsigned int frequency, unsigned long length) // length=0
{
/*
Serial.print(F("MusicEngine tone:"));
Serial.print(frequency);
Serial.print(F(", len "));
Serial.print(length);
Serial.print(F(", pin "));
Serial.println(_pinPwm);
*/
#if defined (ARDUINO_ARCH_ESP8266)
// Set the PWM frequency to that specified by the note being played
analogWriteFreq(frequency);
// Note that PWM has lots of harmonics, so volume control using the PWM
// duty-cycle is not very good, but perhaps better than nothing.
// The default pwm-range is 1024. A 50% duty-cycle (=512) gives highest volume
// The volume command Vnnn has a range 0-128, so we multiply by 4 to get the PWM
// value.
analogWrite(_pinPwm, _volume * 4);
#else
_toneTim2(_pinPwm, frequency, length);
#endif
}
void MusicEngine::noTone()
{
#if defined (ARDUINO_ARCH_ESP8266)
analogWriteFreq(1000); // Note: analogWriteFreq(0); gives a spontaneous WDT reset
analogWrite(_pinPwm, 0); // default range is 1024, start quiet using pulse-width zero
#else
_noToneTim2();
#endif
}
void MusicEngine::waitTone(unsigned long length) // length=0
{ // schedule wait time. length is specified in msec
#if defined (ARDUINO_ARCH_ESP8266)
_scheduler.once(length/1000.0, &MusicEngine::musicTickerCallback, this);
#else
_waitToneTim2(length);
#endif
}
void MusicEngine::play(const char* mml)
{
//Serial.print(F("MusicEngine play:"));
//Serial.println(mml);
// __disable_irq();
_isPlaying = false;
_mml = mml;
_mmlIndex = 0;
_octave = 4;
_duration = QUARTER_NOTE_DURATION;
_durationRatio = DEFAULT_TIMING;
_tempo = 120;
_volume = 128;
//_pwm.period(0);
//_pwm = 0.5f;
this->noTone();
_pause = 0;
_isPlaying = true;
// __enable_irq();
MusicEngine::executeCommand();
}
void MusicEngine::stop()
{
// __disable_irq();
_isPlaying = false;
// __enable_irq();
}
void MusicEngine::executeCommand()
{
// _scheduler.detach();
if (_pause < 0)
_pause = 0;
if (_pause != 0) {
//_pwm.period(0);
//_pwm = 0.0f;
// _scheduler.attach(this, &MusicEngine::executeCommand, _pause);
this->noTone();
this->waitTone(_pause*1000);
_pause = 0;
} else {
int freqIndex = -1;
do {
skipWhiteSpace();
switch (getChar()) {
case 'a':
freqIndex = NOTE_A;
break;
case 'b':
freqIndex = NOTE_B;
break;
case 'c':
freqIndex = NOTE_C;
break;
case 'd':
freqIndex = NOTE_D;
break;
case 'e':
freqIndex = NOTE_E;
break;
case 'f':
freqIndex = NOTE_F;
break;
case 'g':
freqIndex = NOTE_G;
break;
case 'p':
case 'r':
freqIndex = NOTE_REST;
break;
case 'l':
if (isdigit(peekChar()))
_duration = (float)WHOLE_NOTE_DURATION / getNumber(1, 64);
break;
case 'o':
if (isdigit(peekChar()))
_octave = getNumber(0, 7);
break;
case 't':
if (isdigit(peekChar()))
_tempo = getNumber(32, 255);
break;
case 'v':
if (isdigit(peekChar()))
_volume = getNumber(0, 128);
break;
case 'm':
switch (getChar()) {
case 'n':
_durationRatio = DEFAULT_TIMING;
break;
case 'l':
_durationRatio = LEGATO_TIMING;
break;
case 's':
_durationRatio = STACCATO_TIMING;
break;
}
break;
case 'n':
if (isdigit(peekChar()))
freqIndex = getNumber(0, 96);
break;
case '<':
--_octave;
if (_octave < 0)
_octave = 0;
break;
case '>':
++_octave;
if (_octave > 7)
_octave = 7;
break;
case '\0':
_isPlaying = false;
break;
}
if (!_isPlaying) {
//_pwm.period_ms(1);
//_pwm.write(0.0);
this->noTone();
if (_completionCallback)
_completionCallback();
return;
}
float durationRatio = _durationRatio;
float duration = _duration;
if (freqIndex != -1) {
bool fCminus = false; // MMOLE: ugly fix for nitwits that use C- in their music
switch (getChar()) {
case '+':
case '#':
++freqIndex;
break;
case '-':
--freqIndex;
if (freqIndex == 0)
fCminus = true;
break;
case '.':
durationRatio = 3.0f / 2.0f;
while (peekChar() == '.') {
durationRatio *= 3.0f / 2.0f;
getChar();
}
break;
default:
rewind();
break;
}
if (isdigit(peekChar())) {
duration = WHOLE_NOTE_DURATION / getNumber(1, 64);
}
if (freqIndex != NOTE_REST || (fCminus && _octave > 0)) {
//_pwm.period(PERIOD_TABLE[freqIndex + (_octave * 12)]);
//_pwm = 0.5;
float ftFreq = 1.0 / PERIOD_TABLE[freqIndex + (_octave * 12)];
if (fCminus)
ftFreq = 1.0 / PERIOD_TABLE[NOTE_B + ((_octave - 1) * 12)]; // MMOLE: ugly
// fix: play C-
// as B in lower
// octave
this->tone((int)ftFreq); // start playing the new tone
}
duration *= (QUARTER_NOTES_PER_MINUTE / _tempo);
_pause=duration * durationRatio;
this->waitTone(_pause*1000); // schedule to wait until tone is done
_pause = duration * (1 - durationRatio);
}
} while (freqIndex == -1);
}
}
int MusicEngine::getNumber(int min, int max)
{
char ch;
int value = 0;
while ((ch = getChar()) != 0) {
if (!isdigit(ch)) {
rewind();
break;
}
int digit = (int)ch - 48;
value = (value * 10) + digit;
}
value = value < min ? min : value > max ? max : value;
return value;
}
void MusicEngine::skipWhiteSpace()
{
while (isspace(peekChar()))
getChar();
}
char MusicEngine::getChar()
{
return tolower(_mml[_mmlIndex++]);
}
char MusicEngine::peekChar()
{
return tolower(_mml[_mmlIndex]);
}
void MusicEngine::rewind()
{
--_mmlIndex;
}
void MusicEngine::musicTickerCallback(MusicEngine* __thisMusicEngine)
{
__thisMusicEngine->executeCommand();
}
// ATmega Timer2 tone function derived from ToneAC2 library code: https://bitbucket.org/teckel12/arduino-toneac2/
#if !defined(ARDUINO_ARCH_ESP8266)
// #elif defined (__AVR_ATmega328P__) || defined (__AVR_ATmega328__) || defined (__AVR_ATmega168__) || defined (__AVR_ATmega168P__)
// #elif defined (ARDUINO_UNO) || defined(ARDUINO_AVR_MEGA2560)
unsigned long _tTim2_time; // Used to track end note with timer when playing note in the background.
volatile uint8_t *_pinMode; // Pin mode.
uint8_t _pinMask = 0; // Bitmask for pins
volatile uint8_t *_pinOutput; // Output port register for pin.
const int _tTim2_prescale[] = { 2, 16, 64, 128, 256, 512, 2048 }; // Prescaler.
MusicEngine* __thisMusicEngine__; // TODO: unfortunately I know no better way to call an instance method from the ISR than by using a global reference
void MusicEngine::_toneTim2(uint8_t pin, unsigned int frequency, unsigned long length)
{ // playing a tone
long top;
uint8_t prescaler;
for (prescaler = 1; prescaler < 8; prescaler++) { // Find the appropriate prescaler
top = F_CPU / (long) frequency / (long) _tTim2_prescale[prescaler - 1] - 1; // Calculate the top.
if (top < 256) break; // Fits, break out of for loop.
}
if (top > 255) { _noToneTim2(); return; } // Frequency is out of range, turn off sound and return.
if (length > 0) _tTim2_time = millis() + length - 1; else _tTim2_time = 0xFFFFFFFF; // Set when the note should end, or play "forever".
if (_pinMask == 0) { // This gets the port register and bitmap for the pin and sets the pin to output mode.
_pinMask = digitalPinToBitMask(pin); // Get the port register bitmask for pin.
_pinOutput = portOutputRegister(digitalPinToPort(pin)); // Get the output port register for pin.
_pinMode = (uint8_t *) portModeRegister(digitalPinToPort(pin)); // Get the port mode register for pin.
*_pinMode |= _pinMask; // Set pin to Output mode.
}
// TODO: find out how to implement interrupts in class to get rid of globals and non-privates
__thisMusicEngine__=this;
OCR2A = top; // Set the top.
if (TCNT2 > top) TCNT2 = top; // Counter over the top, put within range.
TCCR2B = _BV(WGM22) | prescaler; // Set Fast PWM and prescaler.
TCCR2A = _BV(WGM20) | _BV(WGM21); // Fast PWM and normal port operation, OC2A/OC2B disconnected.
//TIMSK2 &= ~_BV(OCIE2A); // Stop timer 2 interrupt while we set the pin states.
TIMSK2 |= _BV(OCIE2A); // Activate the timer interrupt.
}
void MusicEngine::_noToneTim2(void)
{ // stop playing any tone
TIMSK2 &= ~_BV(OCIE2A); // Remove the timer interrupt.
TCCR2B = _BV(CS22); // Default clock prescaler of 64.
TCCR2A = _BV(WGM20); // Set to defaults so PWM can work like normal (PWM, phase corrected, 8bit).
*_pinMode &= ~_pinMask; // Set pin to INPUT.
_pinMask = 0; // Flag so we know note is no longer playing.
}
void MusicEngine::_executeCommandTim2(void)
{
executeCommand();
}
void MusicEngine::_waitToneTim2(unsigned long length)
{ // set endtime of tone (or no tone) playing to allow callback at end of tone
// TODO: find out how to implement interrupts in class to get rid of globals and non-privates
__thisMusicEngine__=this; // need to be set in both tone and in wait to be able to call executeCommand
_tTim2_time = millis() + length - 1;
TIMSK2 |= _BV(OCIE2A); // Activate the timer interrupt.
}
ISR(TIMER2_COMPA_vect)
{ // Timer interrupt vector.
if(!__thisMusicEngine__)
return;
if (millis() > _tTim2_time)
{
__thisMusicEngine__->_noToneTim2(); // Check to see if it's time for the note to end.
__thisMusicEngine__->_executeCommandTim2(); // execute the next command
}
else
*_pinOutput ^= _pinMask; // Toggle the pin state.
}
#endif
// clang-format off
const float MusicEngine::PERIOD_TABLE[] = {
0,
//1 2 3 4 5 6 7 8 9 10 11 12
//C C# D D# E F F# G G# A A# B
1.0f / 16.35f, 1.0f / 17.32f, 1.0f / 18.35f, 1.0f / 19.45f, 1.0f / 20.60f, 1.0f / 21.83f, 1.0f / 23.12f, 1.0f / 24.50f, 1.0f / 25.96f, 1.0f / 27.50f, 1.0f / 29.14f, 1.0f / 30.87f, // Octave 0
1.0f / 32.70f, 1.0f / 34.65f, 1.0f / 36.71f, 1.0f / 38.89f, 1.0f / 41.20f, 1.0f / 43.65f, 1.0f / 46.25f, 1.0f / 49.00f, 1.0f / 51.91f, 1.0f / 55.00f, 1.0f / 58.27f, 1.0f / 61.74f, // Octave 1
1.0f / 65.41f, 1.0f / 69.30f, 1.0f / 73.42f, 1.0f / 77.78f, 1.0f / 82.41f, 1.0f / 87.31f, 1.0f / 92.50f, 1.0f / 98.00f, 1.0f / 103.83f, 1.0f / 110.00f, 1.0f / 116.54f, 1.0f / 123.47f, // Octave 2
1.0f / 130.81f, 1.0f / 138.59f, 1.0f / 146.83f, 1.0f / 155.56f, 1.0f / 164.81f, 1.0f / 174.62f, 1.0f / 185.00f, 1.0f / 196.00f, 1.0f / 207.65f, 1.0f / 220.00f, 1.0f / 233.08f, 1.0f / 246.94f, // Octave 3
1.0f / 261.63f, 1.0f / 277.18f, 1.0f / 293.67f, 1.0f / 311.13f, 1.0f / 329.63f, 1.0f / 349.23f, 1.0f / 370.00f, 1.0f / 392.00f, 1.0f / 415.31f, 1.0f / 440.00f, 1.0f / 466.17f, 1.0f / 493.89f, // Octave 4
1.0f / 523.25f, 1.0f / 554.37f, 1.0f / 587.33f, 1.0f / 622.26f, 1.0f / 659.26f, 1.0f / 698.46f, 1.0f / 739.99f, 1.0f / 783.99f, 1.0f / 830.61f, 1.0f / 880.00f, 1.0f / 932.33f, 1.0f / 987.77f, // Octave 5
1.0f / 1046.51f, 1.0f / 1108.74f, 1.0f / 1174.67f, 1.0f / 1244.51f, 1.0f / 1318.52f, 1.0f / 1396.92f, 1.0f / 1479.99f, 1.0f / 1567.99f, 1.0f / 1661.23f, 1.0f / 1760.01f, 1.0f / 1864.66f, 1.0f / 1975.54f, // Octave 6
1.0f / 2093.02f, 1.0f / 2217.47f, 1.0f / 2349.33f, 1.0f / 2489.03f, 1.0f / 2637.03f, 1.0f / 2793.84f, 1.0f / 2959.97f, 1.0f / 3135.98f, 1.0f / 3322.45f, 1.0f / 3520.02f, 1.0f / 3729.33f, 1.0f / 3951.09f, // Octave 7
};
// clang-format on