TinkerBlock UNO kit/Sound/16. Lab: a light-and-music show
Sound · 16 of 21

Lab: a light-and-music show

Korobeiniki, a 19th-century Russian folk song, on the passive buzzer, with the WS2812 bar drawing every note as it plays: taller and warmer for higher notes. The two modules each need the processor at an exact moment, so the sketch makes them take turns: the bar is sent in the silences, never while a note sounds.

The melody comes from the TK37, the light from the TK33 bar, and the library that drives the bar is the one installed in the first colours. The new part is two pieces of code that each need exact timing, and that is the subject of timers, tone() and Servo.

Where they plug in

ModuleSocketPin
TK37 passive buzzerD8/D9D9
TK33 WS2812 LED barD4/D5D5

The tune

Korobeiniki ("The Peddlers") is a Russian song from the 19th century; its words are Nikolai Nekrasov's poem of 1861, and the melody is a folk tune, long in the public domain. The sketch plays its first eight bars, moved up to run from A5 (880 Hz) to A6 (1760 Hz), where the TK37 is loud. It is written the way the melody player's tunes are: note numbers and lengths in eighth notes, 150 ms each.

Each note also sets the bar. Its height is map(key, a5, a6, 1, 5): A5 and B5 light one LED, A6 all five, and each height has its own colour, blue at the bottom to red at the top. The bar's brightness is 40 of 255, as in the TK33's book, which the TK33's sketch puts at 30 mA at most even with all five white.

Two clocks, one processor

The two modules are driven in opposite ways.

tone() sets up Timer2 to interrupt the sketch twice per cycle of the note, and the interrupt flips the buzzer pin. At E6 that is every 378 µs. The flip has to happen on time, or the wave is uneven and the note sounds rough.

The NeoPixel library uses no timer at all. A WS2812 reads each bit from the length of a pulse, so show() sends the bar's 120 bits (5 LEDs × 24) by counting processor cycles, and turns every interrupt off for the whole transmission so nothing can stretch a pulse. At 1.25 µs a bit that is about 150 µs.

show() and tone() take turns
The sketch calls show()
Note
silence
Bar
dark
show() blocks
150 µs
E6 half-cycle
378 µs
The sketch sends the bar first and starts the tone after, and clears the bar only after noTone(). show() never overlaps a note, so Timer2's interrupt is never kept waiting and every half-cycle is 378 µs.

With In the silences, show() runs before the tone starts and again after it has stopped, and the buzzer pin is never kept waiting. Pick While a note sounds: the interrupt due inside show() runs only when it ends, that edge comes late, and the next half-cycle is short by the same amount. Once is a faint click; an animation that refreshes the bar every few milliseconds does it hundreds of times a note.

So the loop has a fixed order:

draw(n.key);
bar.show();               // silence: nothing for it to disturb
if (n.key != REST) tone(BUZZER, hz(n.key));
delay(on);                // the note sounds; no show() here
noTone(BUZZER);           // stops Timer2, pin LOW

bar.clear();
bar.show();               // the gap: nothing is sounding
delay(ms - on);

The note is started without a length and stopped with noTone(), so the sketch knows the tone is over before it sends the bar again; a tone() with a length would end on Timer2's count and the delay() on millis(), and the two could miss each other by a fraction of a millisecond. delay() is fine here: this sketch has nothing else to listen to.

What Timer2 costs the rest of the kit

While tone() has Timer2, the two pins Timer2 makes PWM on, D3 and D11, cannot fade. In this kit that is the XL LED's socket (D3) and the active buzzer's (D11). The active buzzer only ever needs HIGH or LOW, so it loses nothing. The XL LED loses its fade for the length of the tune, and after noTone() it stays dark until the sketch calls analogWrite(3, …) again. The bar on D5 is unaffected: it never used a timer.

Make it yours

  • Add the XL LED on D3 as a beat lamp: digitalWrite(3, HIGH) with each note's show(), LOW with the gap's. On and off survive Timer2; a fade would not.
  • Colour by position in the tune instead of by pitch: the hue of each note from its index, so the bar runs through the rainbow once per tune.
  • Swap in one of the melody player's tunes; the bar's map() wants the lowest and highest notes the tune uses.

The code

Light_And_Music.ino

Needs the Adafruit NeoPixel library, as in the first-colours lab. The tune plays, the bar lights from the bottom up for each note and goes dark in the short gap after it, then the tune repeats after a second.

