how to use the two button switches (buttons) to develop interactive programmes.
REACT TO PRESSING A BUTTON
The micro:bit has two programmable buttons. The left one is addressed with button_a, the right one with button_b.
The function button_a.is_pressed() returns True if the left button is pressed at the moment it is called (analogue button_b.is pressed()).
Your programme waits in an infinite loop until you press button A. Then the centre LED starts to flash with a period of 400 ms for as long as you keep the button pressed.
For better structuring, define a blink() function that switches the centre LED on and off again.
Program:
from microbit import *
def blink():
display.set_pixel(2, 2, 9)
sleep(400)
display.set_pixel(2, 2, 0)
sleep(400)
while True:
if button_a.is_pressed():
blink()
sleep(10)
The seemingly superfluous sleep(10) is important so that you don't waste unnecessary computer resources if the programme doesn't have to do anything other than check whether the button is pressed. In technical jargon, the state of the button is also said to be ‘polled’ in the infinite loop.
REACTING TO THE CLICK OF A BUTTON
Just as you know it from mouse clicks, you want to perform an action with a button click. To do this, you use the button_a.was_pressed() function. This returns True if you have clicked the button at any time. The click is recognised as an event that is registered by the system. Clicking on button B deletes all LEDs.
Program:
from microbit import *
while True:
if button_a.was_pressed():
display.show(Image.SQUARE)
if button_b.was_pressed():
display.clear()
sleep(10)
You can develop interactive programmes that react to a pressed button or a button click. With the function is_pressed() the button must be pressed for it to return True, with the function was_pressed() True is returned if the button has been clicked since the start of the programme or since the last call.
TO SOLVE BY YOURSELF
1.
Programme the buttons as follows:
If you press button A, an arrow pointing to the left (ARROW_W) appears, if you press the right button, an arrow pointing to the right (ARROW_E) appears.
2.
Programme a click counter: Each time you click on button A, the number n, which is initially 0, is increased by one and written out in the terminal window for checking purposes. When button B is clicked, the total number should appear as scrolling text on the display.
Note The scroll() function can only display text. With str(n) you can convert a number into a text.
3.
You simulate throwing a dice with the micro:bit. Each time you click on button A, the image of a random side of the dice is shown on the display.
Note:
The easiest way to create the images is as images, e.g. the four with
img = Image('00000:09090:00000:09090:00000:')