MicroPython — buttons A and B on the micro:bit

Lesson 3 of 17 · MicroPython and micro:bit

The micro:bit has two physical buttons — A and B. With them we can make interaction with the user. In this lesson you will learn how to:

  • check whether a button is pressed right now
  • react to a click (one press)
  • combine buttons A and B
  • make a mini project using the buttons

You can try the examples in: ✔ Thonny (Run → Select interpreter → MicroPython BBC micro:bit) ✔ https://python.microbit.org/ (an online editor)


1️⃣ Checking whether a button is pressed (is_pressed)


The method is_pressed() checks whether a button is pressed right now. It returns the value True or False.


from microbit import *

while True:
    # We check the state of button A
    if button_a.is_pressed():
        display.show("A")   # We show the letter A
    else:
        display.clear()     # If it is not pressed – we clear the screen

💡 Important: this code reacts while you HOLD the button.


2️⃣ Reacting to one click (was_pressed)


If we want to react only once per click, we use the method was_pressed().


from microbit import *

while True:
    # If button A has been clicked
    if button_a.was_pressed():
        display.show(Image.HAPPY)
        sleep(500)
        display.clear()

💡 The difference:

  • is_pressed() – reacts while you hold the button
  • was_pressed() – reacts only once per click

3️⃣ Button B


You use button B in the same way:


from microbit import *

while True:
    if button_b.was_pressed():
        display.show("B")
        sleep(500)
        display.clear()

4️⃣ Different reactions for A and B


We can make each button have a different function.


from microbit import *

while True:

    # If A was clicked – we show a heart
    if button_a.was_pressed():
        display.show(Image.HEART)
        sleep(500)

    # If B was clicked – we show a smile
    if button_b.was_pressed():
        display.show(Image.SMILE)
        sleep(500)

    display.clear()

💡 Here we use two separate if conditions. That means both can be executed.


5️⃣ Buttons A and B at the same time


We can check whether both buttons are pressed at the same moment.


from microbit import *

while True:
    if button_a.is_pressed() and button_b.is_pressed():
        display.show(Image.HEART)
    else:
        display.clear()

The operator and means: both conditions must be true.


6️⃣ Example — a counter with button A


Now we make a small project. Every click on button A increases the number by 1.


from microbit import *

number = 0  # the starting value

while True:
    if button_a.was_pressed():
        number = number + 1   # we increase the variable
        display.show(number)
        sleep(500)

This is a real mini project — we use:

  • a variable
  • a button
  • the LED screen

7️⃣ Example — button A increases, B decreases



from microbit import *

number = 0

while True:

    if button_a.was_pressed():
        number += 1   # a short way of writing number = number + 1

    if button_b.was_pressed():
        number -= 1   # we decrease the value

    display.show(number)
    sleep(200)

💡 Now we have full control over the variable with the buttons.


8️⃣ Mini project — a simple menu


Let us make a small menu:

  • Button A → shows the temperature
  • Button B → shows the light level
  • A + B → shows a heart

from microbit import *

while True:

    if button_a.is_pressed() and button_b.is_pressed():
        display.show(Image.HEART)

    elif button_a.was_pressed():
        t = temperature()
        display.scroll("T:" + str(t))

    elif button_b.was_pressed():
        l = display.read_light_level()
        display.scroll("L:" + str(l))

This is already a more serious project because it combines:

  • buttons
  • variables
  • sensors
  • text output

The most common mistakes

  • A forgotten while True — the program runs only once.
  • A forgotten sleep() — the number changes too quickly.
  • Mixing up is_pressed() and was_pressed().

Mini tasks for practice

Task 1 (easy)

When you press A — show the letter A. When you press B — show the letter B.

Task 2

Make a counter that starts from 10 and decreases when button A is pressed.

Task 3

Make a program where:

  • A → shows a smile
  • B → shows a sad face
  • A + B → shows a heart

Task 4 (medium)

Make a counter where:

  • A increases the number
  • B resets the number to 0

Task 5 (challenge)

Make a simple game:

  • A adds 1 point
  • B adds 2 points
  • A + B shows the current score

What have you learned?

  • how to use buttons A and B
  • the difference between is_pressed and was_pressed
  • how to combine conditions
  • how to make interactive projects

Connecting with the page "Commands in MakeCode"