// Light_And_Music.ino: Korobeiniki, a 19th-century Russian folk
// song, on the passive buzzer, with the LED bar drawing every
// note: the higher the note, the taller and warmer the bar.
//
// Wiring, on the TinkerBlock UNO shield:
//   TK37 passive buzzer in the D8/D9 socket, so it is on D9
//   TK33 WS2812 LED bar in the D4/D5 socket, so it is on D5
// Tools > Board: Arduino Uno
// Tools > Port: the CH340 port
// Library Manager: "Adafruit NeoPixel" by Adafruit (1.15.5)
//
// tone() runs on Timer2's interrupt; bar.show() turns every
// interrupt off for about 150 us while it sends 120 bits. So the
// sketch calls show() only in the silences, never while a note
// sounds.

#include <Adafruit_NeoPixel.h>

const byte BUZZER = 9;
const byte DATA = 5;
const byte LEDS = 5;        // pixel 0 is the top LED

Adafruit_NeoPixel bar(LEDS, DATA, NEO_GRB + NEO_KHZ800);

// Note names in lower case: A5 and A6 are already pin names.
enum : byte {
  REST = 0, a5 = 81, b5 = 83, c6 = 84, d6 = 86,
  e6 = 88, f6 = 89, g6 = 91, a6 = 93
};

struct Note { byte key; byte eighths; };

// Korobeiniki, the first eight bars, moved up to A5..A6.
const Note SONG[] = {
  {e6,2},{b5,1},{c6,1},{d6,2},{c6,1},{b5,1},
  {a5,2},{a5,1},{c6,1},{e6,2},{d6,1},{c6,1},
  {b5,3},{c6,1},{d6,2},{e6,2},
  {c6,2},{a5,2},{a5,4},
  {d6,3},{f6,1},{a6,2},{g6,1},{f6,1},
  {e6,3},{c6,1},{e6,2},{d6,1},{c6,1},
  {b5,2},{b5,1},{c6,1},{d6,2},{e6,2},
  {c6,2},{a5,2},{a5,2},{REST,2}
};
const byte COUNT = sizeof(SONG) / sizeof(Note);

const unsigned int EIGHTH_MS = 150;
const byte SOUND_PCT = 90;

// One colour per height, bottom to top: blue to red.
const uint32_t LEVEL_RGB[5] = {
  0x2050FF, 0x00C8D0, 0x30E040, 0xFFC020, 0xFF3020
};

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

// Light the bottom `level` LEDs in that level's colour.
void draw(byte key) {
  bar.clear();
  if (key != REST) {
    byte level = map(key, a5, a6, 1, 5);
    for (byte i = 0; i < level; i++) {
      bar.setPixelColor(LEDS - 1 - i, LEVEL_RGB[level - 1]);
    }
  }
}

void setup() {
  pinMode(BUZZER, OUTPUT);
  digitalWrite(BUZZER, LOW);  // HIGH would hold the coil on
  bar.begin();
  bar.setBrightness(40);      // the TK33 book's: 30 mA at most
  bar.show();
}

void loop() {
  for (byte i = 0; i < COUNT; i++) {
    Note n = SONG[i];
    unsigned long ms = (unsigned long)n.eighths * EIGHTH_MS;
    unsigned long on = ms * SOUND_PCT / 100;

    draw(n.key);
    bar.show();               // silence: nothing for it to disturb
    if (n.key != REST) tone(BUZZER, hz(n.key));
    delay(on);                // the note sounds; no show() here
    noTone(BUZZER);           // stops Timer2, pin LOW

    bar.clear();
    bar.show();               // the gap: nothing is sounding
    delay(ms - on);
  }
  delay(1000);
}

The order inside the loop is the point: draw, show(), tone(), wait, noTone(), clear, show(). Move a show() into the middle of a note and the figure shows what happens to the sound.

View on GitHub · kits/tkbu/light-and-music/Light_And_Music/Light_And_Music.ino @ v1.14

When it does not work

The tune plays but the bar stays dark.

Check the TK33 is in the D4/D5 socket, on D5, and that the sketch says DATA = 5. A bar that has never lit in any lab is more likely its cable or the library: the first-colours lab is the place to prove it alone.

The bar lights but the buzzer is silent.

The TK37 must be in the D8/D9 socket, on D9. Its own lamp glows while a note plays; no glow means the tone is not reaching it.

The notes sound rough or crackle after I added an animation.

Something now calls show() while a note is sounding. show() turns interrupts off for about 150 µs, and tone() needs one at every half-cycle of the note. Update the bar only between notes, or stop the tone first.

The XL LED will not fade while the tune plays.

tone() takes Timer2, which also makes the PWM on D3, where the XL LED is. During a note D3 can only be on or off, and after noTone() it stays dark until the next analogWrite(). Blink it with digitalWrite, or call analogWrite(3, value) again after each noTone() and let it fade only in the gaps.

Where this goes next

The reflective sensor turns the lamp on and off with a wave of the hand.

Lab: a wave switch →

Edit this page — content/books/tkbu/light-and-music.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 →