MUSI6610 · Live Coding: Code as Performance · Week 10 · going beyond the screen

micro:bit ⇄ Strudel

Connect a micro:bit to Strudel over a USB cable: make your patterns light up the LEDs, then use tilt to play the sound. About 20 minutes, then it's yours to bend.

No USB adapter? Try the no-cable version: flash from your phone, connect over Bluetooth. It is experimental.

What you need

Strudel
in Chrome
── text lines ──▶
micro:bit
◀── tilt numbers ──

The whole connection is plain text over USB serial at 115200 baud, one message per line. Strudel sends words like heart; the micro:bit sends numbers like 132. Everything below is a variation on that.

1 Put the program on the micro:bit

One program handles both directions. Pick either route.

Fast route: drag and drop

  1. Plug in the micro:bit. A drive called MICROBIT appears.
  2. Download the program:
    strudel-microbit.hex
  3. Drag the file onto the MICROBIT drive. The light on the back flickers for a few seconds, then the drive reconnects. Done.

Editable route: MakeCode

Use this when you want to change what the micro:bit does (you will, in step 4).

  1. Open makecode.microbit.org and make a new project.
  2. Switch from Blocks to JavaScript at the top of the editor.
  3. Replace everything with the code below.
  4. Click Download and drag the .hex file onto the MICROBIT drive.
  5. Close the MakeCode tab before moving on, so it isn't holding the connection.
micro:bit · MakeCode JavaScript
// micro:bit → Strudel: send left/right tilt 50 times a second
basic.forever(() => {
    serial.writeLine("" + input.acceleration(Dimension.X))
    basic.pause(20)
})

// Strudel → micro:bit: show each message that arrives
serial.onDataReceived(serial.delimiters(Delimiters.NewLine), () => {
    const msg = serial.readUntil(serial.delimiters(Delimiters.NewLine))
    if (msg == "heart") basic.showIcon(IconNames.Heart)
    else if (msg == "skull") basic.showIcon(IconNames.Skull)
    else basic.showString(msg)
})

Nothing visible happens yet: the board is quietly sending tilt numbers and waiting for messages.

2 Pattern → LEDs

Strudel's .serial() sends each event in a pattern out over USB. Open Strudel, paste this, and press Ctrl+Enter.

StrudelOpen in Strudel
// Strudel -> micro:bit LEDs
$: s("bd*2 sd")
$: "<heart skull>".fmap(v => v + '\n').serial()
  1. Chrome pops up a list of serial ports. Choose the one that mentions micro:bit and click Connect.
  2. Press Ctrl+. to stop.

You should get: a drum pattern, and the LEDs switching between a heart and a skull every cycle.

What the line is doing

Single quotes matter. Write '\n', not "\n". Strudel reads double-quoted strings as mini-notation and stops with a parse error.

Any word that isn't heart or skull scrolls across the display as text. Try "<heart skull hi>", then try making the LED pattern and the drum pattern disagree.

3 Tilt → sound

Reload the Strudel page first. Only one piece of code can hold the micro:bit at a time, and step 2 still has it.

Strudel has no built-in serial input, so this snippet reads the port itself and keeps the latest tilt value in window.mbVal, scaled to 0–1. ref() then turns that value into a signal you can plug into any parameter.

StrudelOpen in Strudel
// micro:bit tilt -> filter cutoff
if (!window.mbPort) {
  window.mbPort = await navigator.serial.requestPort()
  await window.mbPort.open({ baudRate: 115200 })
  const reader = window.mbPort.readable
    .pipeThrough(new TextDecoderStream()).getReader()
  let buf = ''
  ;(async () => {
    while (true) {
      const { value, done } = await reader.read()
      if (done) break
      buf += value
      const lines = buf.split('\n')
      buf = lines.pop()
      for (const l of lines) window.mbVal = (parseFloat(l) + 1024) / 2048
    }
  })()
}

$: note("c a f e").s("sawtooth")
  .lpf(ref(() => window.mbVal ?? 0).range(200, 4000))

You should get: a sawtooth melody that gets brighter as you tilt the board to the right and duller to the left.

What to change

4 More sensors