On the page Commands in MakeCode (SR) you can see an overview of the different blocks and commands most often used in programming the micro:bit, such as the commands from:

  • Basic — for text, numbers and basic actions
  • Input — buttons, movements, sensors
  • Music — tones and melodies
  • Logic — conditional decisions
  • Variables — variables

This helps you understand the idea of block commands before you move on to text MicroPython code.

Below are three examples that are analogous to MakeCode commands, but solved in MicroPython.


Example 1 — "Show a name at the start"

In MakeCode you use the block Basic → show string to show a message right away when the program starts. In MicroPython we do it like this:


from microbit import *

# Shows the name once at the beginning
display.scroll("Marko")

✔ This code runs right after the program starts — like the MakeCode block on start → show string.


Example 2 — "Show a heart when shaken"

In MakeCode there is the Input → on shake gesture that reacts to shaking. In MicroPython we can check the gesture in a loop:


from microbit import *

while True:
    if accelerometer.was_gesture("shake"):
        display.show(Image.HEART)
        sleep(600)
        display.clear()

💡 This code detects shaking and then shows a heart — similar to MakeCode's gesture block.


Example 3 — "Show a random number when shaken"

In MakeCode we use the block Math → pick random inside Input → on shake. In MicroPython we do the same with the random module:


from microbit import *
import random

while True:
    if accelerometer.was_gesture("shake"):
        number = random.randint(1, 6)  # a random number 1–6
        display.show(number)
        sleep(800)
        display.clear()

💡 This example makes a digital "die" — every shake gives a new number from 1 to 6. In MakeCode it would be the block "on shake → show number(pick random 1 to 6)".


These MicroPython versions show you how ideas from MakeCode and blocks can be translated into real Python code — and work the same way on your micro:bit.

Mini quiz — MakeCode and MicroPython

Check whether you can recognise which MakeCode block matches the given MicroPython code. Open the quiz and test your knowledge.

Open the quiz

Mini quiz: translate Python into a MakeCode block

1. Which MakeCode block matches this MicroPython code?


display.scroll("Hello")




2. Which block is the equivalent of the following code?


if button_a.is_pressed():
    display.show(Image.HEART)




3. Which MakeCode block matches the following code?


import random
number = random.randint(1, 6)
display.show(number)




4. What does this code do?


if accelerometer.was_gesture("shake"):
    display.show(Image.SMILE)







Mini projects — putting knowledge together (LED + buttons + logic)


These tasks combine everything you have learned so far:

  • the LED matrix (text, images, animations)
  • buttons A and B
  • variables
  • loops and conditions

The tasks are challenging and are meant for independent work.


Mini project 1 — A counter with control

Goal: Make an interactive counter.

Requirements:

  • Button A increases the number by 1
  • Button B decreases the number by 1
  • When both buttons are pressed — the number is reset to 0
  • The current value is shown on the LED matrix

Instructions:

  1. Make a variable number = 0
  2. Use a while True loop
  3. In the loop check the states of the buttons
  4. After every change show the new value
  5. Add a small pause (sleep(200)) to avoid counting several times

Think: how do you stop one press of a button from increasing the number several times?



Mini project 2 — A mini menu (an interactive choice)

Goal: Make a simple menu with three options.

Scenario:

  • Button A changes the option (1 → 2 → 3 → 1)
  • Button B confirms the choice

The options can be:

  • 1 → Show a heart
  • 2 → Show the text "Hello"
  • 3 → Run a short animation

Instructions:

  1. Create a variable option = 1
  2. On button A increase the value of the option
  3. If the option goes above 3 — set it back to 1
  4. On button B perform the action depending on the option
  5. Use if / elif / else

This task introduces the basis for making real interactive systems.



Mini project 3 — A mini game: Guess the number

Goal: Make a simple number guessing game.

Rules:

  • The micro:bit generates a random number from 1 to 5
  • Button A increases your guess
  • Button B confirms the choice
  • If you guess right — show a heart ❤️
  • If you guess wrong — show a sad face and generate a new number

Guidelines:

  1. Use import random
  2. Create a variable for the secret number
  3. Create a variable for the player's choice
  4. Limit the choice to 1–5 (go back to 1 if it goes above 5)
  5. After every round reset the game

This is a combination of:

  • variables
  • conditions
  • buttons
  • the LED display
  • game logic

