YOU LEARN HERE... |
how to use the buttons to develop interactive programs. |
CHECK IF A BUTTON IS PRESSED |
|
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) In the main loop the state of the button is "polled" in an endless loop. sleep(10) is important in order to prevent the waste of computer resources when the button is not pressed. |
CHECK IF THE BUTTON WAS HIT |
Program: from microbit import * while True: if button_a.was_pressed(): display.show(Image.SQUARE) if button_b.was_pressed(): display.clear() sleep(10) The wrong behavior has a simple explanation: Since the program spends most of the time in the blinking function, it is improbable that it just calls button_a.is_pressed() at the time you click the button. To overcome this failure, you must use button_a.was_pressed(). This function "remembers" that you clicked the button anytime since the last call and returns True, if this is the case. The click is perceived as an event that is registered by the system even if your program is doing something else at the the time the button is down. The corrected program responds to clicks as desired.Program: from microbit import * def blink(x, y): display.set_pixel(x, y, 9) sleep(1000) display.set_pixel(x, y, 0) sleep(1000) while True: if button_a.was_pressed(): display.show(Image.SQUARE) sleep(1000) display.clear() blink(2, 2) sleep(10) |
MEMO |
You can develop interactive programs which respond to a button that is hold down or a button that was clicked. is_pressed() returns True, if the button is pressed at the moment of the function call. was_pressed() returns True, if the button has been clicked since the start of the program or since the last call. |
EXERCISES |
|
Images defined in the Image class:
HEART,
HEART_SMALL,
HAPPY,
SMILE,
SAD,
CONFUSED,
ANGRY,
ASLEEP,
SURPRISED,
SILLY,
FABULOUS,
MEH,
YES,
NO,
CLOCK12, CLOCK11, CLOCK10, CLOCK9, CLOCK8,
CLOCK7, CLOCK6, CLOCK5, CLOCK4, CLOCK3, CLOCK2, CLOCK1,
ARROW_N,
ARROW_NE, ARROW_E, ARROW_SE, ARROW_S, ARROW_SW, ARROW_W, ARROW_NW,
TRIANGLE,
TRIANGLE_LEFT,
CHESSBOARD,
DIAMOND,
DIAMOND_SMALL,
SQUARE,
SQUARE_SMALL,
RABBIT,
COW,
MUSIC_CROTCHET,
MUSIC_QUAVER,
MUSIC_QUAVERS,
PITCHFORK,
XMAS,
PACMAN,
TARGET,
TSHIRT,
ROLLERSKATE,
DUCK,
HOUSE,
TORTOISE,
BUTTERFLY,
STICKFIGURE,
GHOST,
SWORD,
GIRAFFE,
SKULL,
SNAKE