TinkerBlock UNO kit/Sound/14. Lab: a melody player
Sound · 14 of 21

Lab: a melody player

Three public-domain tunes on the passive buzzer, each stored as note numbers and lengths, with every frequency worked out by one formula: 440 Hz times 2 to the power of the semitones from A4, over 12. The push button skips to the next tune at once, because nothing in the sketch waits.

The passive buzzer makes no sound of its own: it sounds at whatever frequency it is sent, which is what makes it play tunes. The TK37's book has the coil, the transistor and the gap between notes in a melody is notes and lengths; this lab adds the push button, and leans on tone() and Timer2 and millis().

Where they plug in

ModuleSocketPin
TK37 passive buzzerD8/D9D9
TK04 push buttonD6/D7D7

tone() works on any pin, so D9's PWM is not what it is there for. It is there because the XL LED keeps D3 and the other modules keep their own sockets through this chapter.

One formula instead of a table

The usual melody sketch opens with a page of #define NOTE_C4 262 lines. This one has none. A note is a number, as in MIDI: 69 is A4, and each step up or down is one semitone. The frequency follows from equal temperament, in which every semitone multiplies the frequency by the same ratio, the twelfth root of two, about 1.0595, so twelve of them double it:

unsigned int hz(byte key) {
  return 440.0 * pow(2.0, (key - 69) / 12.0) + 0.5;  // rounded
}

440 Hz for A4 is the standard tuning pitch, set in ISO 16. Everything else in the sketch is a note number from the enum at the top: e6 is 88, so hz(e6) is 1318.51 Hz, sent to tone() as 1319. The names are in lower case because A5 and A6 already mean the UNO's analogue pins.

From a note number to a frequency
NoteE6 (n = 88)
Exact
1318.51 Hz
tone() gets
1319 Hz
Timer2
16 MHz / 32 / 189 / 2
Plays
1322.75 Hz
E6 is 19 semitones above A4, so its frequency is 440 Hz times 2 to the power 19/12. tone() takes whole hertz, and Timer2 can only flip the pin after a whole number of its ticks, 189 ticks of 32 clocks here. Tone.cpp rounds that count down, so the note plays 5.6 cents sharp: a small fraction of the 100 cents between two neighbouring notes, and every note in a tune is off in the same direction.

Slide through the notes. Each octave doubles: C6 is 1046.50 Hz, C7 2093. The number that plays is a little higher than the number asked for, because tone() on Timer2 can only flip the pin after a whole number of the timer's ticks, and the core rounds that number down. Every note here comes out 0.6 to 9.5 cents sharp, against 100 cents between two neighbouring notes.

The tunes

All three are public domain: the theme of Beethoven's Ode to Joy from his Ninth Symphony (1824); the 18th-century French melody Ah! vous dirai-je, maman, sung in English as Twinkle Twinkle; and the French round Frère Jacques. Each is written in the sixth octave, where the TK37 is louder than an octave down, as its book's response curve shows. A tune is an array of pairs, a note and a length in eighth notes:

