Search code examples
micropythonmit-scratchbbc-microbit

Is it possible to wait for either button A or button B?


This is code that waits for an event coming from button A.

control.waitForEvent(Button.A, EventBusValue.MICROBIT_EVT_ANY)

I want to wait for either button A OR button B to be pressed.

Is this possible?

EDIT

I know that in Scratch this is possible with something like button.any, also the above code is written in microjavascript, but it is written similarly in micropython, so maybe someone from this field can also help. Thank you.


Solution

  • The best way I could do it was with common function for A nad B, to be called on events of button pressed, like:

    input.onButtonPressed(Button.A, function () {
        qAndA(true)
    })
    input.onButtonPressed(Button.B, function () {
        qAndA(false)
    })
    

    The true and false are not the best implementations but to know which button was pressed, I needed to pass the true for A and false for B.

    This was required in my case, because I was writing test and later in this function I would compare the button pressed and the actual correct answer. The function (without my full implementation) goes something like this:

    function qAndA(aOrB: boolean) {
        if (text_list.length == 0) {
            basic.showNumber(count)
            basic.pause(2000)
            basic.showLeds(`
                # # # # #
                . . # . .
                . . # . .
                . . # . .
                . . # . .
                `)
        }
        if (text_list[0] == Q1 && aOrB == true) {
            ...
        }
    }