Skip to content

User guide

Python guide

Get started coding your micro:bit with Python, one of the world's most popular programming languages

This guide shows you how to use each feature of the micro:bit in Python, with short example code and links to quick, practical projects.

Online editor

Our online Python editor is designed with teachers and learners in mind: you can easily enlarge the text size for sharing on a large screen or whiteboard, download projects as Python text files or .HEX files ready to flash onto a micro:bit. You can also use it in micro:bit classroom, our tool for making whole-class coding sessions easier to manage either remotely or face-to-face.

Using a recent Chrome or Edge browser you can download your programs direct to your micro:bit using webUSB, and interact directly with your micro:bit using the serial interface feature.

Hello, World!

Let's start by making some words and a picture appear on your micro:bit's display. Go to the Python editor and you’ll see this program:

1
2
3
4
5
6
7
8
# Add your Python code here. E.g.
from microbit import *


while True:
    display.scroll('Hello, World!')
    display.show(Image.HEART)
    sleep(2000)

Flash it to your micro:bit by downloading a hex file and transferring it, or flash it by webUSB, and see words and pictures appear on your micro:bit.

You need to be very precise when coding in text-based languages, and Python is no exception. The spaces at the start of lines 6, 7 and 8 are important. These are called indentations, made from four space characters (or one press of the TAB key.)

You’ll notice that Python programs often use a while True: statement. This is an infinite loop like the forever block in MakeCode or Scratch. The instructions indented after while True: form part of the loop: your micro:bit will keep carrying out those instructions as long as it has power.

Any instructions after while True: that are not indented won't be carried out until the loop has finished.

The Set-up page explains more about connecting and transferring code to your micro:bit:

Images

As well as showing a HEART icon, like in the example above, you can use lots more built-in images with Python. Try HAPPY, DUCK or GHOST. You'll find a list of all the built-in images in the micro:bit Python reference guide.

1
2
3
4
5
6
7
8
9
from microbit import *

while True:
    display.show(Image.HAPPY)
    sleep(1000)
    display.show(Image.DUCK)
    sleep(1000)
    display.show(Image.GHOST)
    sleep(1000)

You can also make your own pictures this example. Try different numbers from 0 to 9 to make each LED darker or brighter:

1
2
3
4
5
6
7
from microbit import *

display.show(Image('00300:'
                   '03630:'
                   '36963:'
                   '03630:'
                   '00300'))

These three projects put Python images to use and give you ideas for taking them further:

Light up your micro:bit with love by showing a heart

Make your micro:bit’s heart beat using loops

Buttons

Unlike MakeCode, Python on the micro:bit doesn’t have event blocks like ‘on button A pressed’. Instead, we use the infinite while True: loop to keep checking if a button has been pressed. (Actually, MakeCode programs do the same thing when they run on your micro:bit, but MakeCode hides the infinite loop from you when you’re writing your code.)

Can you guess what this program does? Try it out!

1
2
3
4
5
6
7
from microbit import *

while True:
    if button_a.is_pressed():
        display.show(Image.HAPPY)
    if button_b.is_pressed():
        display.show(Image.SAD)

Here are three projects using button inputs in Python for you to try:

Use your micro:bit to express how you’re feeling

Use buttons to play different tunes

Sensors

The micro:bit has many built-in sensors which you can access in your Python programs to interact with the world around you.

Accelerometer

Gestures

The micro:bit has an accelerometer input sensor built-in which measures physical forces. You can use to make things happen when you move your micro:bit in certain ways, such as when you shake it, drop it, turn it on its side, face up or face down. These movements are called gestures.

1
2
3
4
5
6
7
8
9
10
11
12
from microbit import *

while True:
    if accelerometer.was_gesture('shake'):
        display.show(Image.SILLY)
        sleep(2000)
    if accelerometer.was_gesture('face up'):
        display.show(Image.HAPPY)
    if accelerometer.was_gesture('left'):
        display.show('<')
    if accelerometer.was_gesture('right'):
        display.show('>')

These three makes show you practical and fun uses for gestures:

Shake your micro:bit to make random numbers

Make your own step counter with a micro:bit

Data