const Note ODE[] = {
  {e6,2},{e6,2},{f6,2},{g6,2},{g6,2},{f6,2},{e6,2},{d6,2},
  ...

Playing without waiting

The player keeps four numbers: which tune, which note is next, when the current note began and how long it lasts. Each time round loop() it checks whether the note is over; if not, it returns at once and the loop goes on to read the button.

if (!playing || millis() - noteAt < noteMs) return;
...
noteAt += noteMs;           // no drift: each note from the last
noteMs = (unsigned long)n.eighths * EIGHTH_MS;
tone(BUZZER, hz(n.key), noteMs * SOUND_PCT / 100);

noteAt += noteMs dates each note from the start of the one before rather than from the moment the loop noticed, so small delays never add up and the tempo holds. tone() with a length stops itself 90 % of the way through and, in the AVR core, leaves the pin LOW. That matters on this board: the TK37's coil is switched by a transistor, and a SIGNAL left HIGH holds the coil on, drawing a couple of hundred milliamps for no sound.

Make it yours

  • Add a fourth tune. Any melody old enough to be public domain will do; REST (0) is a silence of the length you give it.
  • Change EIGHTH_MS: at 150 ms a quarter note is 300 ms, 200 a minute; 250 ms makes it 120 a minute, a walking pace.
  • Play the whole tune an octave lower by subtracting 12 from the key inside hz(), and hear the TK37 get quieter.

The code

Melody_Player.ino

Press the button: Ode to Joy. Press again, even mid-note: Twinkle Twinkle, then Frere Jacques, then round again. The Serial Monitor at 115200 baud names each tune.

// Melody_Player.ino: three public-domain tunes on the passive
// buzzer. Each press of the push button starts the next tune,
// even in the middle of one.
//
// Wiring, on the TinkerBlock UNO shield:
//   TK37 passive buzzer in the D8/D9 socket, so it is on D9
//   TK04 push button in the D6/D7 socket, so it is on D7
// Tools > Board: Arduino Uno
// Tools > Port: the CH340 port
// Serial Monitor: 115200 baud
// No library: tone() is part of the Arduino core.
//
// A note is a number, MIDI style: 69 is A4 and each step is a
// semitone. hz() turns it into a frequency by equal temperament,
// 440 x 2^((n - 69) / 12), so the sketch needs no note table.

const byte BUZZER = 9;
const byte BUTTON = 7;

// 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 unsigned int EIGHTH_MS = 150;  // one eighth note
const byte SOUND_PCT = 90;           // the rest of it is silence

int tune = -1;              // none yet
byte next = 0;              // the next note to play
bool playing = false;
unsigned long noteAt = 0;   // when the current note began
unsigned long noteMs = 0;   // its whole length, gap included

bool raw = LOW, pressed = LOW;
unsigned long rawAt = 0;

unsigned int hz(byte key) {
  return 440.0 * pow(2.0, (key - 69) / 12.0) + 0.5;
}

void start(int t) {
  noTone(BUZZER);
  tune = t;
  next = 0;
  playing = true;
  noteAt = millis();
  noteMs = 0;               // so the first note starts now
  Serial.print("Playing ");
  Serial.println(TUNES[t].name);
}

// True once per press: HIGH for 20 ms after being LOW.
bool buttonPressed() {
  bool reading = digitalRead(BUTTON);
  if (reading != raw) {
    raw = reading;
    rawAt = millis();
  }
  if (raw != pressed && millis() - rawAt >= 20) {
    pressed = raw;
    return pressed == HIGH;
  }
  return false;
}

void setup() {
  pinMode(BUZZER, OUTPUT);
  digitalWrite(BUZZER, LOW);  // HIGH would hold the coil on
  pinMode(BUTTON, INPUT);     // the TK04 has its own pull-down
  Serial.begin(115200);
  Serial.println("Press the button for a tune.");
}

void loop() {
  if (buttonPressed()) start((tune + 1) % TUNE_COUNT);

  if (!playing || millis() - noteAt < noteMs) return;

  const Tune &t = TUNES[tune];
  if (next >= t.count) {
    playing = false;
    Serial.println("End. Press for the next tune.");
    return;
  }
  Note n = t.notes[next++];
  noteAt += noteMs;           // no drift: each note from the last
  noteMs = (unsigned long)n.eighths * EIGHTH_MS;
  if (n.key != REST) {
    // tone() with a length stops itself and leaves the pin LOW.
    tone(BUZZER, hz(n.key), noteMs * SOUND_PCT / 100);
  }
}

A tune is an array of {note, eighths}. Write your own with the note numbers in the enum, add a line to TUNES, and it joins the rotation. EIGHTH_MS is the tempo for all three.

View on GitHub · kits/tkbu/melody-player/Melody_Player/Melody_Player.ino @ v1.14

When it does not work

The button does nothing until a tune ends.

That is a sketch that plays with delay(): the loop is stuck in the wait and never reads the pin. This one keeps the time each note began and checks millis() instead. If you have added a delay() of your own, take it out.

The buzzer is silent when a tune should be playing.

The TK37's lamp glows while a note plays, because its transistor switches with the wave. No glow means no wave on SIGNAL: check the TK37 is in the D8/D9 socket, on D9, its cable is seated, and the Serial Monitor printed Playing.

Two equal notes in a row sound like one long one.

Each note must stop before the next starts. The sketch sounds a note for SOUND_PCT, 90 %, of its length; at 100 % there is no gap and repeats merge. 80 % sounds more detached.

The XL LED stopped fading after I added a tune.

tone() runs on Timer2, which also makes the PWM on D3 and D11. While a note plays, D3 cannot fade, and after noTone() it stays off until the next analogWrite(). Write the LED's value again after each note, or blink it with digitalWrite.

A tune is in tune with itself but slightly sharp.

Timer2 can only count whole ticks, so tone() plays every note a few cents high, up to about 10 cents for the notes here. The figure shows each note's error. It is far less than the 100 cents between neighbouring notes.

Where this goes next

The same player, driven by characters typed into the Serial Monitor.

Lab: a jukebox you type to →

Edit this page — content/books/tkbu/melody-player.mdx

Community

Questions about this product

See what other owners have asked, and read their solutions.

Ask a question ↗

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.

Browse Modules and blocks on the forum →