You are on page 1of 28

First steps User guide BBC micro:bit in school Home learning

User guide Share

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:

1 # Add your Python code here. E.g.

2 from microbit import *

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:

Visit the editor Set up 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 from microbit import *

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'))

Images reference guide Learn about the LEDs

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!

1 from microbit import *


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)

Buttons reference guide Learn about the buttons

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.

1 from microbit import *

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('>')

Gestures reference guide Learn about the accelerometer

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

Dice
Shake your micro:bit to make
random numbers
Beginner
Beginner

Rock, paper, scissors


Recreate a classic game with
two micro:bits
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:

1 from microbit import *

3 while True:

4 reading = accelerometer.get_x()

5 if reading > 20:


5 if reading > 20:

6 display.show(">")

7 elif reading < -20:

8 display.show("<")

9 else: display.show("-")

Movement reference guide Learn about the accelerometer

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

Sensitive step counter


Make a more accurate step-
counter
Intermediate
Animal tracker
Build a prototype radio animal
tracker
Beginner

Python data logger


Create a wireless data logger
with Python
Advanced

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 from microbit import *

3 while True:

4 if button a.was pressed():


4 if button_a.was_pressed():

5 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:

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

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 from microbit import *

3 while True:

4 if display.read_light_level() < 100:

5 display.show(Image.HEART)

6 else: display.clear()

7 sleep(2000)

Display reference guide Learn about the light sensor

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

Make your micro:bit light up


Beginner

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

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 from microbit import *

3 while True:

4 if button_a.was_pressed():

5 display.scroll(str(compass.heading()))

Direction reference guide Learn about the compass

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

Radio door alarm


Make your own micro:bit
wireless door alarm
Advanced

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:

1 from microbit import *

3 while True:

4 if pin_logo.is_touched():

5 display.show(Image.SURPRISED)

Learn about the touch logo

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

Touch emotion badge

Add an extra emotion with


touch
Beginner

micro:bit pet

Code your own electronic pet

Intermediate
Touch stopwatch

Make a stopwatch using the


touch logo
Intermediate

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.

1 from microbit import *

2 import music

4 while True:

5 if button_a.was_pressed():

6 music.play(music.NYAN)

Music reference guide Learn about micro:bit sound

Explore music further with these three makes:

Make some noise


Connect headphones or
speakers to make noise
Intermediate

Jukebox
Use buttons to play different
tunes
Intermediate

Frè - re Jac - ques

è
Frère Jacques loops
Program your micro:bit to play
a tune
Intermediate

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 from microbit import *

2 import speech

4 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 from microbit import *


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)

Learn about the speaker


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.

Sound emotion badge

Express yourself with sound

Beginner

Sensory toy

Make a multi-sensory toy

Beginner
micro:bit pet
Code your own electronic pet

Intermediate

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 from microbit import *

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:

1 from microbit import *

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:

12 time = running_time() - start

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:

1 from microbit import *

3 lights = Image("11111:"

4 "11111:"

5 "11111:"

6 "11111:"

7 "11111")

9 while True:

10 display.show(lights * microphone.sound_level())

11

Learn about the microphone

Explore these and other sound measuring projects in more depth:


Clap hearts
Clap your hands to make the
micro:bit heart beat
Beginner

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))

Random numbers reference guide

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:

1 from microbit import *


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

Radio reference guide Learn about micro:bit radio

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

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.

Pins reference guide Learn about the pins

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

Guitar 1 - touch tunes


Create and play a micro:bit
guitar
Advanced

Reaction game
Make a 2-player reaction game

Advanced

PIR movement alarm


Make a wireless intruder alarm
to detect movement
Advanced

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
g
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

2021 virtual micro:bit conference

Submit your proposal


About us Get involved
Who we are Become a reseller
Our mission Submit your accessory
Our partners Developer community
Board Be a beta tester
Meet the team Be a micro:bit champion
Work for us Translate the website
Sign up to our newsletter
Join us

Follow us

© Micro:bit Educational Foundation Help & support Contact us


Safeguarding Privacy policy Terms of use

You might also like