Professional Documents
Culture Documents
Select section
Python 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:
5 while True:
5 while True:
6 display.scroll('Hello, World!')
7 display.show(Image.HEART)
8 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.
3 while True:
4 display.show(Image.HAPPY)
5 sleep(1000)
6 display.show(Image.DUCK)
7 sleep(1000)
8 display.show(Image.GHOST)
9 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 from microbit import *
3 display.show(Image('00300:'
4 '03630:'
5 '36963:'
6 '03630:'
7 '00300'))
These three projects put Python images to use and give you ideas for taking them
further:
Heart
Light up your micro:bit with
love by showing a heart
Beginner
Beating heart
Make your micro:bit’s heart
beat using loops
Beginner
Beginner
Animated animals
Animate your own animals on
the micro:bit display
Beginner
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!
3 while True:
4 if button_a.is_pressed():
5 display.show(Image.HAPPY)
6 if button_b.is_pressed():
7 display.show(Image.SAD)
Here are three projects using button inputs in Python for you to try:
Emotion badge
Use your micro:bit to express
how you’re feeling
Beginner
Flashing emotions
Make flashing happy and sad
faces
Beginner
Jukebox
Use buttons to play different
tunes
Intermediate
Sensors
The micro:bit has many built in sensors which you can access in your Python programs
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.
3 while True:
4 if accelerometer.was_gesture('shake'):
5 display.show(Image.SILLY)
6 sleep(2000)
7 if accelerometer.was_gesture('face up'):
8 display.show(Image.HAPPY)
9 if accelerometer.was_gesture('left'):
10 display.show('<')
11 if accelerometer.was_gesture('right'):
12 display.show('>')
These three makes show you practical and fun uses for gestures:
Dice
Shake your micro:bit to make
random numbers
Beginner
Beginner
Step counter
Make your own step counter
with a micro:bit
Beginner
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:
3 while True:
4 reading = accelerometer.get_x()
6 display.show(">")
8 display.show("<")
9 else: display.show("-")
Here are three programs that use accelerometer data in practical ways:
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:
3 while True:
5 display.scroll(temperature())
You could use any of these three projects in your classroom or home to monitor and log
temperature data:
Thermometer
Make a simple thermometer
with your micro:bit
Beginner
Max-min thermometer
Track high and low
temperatures with your…
Intermediate
Indoor-outdoor
thermometer
Sense how warm or cold it is
outside
Intermediate
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.
3 while True:
5 display.show(Image.HEART)
6 else: display.clear()
7 sleep(2000)
These three practical projects use light sensor data to trigger different outputs:
Sunlight sensor
Nightlight
Create a light that turns on
when it’s dark
Intermediate
Light alarm
Make an alarm that goes off
when lights go on
Advanced
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.
3 while True:
4 if button_a.was_pressed():
5 display.scroll(str(compass.heading()))
Here are three projects using the compass and magnetometer to measure the strength
of a magnetic field:
Compass bearing
Turn your micro:bit into a
u you c o b oa
simple compass
Beginner
Compass North
Create a simple compass to
show which way is North
Intermediate
Touch logo
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:
3 while True:
4 if pin_logo.is_touched():
5 display.show(Image.SURPRISED)
Explore other ways of using the touch logo in these three projects:
micro:bit pet
Intermediate
Touch stopwatch
Sound
With Python your micro:bit can make music, express itself - and even speak!
Music
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.
2 import music
4 while True:
5 if button_a.was_pressed():
6 music.play(music.NYAN)
Jukebox
Use buttons to play different
tunes
Intermediate
è
Frère Jacques loops
Program your micro:bit to play
a tune
Intermediate
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?
2 import speech
4 speech.say('Hello, World')
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:
2 import audio
4 while True:
5 if button_a.is_pressed():
6 display.show(Image.HAPPY)
7 audio.play(Sound.HAPPY)
8 if button_b.is_pressed():
9 display.show(Image.SAD)
10 audio.play(Sound.SAD)
11 if pin_logo.is_touched():
12 display.show(Image.SURPRISED)
13 di l (S d SPRING)
13 audio.play(Sound.SPRING)
Beginner
Sensory toy
Beginner
micro:bit pet
Code your own electronic pet
Intermediate
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:
3 while True:
4 if microphone.current_event() == SoundEvent.LOUD:
5 display.show(Image.HEART)
6 sleep(200)
7 if microphone.current_event() == SoundEvent.QUIET:
8 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:
2 microphone.set_threshold(SoundEvent.LOUD, 150)
3 start = 0
4
4
5 while True:
6 if microphone.was_event(SoundEvent.LOUD):
7 start = running_time()
8 display.show(Image.TARGET)
10 if microphone.was_event(SoundEvent.QUIET):
11 if start > 0:
13 start = 0
14 display.clear()
15 sleep(100)
16 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:
3 lights = Image("11111:"
4 "11111:"
5 "11111:"
6 "11111:"
7 "11111")
9 while True:
10 display.show(lights * microphone.sound_level())
11
Disco lights
Make lights flash to the rhythm
Beginner
Sound logger
Measure noise levels around
you
Intermediate
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 from microbit import *
2 import random
4 while True:
5 if accelerometer.was_gesture('shake'):
6 display.show(random.randint(1, 6))
Dice
Shake your micro:bit to make
random numbers
Beginner
Magic 8-ball
Make a toy to tell your fortune
Beginner
Rock, paper, scissors
Recreate a classic game with
two micro:bits
Beginner
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:
2 import radio
3 radio.config(group=23)
4 radio.on()
6 while True:
7 message = radio.receive()
8 if message:
9 display.show(Image.DUCK)
10 if accelerometer.was_gesture('shake'):
11 display.clear()
12 radio.send('duck')
13
There are over a dozen Python projects using radio. Here are three to get you started:
Teleporting duck
Teleport a duck between
micro:bits using radio
Intermediate
Proximity beacon
Sense when something is
getting close
Advanced
Tell me a secret
Swap secrets with a friend
using radio
Intermediate
Reaction game
Make a 2-player reaction game
Advanced
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.
Adding modules
g
You can access the micro:bit's Python file system to add Python modules to extend your
programs or make using accessories easier.
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.
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.
Follow us