In order to be able to detect button pressed events, we can use the onButtonPressed function of the input namespace.
This function receives as parameters the button and a handling function that is executed when the click event on that button is detected.
In our board we have two buttons that we can use as user inputs, which are defined as button A and button B. Button A is the one on the left, above pin 0. Button B is the one on the right, above the GND pin.
So, for the first argument of the onButtonPressed function, the buttons are defined in the Button enum. For button A we use Button.A and for button B we use Button.B.
Note that although we also have functions to check the state of each button (pressed or not) at a given time, we would need to use a technique called polling, which corresponds to periodically check the button of the state.
Although in certain program architectures it is feasible to do it, it is much more efficient to use a callback function (like we are doing) that is triggered when the event occurs, leaving the CPU free to do other tasks when no click event is detected.
Our arrow function will simply toggle a specific LED when it executes. You can check more about LED controlling here. We will toggle the LED at coordinates (0,0) on a click on button A, and the LED at coordinates (4,0) on a click on button B.
To test the code, simply click the download button on the bottom left corner and drag the file to the micro:bit driver that should be available on your computer. After the procedure finishes, the code automatically runs and you can test it by clicking the buttons.
As usual, you can also do the tests on the simulation mode. Figure 1 shows both LEDs in the on state in simulation mode, resulting from pressing the buttons.
Figure 1 – LEDs toggled from button clicks, on simulation mode.
NOTE: This article is written by Nuno Santos who is an kindly Electronics and Computers Engineer. live in Lisbon, Portugal. you could check the original article here. He had written many useful tutorials and projects about ESP32, ESP8266, microbit, If you are interested, you could check his blog to know more.