Hands, sound and beams · 19 of 21

Lab: disco lights

The TK27 microphone drives the TK33 WS2812 bar, as a VU meter that lights one LED for each doubling of the loudness, or as a beat flash that changes colour when a sound jumps above the running average. The TK04 button switches between the two.

This lab uses the TK27 microphone, the TK33 WS2812 bar and the TK04 push button. The bar needs the Adafruit NeoPixel library, from the Library Manager.

What goes where

ModuleSocketPinMove
TK27 microphoneD9/A0A0Stays from the last lab
TK33 WS2812 barD4/D5D5Stays where it is
TK04 push buttonD6/D7D7Stays where it is
TK36 active buzzerD10/D11D11May stay: the sketch holds D11 LOW

The TK36's board has nothing holding its transistor off, so a pin left as an input could let it sound. The sketch makes D11 an output and drives it LOW.

Loudness, measured as in the alarm

Each 30 ms the sketch reads A0 as fast as it can and keeps the highest and lowest reading: the swing. It takes off the biggest swing the quiet room gave during the first second, so silence is zero. A 30 ms window holds two cycles of the microphone's lowest notes, near 75 Hz, and gives the bar more than thirty updates a second.

One LED per doubling

One LED per doubling
160 mV above quiet
Swing above the quiet room160 mV
doublings
3 of 5
equal steps
1 of 5
a step is
6 dB
3 lit against 1. Each doubling of the swing is the same step to the ear, so it gets one LED; equal steps crowd the quiet half into the first LED.

Slide from talking to a clap. On equal steps the first LED waits for 128 mV, so talking and a raised voice look the same and the whole bar is spent on claps. On doublings each LED needs twice the swing of the one below: 40, 80, 160, 320 and 640 mV. Twice the swing is twice the sound pressure, about 6 dB, and that is the same step to the ear however loud the sound already is. So a voice moves the bar and a clap still fills it.

The sounds under the slider come from the microphone book's model, which borrows another capsule's sensitivity: they show sizes, not measurements.

The meter rises at once and falls one LED every 80 ms. Without the slow fall it flickers with every window; with it, a full bar takes 0.4 s to empty, and reads as a level.

The beat flash

A beat is a window that stands out from the recent past. The sketch keeps a running average, average += (loud - average) / 8, which follows the last quarter second or so of 30 ms windows. A window more than twice that, and more than 100 mV, is a beat: the whole bar flashes the next colour in the list for 60 ms. After a beat the sketch waits 150 ms before it can flash again, so one drum hit is one flash.

The sketch

meter() counts the steps the loudness passes and compares that with shown, the LEDs on the bar now: up at once, down one step per FALL_MS. It writes from pixel 4 upwards, because pixel 0 is LED1, the LED the data reaches first, and on the bar as its book draws it that is the top. So the meter rises from the bottom.

pressed() reports a rising edge on D7 when the reading has been different for more than 30 ms since the last change, which ignores the contacts' bounce. The TK04 has its own pull-down, so the pin is a plain INPUT.

bar.setBrightness(40) keeps the current down: each LED draws 12 mA per colour at full brightness, 180 mA for the bar all white, and 40 of 255 scales that to about 30 mA.

Make it yours

  • Add a third mode: a dot that sits at the loudness instead of a bar, or one colour per step that changes with the beat.
  • Put the TK07 knob in the A0/A1 socket in place of the TK57 and let it set STEP_MV's base, so the meter can be tuned to the room.
  • Drive the XL LED on D3 with analogWrite from the loudness as well.

The code

Disco_Lights.ino

Measures the quiet room for a second, then measures the swing of every 30 ms window less the quiet one. In VU mode that lights one LED per doubling, 40 to 640 mV, and the bar falls back one LED every 80 ms. In beat mode a window that swings twice the running average, and at least 100 mV, flashes the whole bar in the next colour.

/*
  Disco lights                        TinkerBlock UNO kit, /manuals/tkbu

  The TK27 microphone drives the TK33 WS2812 bar, two ways. The TK04
  button switches between them.

  VU meter: one LED for each doubling of the loudness above the quiet
  room (40, 80, 160, 320, 640 mV of swing), green to red, rising from
  LED5 to LED1. The bar falls back one LED every 80 ms, so it reads
  as a level rather than a flicker.

  Beat flash: the whole bar flashes a new colour when a 30 ms window
  swings twice the running average, then waits 150 ms before it can
  flash again.

  Loudness is the swing: the highest minus the lowest reading over
  one window, less the swing the quiet room had at start-up.

  Wiring, on the TinkerBlock UNO shield:
    TK27 microphone    in the D9/A0 socket, so it is on A0
                       (it takes the TK07 knob's place)
    TK33 WS2812 bar    in the D4/D5 socket, so it is on D5
    TK04 push button   in the D6/D7 socket, so it is on D7
    TK36 buzzer        may stay in the D10/D11 socket: D11 is
                       held LOW, so it stays silent
  A module is on the second pin printed beside its socket.

  Arduino IDE
    Tools > Board: Arduino Uno
    Tools > Port:  the CH340 port
    Library: Adafruit NeoPixel (1.15.5), from the Library Manager.
    Serial Monitor at 115200. Keep quiet for the first second.
*/

#include <Adafruit_NeoPixel.h>

const int MIC_PIN = A0;     // TK27 SIGNAL
const int BAR_PIN = 5;      // TK33 DATA
const int BUTTON_PIN = 7;   // TK04 SIGNAL: HIGH while pressed
const int BUZZER_PIN = 11;  // TK36, if plugged in: kept quiet
const int LEDS = 5;