You can also get more accurate readings of forces from the micro:bit’s accelerometer in 3 dimensions. This program works as a kind of spirit level, showing a dash if it’s level, or showing arrows to tell you which way it’s leaning if it’s not flat on your desk. It does this by measuring forces just in the x-axis:

1
2
3
4
5
6
7
8
9
from microbit import *

while True:
    reading = accelerometer.get_x()
    if reading > 20:
        display.show(">")
    elif reading < -20:
        display.show("<")
    else: display.show("-")
micro:bit showing X axis going across the front, Y axis going down and up, Z axis going back to front

Here are three programs that use accelerometer data in practical ways:

Explore all accelerometer projects

Temperature

The micro:bit’s processor contains a temperature sensor which you can use in your programs. It’s a useful approximation of the temperature around your micro:bit. This program shows how warm or cold your micro:bit is in °C when you press button A:

1
2
3
4
5
from microbit import *

while True:
    if button_a.was_pressed():
        display.scroll(temperature())
Learn about the temperature sensor

You could use any of these three projects in your classroom or home to monitor and log temperature data:

Make a simple thermometer with your micro:bit

Explore all temperature projects

Light

The LED display on the front of your micro:bit can also detect light, acting as a sensor input as well as an output. Try this simple nightlight project: shine a light on your micro:bit, then cover it or turn out the lights and you should see the display light up.

1
2
3
4
5
6
7
from microbit import *

while True:
    if display.read_light_level() < 100:
        display.show(Image.HEART)
    else: display.clear()
    sleep(2000)

These three practical projects use light sensor data to trigger different outputs:

Create a light that turns on when it’s dark

Make an alarm that goes off when lights go on

Explore all light sensor projects

Compass

Your micro:bit has an input sensor for measuring magnetic fields, which you can use as a compass. This project tells you, once you’ve calibrated it by playing a little game, what compass bearing the top of your micro:bit is pointing towards.

1
2
3
4
5
from microbit import *

while True:
    if button_a.was_pressed():
        display.scroll(str(compass.heading()))
diagram showing a compass rose and micro:bit

Here are three projects using the compass and magnetometer to measure the strength of a magnetic field:

Create a simple compass to show which way is North

The new micro:bit with sound has a gold logo on the front that works as a touch sensor. Here's how to use it an extra input button in your projects:

1
2
3
4
5
from microbit import *

while True:
    if pin_logo.is_touched():
        display.show(Image.SURPRISED)

Explore other ways of using the touch logo in these three projects:

Sound

With Python your micro:bit can make music, express itself - and even speak!

Music

headphones connected to pin 0 and GND pin of micro:bit using crocodile clip leads

Attach headphones to pin 0 and GND on your micro:bit and you can use it to make noise and play music. There are many more built-in tunes to enjoy, try ODE, BLUES or BIRTHDAY - or compose your own. If you have a new micro:bit with sound, the music will also play from the built-in speaker.

1
2
3
4
5
6
from microbit import *
import music

while True:
    if button_a.was_pressed():
        music.play(music.NYAN)

Explore music further with these three makes:

Use buttons to play different tunes

Explore all sound projects

Speech

Your micro:bit can talk when you import the speech module. How could you add speech to improve a project like a compass or thermometer to make it more accessible?

1
2
3
4
from microbit import *
import speech

speech.say('Hello, World')
Speech reference guide

Speaker

Expressive sounds

The new micro:bit with a built-in speaker can also play expressive sounds like giggles, yawns and greet you with a 'hello'. The Sound emotion badge project uses three of them:

1
2
3
4
5
6
7
8
9
10
11
12
13
from microbit import *
import audio

while True:
    if button_a.is_pressed():
        display.show(Image.HAPPY)
        audio.play(Sound.HAPPY)
    if button_b.is_pressed():
        display.show(Image.SAD)
        audio.play(Sound.SAD)
    if pin_logo.is_touched():
        display.show(Image.SURPRISED)
        audio.play(Sound.SPRING)

The full list of expressive sounds includes GIGGLE, HAPPY, HELLO, MYSTERIOUS, SAD, SLIDE, SOARING, SPRING, TWINKLE and YAWN. Try them out and see which ones best add personality to your project.

Muting the speaker

Any sound you make with the micro:bit will come out of the new micro:bit's built-in speaker and pin 0 by default. You can mute the speaker using pin_speaker.disable() and the sound will still go to any headphones connected to pin 0.

Microphone

The new micro:bit has a built-in microphone that can detect loud and quiet events, and also measure how loud a sound is.

This simple Clap hearts program reacts to current loud sounds like claps to animate a heart:

1
2
3
4
5
6
7
8
from microbit import *

while True:
    if microphone.current_event() == SoundEvent.LOUD:
        display.show(Image.HEART)
        sleep(200)
    if microphone.current_event() == SoundEvent.QUIET:
        display.show(Image.HEART_SMALL)

You can set the threshold for loud and quiet events using numbers from 0-255, with 0 being the quietest and 255 the loudest.

You can also check the last sound event rather than the current one, like in this Clap-o-meter program that measures the duration of loud sounds:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from microbit import *
microphone.set_threshold(SoundEvent.LOUD, 150)
start = 0

while True:
    if microphone.was_event(SoundEvent.LOUD):
        start = running_time()
        display.show(Image.TARGET)

    if microphone.was_event(SoundEvent.QUIET):
        if start > 0:
            time = running_time() - start
            start = 0
            display.clear()
            sleep(100)
            display.scroll(time / 1000)

You can use microphone.sound_level() to measure how loud sounds are. This Disco lights program makes the LED display glow brighter the louder sounds picked up by the microphone are:

1
2
3
4
5
6
7
8
9
10
from microbit import *

lights = Image("11111:"
              "11111:"
              "11111:"
              "11111:"
              "11111")

while True:
    display.show(lights * microphone.sound_level())

Explore these and other sound measuring projects in more depth:

Clap your hands to make the micro:bit heart beat

Random numbers

You can add more functions to Python on your micro:bit by importing modules. This program imports the random module so we can make a simple random number generator like dice:

1
2
3
4
5
6
from microbit import *
import random

while True:
    if accelerometer.was_gesture('shake'):
        display.show(random.randint(1, 6))
Random numbers reference guide

Shake your micro:bit to make random numbers

Radio

Two or more micro:bits can communicate wirelessly using the radio module. Flash this program on to two micro:bits and see what happens when you shake each in turn:

1
2
3
4
5
6
7
8
9
10
11
12
from microbit import *
import radio
radio.config(group=23)
radio.on()

while True:
    message = radio.receive()
    if message:
        display.show(Image.DUCK)
    if accelerometer.was_gesture('shake'):
        display.clear()
        radio.send('duck')

There are over a dozen Python projects using radio. Here are three to get you started:

Explore all radio projects

Pins

The strip of golden 'teeth' at the bottom of your micro:bit allow you to connect it to electronics such as switches, sensors, lights, motors - and even other micro:bits.

Get started expanding your micro:bit with these three makes:

Explore all pins projects

Networking

You can communicate securely over wires with two micro:bits (no-one can snoop on your radio messages!) and learn about computer networking.

Nominet have also written a Python version of their book Networking with the micro:bit which covers wired and wireless networking.

Networking reference guide

Adding modules

You can access the micro:bit's Python file system to add Python modules to extend your programs or make using accessories easier.

Learn how to add files and modules

Serial (REPL)

The serial REPL (Read-Evaluate-Print-Loop) feature lets you type Python commands on your computer and run them immediately on your micro:bit without the need to flash a whole program. Connect using webUSB, flash any Python program onto your micro:bit then click on the 'Open Serial' button, and click on the Ctrl-C button.

Type import love into the REPL, press enter and see what happens to your micro:bit!

The serial feature is also helpful for debugging programs as you can use it to read any Python error messages from your micro:bit. Switch to the serial mode and reset your micro:bit and you'll see any error messages on your computer screen as well as scrolling across the micro:bit's display.

Find out more about the REPL

Next steps

Always experiment, always explore, always learn!

Once you get used to the concepts in this guide, read the full Python documentation to learn how to take things further.

micro:bit Python reference guide