LED Display & Buttons on BBC micro:bit

LED Display & Buttons on BBC micro:bit

Show text, images, and animations on the 5G—5 LED grid and respond to buttons.

The 5G—5 LED Matrix

The micro:bit has a grid of 25 red LEDs arranged in 5 rows and 5 columns. You address individual pixels by (x, y) where (0,0) is the top-left and (4,4) is the bottom-right.

Brightness can be set from 0 (off) to 9 (full brightness).

Displaying Text

from microbit import *

# Scroll a string across the display
display.scroll("Hello, World!")

# Scroll with custom speed (delay in ms per frame, default 150)
display.scroll("Fast!", delay=50)

# Show a single character
display.show("A")

# Show a number
display.show(42)

display.scroll() moves text from right to left. display.show() shows a single character or image.

Built-in Images

MicroPython has dozens of pre-defined images:

display.show(Image.HEART)
display.show(Image.HAPPY)
display.show(Image.SAD)
display.show(Image.YES)
display.show(Image.NO)
display.show(Image.ARROW_N)   # Arrow pointing north

[Full image list: Image.ALL_CLOCKS, Image.DUCK, Image.GIRAFFE, Image.SKULL, and many more]

Custom Images

Define your own image with a 5G—5 brightness grid:

boat = Image("05050:"
             "05050:"
             "05050:"
             "99999:"
             "09990")
display.show(boat)

Each row is 5 digits (0߀“9 brightness), separated by colons.

Animations

Pass a list of images to display.show() with loop=True:

display.show([Image.ARROW_N, Image.ARROW_NE, Image.ARROW_E,
              Image.ARROW_SE, Image.ARROW_S], delay=200, loop=True)

Or create a clock-spin animation using Image.ALL_CLOCKS:

display.show(Image.ALL_CLOCKS, delay=100, loop=True)

Individual Pixel Control

display.set_pixel(2, 2, 9)   # Centre pixel at full brightness
display.set_pixel(0, 0, 0)   # Top-left off

x = display.get_pixel(2, 2)  # Returns brightness 0߀“9

display.clear()               # Turn off all LEDs

Button A and Button B

The micro:bit has two physical buttons labelled A and B. You can check if they are pressed or have been pressed since last check:

from microbit import *

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

Button Event Methods

Method Returns Description
button_a.is_pressed() bool True while button is held
button_a.was_pressed() bool True if pressed since last check (clears flag)
button_a.get_presses() int Count of presses since last call (resets count)

Touch Logo (V2)

The golden logo on the front of V2 is a touch sensor:

if pin_logo.is_touched():
    display.show(Image.HEART)

Combining Display and Buttons

from microbit import *

count = 0

while True:
    if button_a.was_pressed():
        count += 1
    if button_b.was_pressed():
        count = 0
    display.show(count)
    sleep(100)