I am experimenting with using custom events to control program flow, and am looking for a way to use “source IDs” that aren’t already in use. The doc provides a link to a page that is claimed to contain a table of reserved IDs, but I don’t see this info there or anyplace else. Is there such a table?
From the doc:
Creating an event is easy - just create a MicroBitEvent with the source and value you need, and the runtime takes care of the rest:
MicroBitEvent(MICROBIT_ID_BUTTON_A, MICROBIT_BUTTON_EVT_CLICK);
Feel free to create your own events lke this too. Just try to avoid using any source ID that is already used by the runtime! See the messageBus page for a complete table of the reserved source IDs.
If you search for “ID” in that page you should find most of them. I think the only other one we use that isn’t listed there is MICROBIT_MELODY_ID = 2000 which is used to produce events for the melody APIs in the music category.
Excellent - thanks! I am thinking that kids might find events a good way to implement some more complicated logic, though I am a bit chagrined that there aren’t built in timer events of any kind?
I am concerned that relying on using “pause” in a background “while(true)” will result in considerable drift, but I need to do some tests on a micro:bit. For example, 25 background “while(true)” loops containing a “pause(100)” that each toggle one of the leds.
edit: I just tried this, and on a physical micro:bit I cannot create 25 background subprograms (X020 No Free Memory), but I can create 12. Also, the drift is a lot more than in the simulator.
let ledBlink = ((x: number, y: number, pauseMS: number) => {
control.inBackground(() => {
while (true) {
led.toggle(x, y)
basic.pause(pauseMS)
}
})
})
// 5x5 doesn’t work but this 4x3 does
for (let ix = 0; ix < 4; ix++) {
for (let iy = 0; iy < 3; iy++) {
ledBlink(ix, iy, 100)
}
}
I think that I will look at creating an extension that will raise an event every x milliseconds.
Also, I wonder if it might be fun for our students to use “music” events and “tempo” to get a nice pulse?
music.onEvent(MusicEvent.MelodyNotePlayed, function () {
led.toggle(4, 4)
})
// tempo of 60 is 1 beat / sec
music.setTempo(60)
// play a rest for 1 sec
music.beginMelody([“r1:4”], MelodyOptions.Forever)
You could hack something together by compensating for drift by looking at current time. Pause on microbit has i think 6ms resolution. It’s 4ms or so on codal targets.
Music.Melody with beat=60 produces a pulse that runs 9ms/sec slow:
let t = 0
let seconds = 0
music.onEvent(MusicEvent.MelodyNotePlayed, function () {
// init t
if (t == 0) {
t = input.runningTime()
}
led.toggle(0, 0)
seconds += 1
//if (seconds % 10 == 0) {
serial.writeNumbers([seconds, input.runningTime() - t])
serial.writeLine("")
//}
t += 1000
})
// tempo of 60 is 1 beat / sec
music.setTempo(60)
// play a rest for 1 sec
music.beginMelody([“r:4”], MelodyOptions.Forever)