💡 A challenge for advanced students: Add a counter of tries and show how many times the player tried to guess the number.


Solutions of the mini projects (for teachers)

This part is meant for teachers, for checking and demonstrating possible solutions. It is recommended that students first try on their own.

Show the solutions

Mini project 1 — An interactive counter


from microbit import *

counter = 0  # the starting value

while True:

    # If button A was pressed, increase the counter
    if button_a.was_pressed():
        counter = counter + 1
        display.show(str(counter))  # we turn the number into text

    # If button B was pressed, decrease the counter
    if button_b.was_pressed():
        counter = counter - 1
        display.show(str(counter))

    # If both buttons are pressed at the same time, reset the counter
    if button_a.is_pressed() and button_b.is_pressed():
        counter = 0
        display.show("0")

    sleep(100)

A note for teaching:
Pay attention to the difference between was_pressed() and is_pressed(). was_pressed() reacts only once per press — ideal for counters.


Mini project 2 — A mini menu with confirmation


from microbit import *

option = 1  # the current option (1, 2 or 3)
display.show(option)

while True:
    # Button A – the next option (1 -> 2 -> 3 -> 1)
    if button_a.was_pressed():
        option = option + 1
        if option > 3:
            option = 1
        display.show(option)

    # Button B – confirm the choice
    if button_b.was_pressed():
        if option == 1:
            display.show(Image.HEART)
        elif option == 2:
            display.scroll("Hello")
        else:
            # a short animation: the clock hand goes round
            display.show([Image.CLOCK12, Image.CLOCK3, Image.CLOCK6, Image.CLOCK9], delay=200)
        sleep(1000)
        display.show(option)  # back to the menu

    sleep(100)

A note for teaching:
The variable option remembers where we are in the menu; button A only changes it, and button B performs the action with if / elif / else. The list of images in display.show plays as an animation.


Mini project 3 — Guess the number


from microbit import *
import random

secret = random.randint(1, 5)  # the secret number
guess = 1                      # the player's guess
tries = 0                      # the number of tries (challenge for advanced students)
display.show(guess)

while True:
    # Button A – increase the guess (1 -> 2 -> ... -> 5 -> 1)
    if button_a.was_pressed():
        guess = guess + 1
        if guess > 5:
            guess = 1
        display.show(guess)

    # Button B – confirm the guess
    if button_b.was_pressed():
        tries = tries + 1
        if guess == secret:
            display.show(Image.HEART)
            sleep(1000)
            display.scroll("Tries: " + str(tries))
            tries = 0
        else:
            display.show(Image.SAD)
            sleep(1000)
        # a new round: a new secret number and the guess starts from 1 again
        secret = random.randint(1, 5)
        guess = 1
        display.show(guess)

    sleep(100)

A note for teaching:
The project combines variables, conditions, buttons, the LED display and random numbers. The tries counter is reset only after a correct guess, so the player sees how many tries the whole game took.


Additional example — a menu with icons (A next, B previous)


from microbit import *

# A list of icons (the menu)
icons = [Image.HEART, Image.HAPPY, Image.SAD]
position = 0

display.show(icons[position])

while True:

    # Button A – the next icon
    if button_a.was_pressed():
        position = position + 1
        if position >= len(icons):
            position = 0  # back to the beginning
        display.show(icons[position])

    # Button B – the previous icon
    if button_b.was_pressed():
        position = position - 1
        if position < 0:
            position = len(icons) - 1
        display.show(icons[position])

    sleep(100)

A note for teaching:
This example introduces working with lists and indexes. Students learn how len() works and how to move through a list in a cycle.


Additional example — a reaction test


from microbit import *
import random

while True:

    # A random wait between 2 and 5 seconds
    wait = random.randint(2000, 5000)
    sleep(wait)

    display.show("!")

    start = running_time()  # we record the starting time

    # We wait for the user to press button A
    while not button_a.is_pressed():
        pass

    reaction = running_time() - start  # we calculate the time difference

    display.scroll(str(reaction) + "ms")
    sleep(2000)

A note for teaching:
This project combines:

  • working with variables
  • working with time (running_time())
  • loops
  • random numbers
An excellent example of combining several lessons in one project.

Related: the same topic in MakeCode and other lessons

If you programmed the micro:bit with blocks in grade 5 or 6, compare the blocks with the MicroPython code: