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
- A micro:bit (this was tested on a V2).
- A USB data cable. Charge-only cables power the board but the computer never sees it.
- A laptop with Chrome or Edge. Firefox, Safari, phones and tablets won't work, because they don't have Web Serial.
in Chrome
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
- Plug in the micro:bit. A drive called
MICROBITappears. - Download the program:
strudel-microbit.hex - Drag the file onto the
MICROBITdrive. 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).
- Open makecode.microbit.org and make a new project.
- Switch from Blocks to JavaScript at the top of the editor.
- Replace everything with the code below.
- Click Download and drag the
.hexfile onto theMICROBITdrive. - Close the MakeCode tab before moving on, so it isn't holding the connection.
// 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.
// Strudel -> micro:bit LEDs
$: s("bd*2 sd")
$: "<heart skull>".fmap(v => v + '\n').serial()
- Chrome pops up a list of serial ports. Choose the one that mentions micro:bit and click Connect.
- 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
"<heart skull>"is an ordinary mini-notation pattern whose values happen to be words..fmap(v => v + '\n')adds a newline to each word, which is how the micro:bit knows a message has ended..serial()sends each value at the moment it would have sounded.
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.
// 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
- Leave the
if (!window.mbPort) { … }block alone and edit only the pattern at the bottom. You can re-run with Ctrl+Enter as often as you like; the port stays open. - The tilt signal works anywhere a pattern does. Swap
.lpf(…)for.pan(…),.gain(…),.room(…)or.speed(…), and change the numbers in.range()to suit. - Flat is about 0.5. A hard shake can go below 0 or above 1.
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):
// 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.
// 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.
| MakeCode | Gives 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 : 0 | Touch 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:
- Make it playable. A filter sweep is a demo. What mapping would you actually want to perform with for three minutes? Which gestures should be big, and which should be fine?
- Make it a score. Send words to the display instead of icons: instructions to yourself, to a partner, or to the audience.
- Make it a metronome you can argue with. Let the LEDs show one pattern while the sound plays another.
- Hand it to someone else. One person types, another holds the board. Who is performing?
- Close the loop. Steps 2 and 3 can't run together, because each one grabs the port for itself. Write one piece of code that opens the port once and both reads and writes.
- Take the screen away. How much of a set can you play with the laptop lid nearly shut?
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 see | What to do |
|---|---|
No MICROBIT drive appears | Swap the cable; many are charge-only. Try another USB port. |
| The port list is empty, or has no micro:bit | Same 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 use | Something 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() line | Use '\n' in single quotes. |
| Sound plays but tilting changes nothing | Check the board has the program from step 1 on it, then reload and pick the port again. |
| LEDs lag behind fast patterns | Each icon stays up for a moment and text scrolls slowly. Send fewer messages per cycle. |
| On a school-managed laptop, no port prompt ever appears | Serial devices may be blocked by policy. Pair up with someone on a personal laptop. |