Lab: a jukebox you type to
The melody player with the button replaced by the keyboard. Every character typed into the Serial Monitor is a command: a digit picks a tune, p pauses, + and - change the tempo, u and d move the whole tune a semitone. The player never stops to listen, because the characters wait in a buffer until it looks.
The melody player chose tunes with a button; this one takes orders from the computer. The tunes, the formula and the player are the same, and the TK37's book covers the buzzer. What is new is reading text from the Serial Monitor, which runs over D0 and D1 and the USB cable.
Where it plugs in
| Module | Socket | Pin |
|---|---|---|
| TK37 passive buzzer | D8/D9 | D9 |
The push button can stay in its D6/D7 socket; this sketch does not read it.
One character, one command
| Type | It does |
|---|---|
1 2 3 | play Ode to Joy, Twinkle Twinkle or Frere Jacques from the start |
p | pause, or carry on from the note that was next |
s | stop and forget the place |
+ - | eighth note 15 ms shorter or longer (60 to 300 ms) |
u d | every note a semitone up or down (12 at most either way) |
? | print this list |
Press 1, then u a few times: Ode to Joy's first note, E6, climbs 1319, 1397, 1480 Hz, each about 6 % above the last, because a semitone is the same ratio everywhere. Press x: the sketch says it does not know it rather than doing nothing.
Reading without waiting
Characters from the computer arrive at 115200 baud, about eleven thousand a second,
whether or not the sketch is looking. The UNO's serial code catches each in
an interrupt and keeps it in a 64-byte buffer until the sketch asks.
Serial.available() says how many are waiting; Serial.read() takes one.
while (Serial.available() > 0) {
char c = Serial.read();
if (c != '\n' && c != '\r' && c != ' ') command(c);
}The loop takes everything waiting, then goes straight back to the player's
millis() check, which is why a command lands between two notes rather than
after the tune. One character per command keeps it that simple: there is no
line to assemble, no number to parse, and the monitor's line-ending setting
cannot break it, because \n and \r are skipped.
Tempo and transpose are two numbers
Every length in a tune is a count of eighth notes and every pitch a note number, so speeding up and moving up are each one variable:
noteMs = (unsigned long)n.eighths * eighthMs; // + and - change eighthMs
tone(BUZZER, hz(n.key + shift), noteMs * SOUND_PCT / 100); // u and dThe tune itself is never touched. A change takes effect from the next note,
and s puts nothing back: the tempo and the transpose stay where you left
them until you press the reset button.
Make it yours
- Add a command that plays one note:
afor A6, held for a quarter note, withtone(BUZZER, hz(a6 + shift), 300). - Print each note as it plays, its number and
hz(), to watch transposing change the frequencies. - Accept numbers: read digits into a value until a newline, and set the
tempo in milliseconds with a command like
t120.
The code
Open the Serial Monitor at 115200 baud, type 1 and press Enter. Then, while it plays: + + to speed it up, u u u to move it up three semitones, p to pause and p again to carry on.
// Serial_Jukebox.ino: the melody player, driven from the Serial
// Monitor. Type a command and press Enter (or not: every
// character is a command, and line endings are ignored).
//
// 1 2 3 play that tune p pause or carry on
// s stop + faster - slower
// u up a semitone d down a semitone
// ? this list
//
// Wiring, on the TinkerBlock UNO shield:
// TK37 passive buzzer in the D8/D9 socket, so it is on D9
// Tools > Board: Arduino Uno
// Tools > Port: the CH340 port
// Serial Monitor: 115200 baud, any line ending
// No library.
const byte BUZZER = 9;
// Note names in lower case: A5 and A6 are already pin names.
enum : byte {
REST = 0, g5 = 79, a5 = 81, b5 = 83, c6 = 84, d6 = 86,
e6 = 88, f6 = 89, g6 = 91, a6 = 93
};
struct Note { byte key; byte eighths; };
// Beethoven, Symphony No. 9 (1824): the Ode to Joy theme.
const Note ODE[] = {
{e6,2},{e6,2},{f6,2},{g6,2},{g6,2},{f6,2},{e6,2},{d6,2},
{c6,2},{c6,2},{d6,2},{e6,2},{e6,3},{d6,1},{d6,4},
{e6,2},{e6,2},{f6,2},{g6,2},{g6,2},{f6,2},{e6,2},{d6,2},
{c6,2},{c6,2},{d6,2},{e6,2},{d6,3},{c6,1},{c6,4}
};
// An 18th-century French melody, later sung to Twinkle Twinkle.
const Note TWINKLE[] = {
{c6,2},{c6,2},{g6,2},{g6,2},{a6,2},{a6,2},{g6,4},
{f6,2},{f6,2},{e6,2},{e6,2},{d6,2},{d6,2},{c6,4},
{g6,2},{g6,2},{f6,2},{f6,2},{e6,2},{e6,2},{d6,4},
{g6,2},{g6,2},{f6,2},{f6,2},{e6,2},{e6,2},{d6,4},
{c6,2},{c6,2},{g6,2},{g6,2},{a6,2},{a6,2},{g6,4},
{f6,2},{f6,2},{e6,2},{e6,2},{d6,2},{d6,2},{c6,4}
};
// Frere Jacques, a French round.
const Note FRERE[] = {
{c6,2},{d6,2},{e6,2},{c6,2},{c6,2},{d6,2},{e6,2},{c6,2},
{e6,2},{f6,2},{g6,4},{e6,2},{f6,2},{g6,4},
{g6,1},{a6,1},{g6,1},{f6,1},{e6,2},{c6,2},
{g6,1},{a6,1},{g6,1},{f6,1},{e6,2},{c6,2},
{c6,2},{g5,2},{c6,4},{c6,2},{g5,2},{c6,4}
};
struct Tune { const char *name; const Note *notes; byte count; };
#define TUNE(name, a) { name, a, sizeof(a) / sizeof(Note) }
const Tune TUNES[] = {
TUNE("Ode to Joy", ODE),
TUNE("Twinkle Twinkle", TWINKLE),
TUNE("Frere Jacques", FRERE)
};
const byte TUNE_COUNT = sizeof(TUNES) / sizeof(Tune);
const byte SOUND_PCT = 90;
const int TEMPO_STEP = 15, MIN_EIGHTH = 60, MAX_EIGHTH = 300;
const int MAX_SHIFT = 12;
int eighthMs = 150; // the tempo: one eighth note, ms
int shift = 0; // transpose, semitones
int tune = 0;
byte next = 0;
bool playing = false;
unsigned long noteAt = 0;
unsigned long noteMs = 0;
unsigned int hz(int key) {
return 440.0 * pow(2.0, (key - 69) / 12.0) + 0.5;
}
void help() {
Serial.println("1 2 3 tune, p pause, s stop, + faster, - slower,");
Serial.println("u up a semitone, d down a semitone, ? this list");
}
void resume() {
playing = true;
noteAt = millis();
noteMs = 0;
}
void command(char c) {
if (c >= '1' && c < '1' + TUNE_COUNT) {
noTone(BUZZER);
tune = c - '1';
next = 0;
resume();
Serial.print("Playing ");
Serial.println(TUNES[tune].name);
} else if (c == 'p') {
if (playing) {
noTone(BUZZER);
playing = false;
Serial.println("Paused");
} else if (next > 0 && next < TUNES[tune].count) {
resume();
Serial.println("Carrying on");
} else {
Serial.println("Nothing to carry on: type 1, 2 or 3");
}
} else if (c == 's') {
noTone(BUZZER);
playing = false;
next = 0;
Serial.println("Stopped");
} else if (c == '+' || c == '-') {
eighthMs += (c == '+') ? -TEMPO_STEP : TEMPO_STEP;
eighthMs = constrain(eighthMs, MIN_EIGHTH, MAX_EIGHTH);
Serial.print("Eighth note: ");
Serial.print(eighthMs);
Serial.println(" ms");
} else if (c == 'u' || c == 'd') {
shift += (c == 'u') ? 1 : -1;
shift = constrain(shift, -MAX_SHIFT, MAX_SHIFT);
Serial.print("Transpose: ");
Serial.print(shift);
Serial.print(" semitones, first note ");
Serial.print(hz(TUNES[tune].notes[0].key + shift));
Serial.println(" Hz");
} else if (c == '?') {
help();
} else {
Serial.print("Unknown command: ");
Serial.println(c);
}
}
void setup() {
pinMode(BUZZER, OUTPUT);
digitalWrite(BUZZER, LOW); // HIGH would hold the coil on
Serial.begin(115200);
Serial.println("Serial jukebox.");
help();
}
void loop() {
// One character at a time; the line ending and spaces are not
// commands.
while (Serial.available() > 0) {
char c = Serial.read();
if (c != '\n' && c != '\r' && c != ' ') command(c);
}
if (!playing || millis() - noteAt < noteMs) return;
const Tune &t = TUNES[tune];
if (next >= t.count) {
playing = false;
next = 0;
Serial.print("End of ");
Serial.println(t.name);
return;
}
Note n = t.notes[next++];
noteAt += noteMs;
noteMs = (unsigned long)n.eighths * eighthMs;
if (n.key != REST) {
tone(BUZZER, hz(n.key + shift), noteMs * SOUND_PCT / 100);
}
}Every character is a command and the line ending is skipped, so the monitor's line-ending menu does not matter and several commands can go in one line: 2++uu starts Twinkle Twinkle, faster and higher.
View on GitHub · kits/tkbu/serial-jukebox/Serial_Jukebox/Serial_Jukebox.ino @ v1.14When it does not work
Its baud menu must say 115200, the number in Serial.begin(). The sketch prints its list of commands when it starts; opening the monitor resets the UNO, so the list appears each time you open it.
The Serial Monitor sends what is in its input box only when you press Enter or Send. The sketch answers every command with a line, even an unknown one, so silence means the characters never left the computer.
The sketch skips newline, carriage return and space, so line endings are not the cause. Look at what follows the colon: capital letters are different characters from lower case, and P is not p.
s, or the end of the tune, forgets the place: the next note goes back to the first. p only resumes a tune that was paused in the middle. Type the tune's digit to start it again.
The eighth note stops at 60 ms and at 300 ms the other way, and the transpose at 12 semitones either side. At 12 up, A6 becomes A7 at 3520 Hz, past the TK37's 2.7 kHz peak and shrill; at 12 down the tunes fall into the fifth octave, where the TK37 is much quieter.
A folk tune on the buzzer and the LED bar at once, and why they must take turns.
Lab: a light-and-music show →Edit this page — content/books/tkbu/serial-jukebox.mdx
Questions about this product
See what other owners have asked, and read their solutions.
TinkerBlock UNO R3 Starter Kit, 12 Modules
Loading discussions…
Discuss this article
Ask about this page. The answer stays here, on the page it belongs to, for whoever hits the same wall next.