One number is a start. This version sends tilt in two directions plus both buttons, as one comma-separated line such as 132,-40,0,1.

How far this was tested: steps 1–3 were run end to end on a real board. The two blocks in this step were only checked separately: the micro:bit code passes MakeCode's error checking, and the Strudel pattern runs with stand-in values. Expect to debug a little.

Flash this through MakeCode (the editable route in step 1):

micro:bit · MakeCode JavaScript
// Send several sensors as one comma-separated line: x,y,a,b
basic.forever(() => {
    serial.writeLine([
        input.acceleration(Dimension.X),
        input.acceleration(Dimension.Y),
        input.buttonIsPressed(Button.A) ? 1 : 0,
        input.buttonIsPressed(Button.B) ? 1 : 0
    ].join(","))
    basic.pause(20)
})

serial.onDataReceived(serial.delimiters(Delimiters.NewLine), () => {
    const msg = serial.readUntil(serial.delimiters(Delimiters.NewLine))
    if (msg == "heart") basic.showIcon(IconNames.Heart)
    else if (msg == "skull") basic.showIcon(IconNames.Skull)
    else basic.showString(msg)
})

Then reload Strudel and run this. Tilt left/right picks the note, tilt forward/back pans it, and the hi-hats only sound while button A is held.

StrudelOpen in Strudel
// micro:bit x, y, A, B -> window.mb
if (!window.mbPort) {
  window.mbPort = await navigator.serial.requestPort()
  await window.mbPort.open({ baudRate: 115200 })
  const reader = window.mbPort.readable
    .pipeThrough(new TextDecoderStream()).getReader()
  let buf = ''
  ;(async () => {
    while (true) {
      const { value, done } = await reader.read()
      if (done) break
      buf += value
      const lines = buf.split('\n')
      buf = lines.pop()
      for (const l of lines) {
        const [x, y, a, b] = l.split(',').map(Number)
        if (!isNaN(b)) window.mb = { x: (x + 1024) / 2048, y: (y + 1024) / 2048, a, b }
      }
    }
  })()
}
const mb = (k) => ref(() => window.mb?.[k] ?? 0)

$: n(mb('x').range(0, 7).floor().segment(8)).scale("C:minor").s("triangle").pan(mb('y'))
$: s("hh*8").gain(mb('a'))

If you change the parsing inside the if block, reload the page so it runs again.

Other things the board can sense

Add any of these to the list in the micro:bit program, and a matching name on the Strudel side.

MakeCodeGives you
input.acceleration(Dimension.Z)Face up / face down, about −1024 to 1024
input.acceleration(Dimension.Strength)How hard it is being shaken
input.compassHeading()Direction it points, 0–359 (asks you to calibrate first)
input.soundLevel()Microphone loudness, 0–255 (V2 only)
input.logoIsPressed() ? 1 : 0Touch on the gold logo (V2 only)
input.temperature()Degrees Celsius, slow to change
pins.analogReadPin(AnalogPin.P0)0–1023 from anything wired to pin 0: a knob, a light sensor, a banana

5 Étude: do something interesting

You now have an instrument with a body. Some directions to push:

Homework for this week: connect some external device for parameter control. This counts, and so does anything else you can get talking to your language.

Troubleshooting

What you seeWhat to do
No MICROBIT drive appearsSwap the cable; many are charge-only. Try another USB port.
The port list is empty, or has no micro:bitSame as above. Also check you're in Chrome or Edge.
Nothing happens after Ctrl+Enter and the play button shows ...Strudel is waiting for you to choose a port. Look for the port list near the address bar.
"Failed to open serial port" or the port is already in useSomething else has it. Close the MakeCode tab and any other Strudel tabs, then reload.
Step 3 does nothing after doing step 2 (or the reverse)Reload the Strudel page between them.
[mini] parse error on the .serial() lineUse '\n' in single quotes.
Sound plays but tilting changes nothingCheck the board has the program from step 1 on it, then reload and pick the port again.
LEDs lag behind fast patternsEach icon stays up for a moment and text scrolls slowly. Send fewer messages per cycle.
On a school-managed laptop, no port prompt ever appearsSerial devices may be blocked by policy. Pair up with someone on a personal laptop.