const float MV_PER_COUNT = 5000.0 / 1024;
const unsigned long WINDOW_MS = 30;
const unsigned long LEARN_MS = 1000;
const float STEP_MV[LEDS] = { 40, 80, 160, 320, 640 };
const unsigned long FALL_MS = 80;     // the meter falls this slowly
const float BEAT_RATIO = 2.0;         // a beat: twice the average
const float BEAT_FLOOR_MV = 100;      // and at least this loud
const unsigned long BEAT_GAP_MS = 150;
const unsigned long FLASH_MS = 60;

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

// LED5 (bottom) to LED1 (top): green, green, yellow, orange, red.
const uint32_t METER[LEDS] = {
  0x00FF00, 0x00FF00, 0xFFC000, 0xFF6000, 0xFF0000
};
const uint32_t FLASH[] = {
  0xFF0040, 0x00FFFF, 0xFFFF00, 0x8000FF, 0x00FF40, 0xFFFFFF
};
const int FLASHES = sizeof(FLASH) / sizeof(FLASH[0]);

bool vuMode = true;
float quietMv;
int shown = 0;               // LEDs the meter shows now
unsigned long lastFall = 0;
float average = 0;           // running average loudness, beat mode
unsigned long lastBeat = 0;
int flashColour = 0;
bool lastButton = LOW;
unsigned long buttonChanged = 0;

// Highest minus lowest reading over one window, in mV.
float swingMv() {
  int lo = 1023;
  int hi = 0;
  unsigned long start = millis();
  while (millis() - start < WINDOW_MS) {
    int r = analogRead(MIC_PIN);
    if (r < lo) lo = r;
    if (r > hi) hi = r;
  }
  return (hi - lo) * MV_PER_COUNT;
}

void fill(uint32_t c) {
  for (int i = 0; i < LEDS; i++) bar.setPixelColor(i, c);
  bar.show();
}

// Pressed: a clean rising edge, 30 ms after the last change.
bool pressed() {
  bool b = digitalRead(BUTTON_PIN);
  if (b != lastButton && millis() - buttonChanged > 30) {
    lastButton = b;
    buttonChanged = millis();
    return b == HIGH;
  }
  return false;
}

void meter(float loud) {
  int lit = 0;
  while (lit < LEDS && loud >= STEP_MV[lit]) lit++;
  unsigned long now = millis();
  if (lit > shown) {
    shown = lit;                  // up at once
    lastFall = now;
  } else if (shown > 0 && now - lastFall >= FALL_MS) {
    shown--;                      // down one step at a time
    lastFall = now;
  }
  for (int i = 0; i < LEDS; i++) {
    // Pixel 0 is LED1, the top: the meter starts at pixel 4.
    bar.setPixelColor(LEDS - 1 - i, i < shown ? METER[i] : 0);
  }
  bar.show();
}

void beat(float loud) {
  unsigned long now = millis();
  if (loud > BEAT_RATIO * average && loud > BEAT_FLOOR_MV &&
      now - lastBeat >= BEAT_GAP_MS) {
    lastBeat = now;
    flashColour = (flashColour + 1) % FLASHES;
    fill(FLASH[flashColour]);
  } else if (now - lastBeat >= FLASH_MS) {
    fill(0);
  }
  average += (loud - average) / 8;  // about the last quarter second
}

void setup() {
  Serial.begin(115200);
  pinMode(BUTTON_PIN, INPUT);   // the TK04 has its own pull-down
  pinMode(BUZZER_PIN, OUTPUT);  // an input would float its base
  digitalWrite(BUZZER_PIN, LOW);
  bar.begin();
  bar.setBrightness(40);        // of 255: about 30 mA all white
  bar.show();

  Serial.println(F("Measuring the quiet room. Keep quiet..."));
  quietMv = 0;
  unsigned long start = millis();
  while (millis() - start < LEARN_MS) {
    float s = swingMv();
    if (s > quietMv) quietMv = s;
  }
  Serial.print(F("Quiet swing "));
  Serial.print(quietMv, 0);
  Serial.println(F(" mV. VU meter; press the button for beats."));
}

void loop() {
  if (pressed()) {
    vuMode = !vuMode;
    shown = 0;
    fill(0);
    Serial.println(vuMode ? F("VU meter") : F("Beat flash"));
  }
  float loud = swingMv() - quietMv;
  if (loud < 0) loud = 0;
  if (vuMode) meter(loud);
  else beat(loud);
}

Install Adafruit NeoPixel from the Library Manager first; the sketch was compiled with 1.15.5. Brightness is 40 of 255, about 30 mA with all five LEDs white. Keep quiet for the first second.

View on GitHub · kits/tkbu/disco-lights/Disco_Lights/Disco_Lights.ino @ v1.14

When it does not work

The meter barely moves to music.

The microphone hears best from about 75 Hz to 1 kHz and is built for claps and knocks, not quiet sound. Put it close to the speaker, or lower the steps: halve every value in STEP_MV.

The bar sits at one or two LEDs in silence.

The room was quieter during the first second than it is now, or the desk is carrying vibration. Press reset in the conditions you want to measure against, and keep the microphone block off the speaker's surface.

Beat mode flashes on everything, or on nothing.

BEAT_RATIO sets how much a beat has to stand out from the average. Raise it to 3 for busy music that flashes constantly; lower it to 1.5, or BEAT_FLOOR_MV to 50, for quiet music that never does.

Compiling fails on Adafruit_NeoPixel.h.

The library is not installed. Open the Library Manager, search for Adafruit NeoPixel, and install it. The TK33 bar's own book uses the same library, so one install covers both.

Where this goes next

The infrared pair across a doorway, and the I2C socket's pull-up on the transmitter's pin.

Lab: an invisible beam alarm →

Edit this page — content/books/tkbu/disco-lights.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 →