Deutsch English |
The micro:bit has two programmable buttons, which make it possible to interact with the program execution. The left one is referenced by button_a, the right one by button_b. The function button_a.is_pressed() returns True if the left button is pressed at the moment of the call (analog for button_b_is pressed()). |
Example 1: Responding to pressing a button
The program waits in an endless loop until button A or button B is pressed. Then the right or left LED starts flashing with a period of 1s as long as the button is hold down.
# Mr4a.py from microbit import * from mbrobot import * #from mbrobot_plusV2 import * def blink(): setLED(1) delay(500) setLED(0) delay(500) while True: if button_a.is_pressed(): blink() delay(100) |
Explanations of the program code:
def blink(led): It makes sense to write a function for the flashing of an LED and then to call it with the parameter leftLED or rightLED | |
if button_a.is_pressed() Returns True while the button is pressed |
Example 2: Responding to the click of a button
In an endless while loop you flash the right and left LED with a period of 1 s.. A click on the button A or B interrupts the blinking and a sound is played.
# Mr4b.py from microbit import * from mbrobot import * from music import * def blink(): ledLeft.write_digital(1) ledRight.write_digital(1) delay(500) ledLeft.write_digital(0) ledRight.write_digital(0) delay(500) while True: if button_a.was_pressed(): play(JUMP_UP) if button_b.was_pressed(): play(JUMP_DOWN) blink() |
Explanations of the program code:
if button_a.was_pressed() Returns True if the button has been pressed since the last call. | |
from music import *: Imports the module music to play sounds | |
play(JUMP_UP): Plays a short song. Some songs are included in the distribution of TigerJython (see Doc) |
Example 3: A moving robot is stopped with a button click
For moving robots it is advantageous to use a while loop which is repeated until a button is pressed.
As long as button A was not pressed, the robot repeats the commands in the while loop. The button click ends the loop and the program continues to the stop() command.
# Mr4c.py from microbit import * from mbrobot import * setSpeed(15) forward() while not button_a.was_pressed(): d = getDistance() if d < 10: backward() delay(1000) forward() delay(200) stop() |
Explanations of the program code:
|
Exercises: |
1) |
|
2) |
|
3) |
|