Home MIcro:bit Microbit button example

Microbit button example

by shedboy71

Table of Contents

Buttons

There are two buttons on the board, called button_a and button_b.
Attributes

button_a
A Button instance representing the left button.

button_b
A Button instance representing the right button.

Classes

class Button
Represents a button.

Note
This class is not actually available to the user, it is only used by the two button instances, which are provided already initialized.

is_pressed()
Returns True if the specified button button is pressed, and False otherwise.

was_pressed()
Returns True or False to indicate if the button was pressed since the device started or the last time this method was called.

get_presses()
Returns the running total of button presses, and resets this total to zero before returning.

Code

Here is an example written in python using the Mu editor

[codesyntax lang=”python”]

from microbit import *

while True:
    if button_a.is_pressed():
        display.show("A")
    elif button_b.is_pressed():
        display.show("B")
    else:
        display.clear()

[/codesyntax]

 

Here is an example using the Block Editor

You may also like