Cheat Sheet
Microbit Playground’s cheat sheet has snippets of python code to get you started.
import
modules must be imported at the beginning of the program.
from microbit import *

from microbit import *
  display.show(Image.HAPPY)

First line of code imports the microbit module.

import random

for using random numbers

from microbit import *
import random

random_number = random.randrange(0,10)
display.scroll(str(random_number))

Scroll a random number between 0 and 10 on the microbit’s display.

import neopixel

from microbit import *
import neopixel

neopixels = neopixel.NeoPixel(pin0, 12)

neopixels[0] = (255,150,0)
neopixels[1] = (0,255,0)
neopixels[-1] = (255,0,0)

neopixels.show() # Light the LEDs

for using a neopixel (a separate multicoloured light)

import music

from microbit import *
import music

for making sound (speaker needed)

import speech

from microbit import *
import speech

for generating speech (speaker needed)

Loops
Loops handle logic and run the program.
if

Tests a condition

while True:
  if button_a.is_pressed():
    display.show(Image.HAPPY)
  else:
    display.clear()
  sleep(100)

if button_a is pressed show happy face, sleep for 1 second and clear the display. The if loop is inside a while True: loop so it will repeat forever.

for

repeat an operation a set number of times

for x in range(0, 3):
  display.scroll(x) 

Scrolls 0, 1 & 2 on screen. Loop repeats 3 times.

while

Continues while the condition is true.

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

Show a happy face while button_a is_pressed. Show a sad face at all other times. while True loop continually tests the condition while button_a.is_pressed()

while True

repeats statement forever.

while True:
  display.show(Image.HAPPY)
  sleep(200)
  display.show(Image.SAD)
  sleep(200)

Alternates between a happy and sad face forever.

Maths
Simple maths in Python.
basic operations × ÷ − +

4 + 5 = 9 # add
5 - 1 = 4 # subtract
50 / 5 = 10 # divide
3 * 3 = 9  # multiply 
floor division

Floor division discards the remainder.

24 / 4 # 5.75
24 // 4 # 4
 

Note that no rounding takes place. It is simply discarded.

trickier

# Exponent #
6 ** 2 # = 36 (6 squared)
5 ** 3 # = 125 (6 cubed etc..)

# Modulo #
7%3 # = 1 (Remainder of 7 divided by 3)
27%7 # = 6 (Remainder of 27 divided by 7)
Data Types
Variables can hold different types of data
integers

Whole numbers.

x = 5
y = 4
answer = x * y
display.scroll(str(answer))

Store product of 4 * 5 as an integer in answer variable. Convert the integer to a string (str(answer)) and scroll on display.

strings

Are characters which Python cannot interpret. Strings are always surronded by " or ' marks.

while True:
  if microbit.button_a.is_pressed():
    mystring = "I am a string"
    display.scroll(mystring)

if button_a is pressed show happy face, sleep for 1 second and clear the display. Then wait for button to be pressed again.

lists

list of values. Called arrays in other languages

pets   = ["hamster",
          "dog",
          "cat",
          "dragon",]

List of values separated by a comma surrounded by square brackets. Single or muliple lines.

display
Module controls 5x5 display on front of micro:bit
display.get_pixel(x, y)

return brightness of LED at column x and y as an integer between 0 (off) and 9 (bright).

display.get_pixel(0,0)

get the brightness of the top left pixel as an integer from 0 to 9. Off is 0.

display.set_pixel(x, y, value)

set brightness of LED at column x and y. Value is the LED’s brightness as an integer between 0 (off) and 9 (bright).

display.set_pixel(0,0,9)

top left pixel set to maxium brightness.

display.clear()

clears micro:bit’s display

display.clear()
display.show(image)

show a premade image on micro:bit’s display. See separate entry for image.

display.show(Image.SAD)

Show a sad face.

display.scroll(string)

scroll a string across micro:bit’s display. delay parameter controls scroll speed.

display.scroll("hello world")

Scroll ‘hello world’ on the microbit’s display. Speed can be changed with delay parameter. display.scroll("hello", delay = 100)

display.show(Image.string)
Used to show predefined images on the microbit’s display.
predefined Images

Predefined images use with display.show(Image.string)

# example
display.show(Image.DUCK)

# list
HEART_SMALL    DUCK
HAPPY          HOUSE
SMILE          TORTOISE
SAD            BUTTERFLY
CONFUSED       STICKFIGURE
ANGRY          GHOST
ASLEEP         SWORD
SURPRISED      GIRAFFE
SILLY          SKULL
FABULOUS       UMBRELLA
MEH            SNAKE
YES            DIAMOND
NO             DIAMOND_SMALL
TRIANGLE       SQUARE
TRIANGLE_LEFT  SQUARE_SMALL
CHESSBOARD     RABBIT
XMAS           COW
PACMAN         MUSIC_CROTCHET
TARGET         MUSIC_QUAVER
TSHIRT         MUSIC_QUAVERS
ROLLERSKATE    PITCHFORK

CLOCK12, CLOCK11, etc
ARROW_N, ARROW_NE, etc

display.show(Image.HEART_SMALL) shows heart on micro:bit.

Accelerometer
used to detect how the micro:bit is moved
list of gestures

up        freefall
down      3g
left      6g
right     8g
face up   shake
face down
.current_gesture()

returns the gesture (above) happening to the micro:bit.

while True:
  if accelerometer.current_gesture() == "freefall":
    display.show(Image.HAPPY)
  else:
    display.show(Image.ANGRY)

gesture variable holds the gesture experienced by the micro:bit. If it’s in 0g (freefall) it shows a happy face.

.was_gesture

returns last gesture experienced by the micro:bit.

while True:
  display.show(SAD)
  if accelerometer.was_gesture("shake"):
    display.show(SKULL)

# Same as:
while True:
  display.show(SAD)
  if accelerometer.was_gesture() == "shake":
    display.show(SKULL)

The micro:bit shows a sad face. If it experiences a force greater than eight times that of earth’s gravitational pull it shows a skull.

Can you spin the micro:bit fast enough to experience that centrifugal force?

.get_x() .get_y() get_z

Returns acceleration measurement in the x, y or z axis as a positive or negative integer.

random
must be loaded at beginning of program. Put import random after from microbit import*.
randrange(start,stop)

returns random integer between start - stop.

randrange(20,30)

random number between 20 & 30.

.choice

pick random item from a list

animals   = ["dog",
            "cat",
            "horse",
            "pig",]

# pick random item from animals list
display.scroll(str(animals.choice))

scroll random animal.

button_a button_b
button_a & button_b methods:
is_pressed()

returns True if button is pressed.

if button_b.is_pressed():
  display.scroll("button pressed")

scroll string if button pressed.

.was_pressed()

return True if button was pressed since last time this function was called.

if button_b.was.pressed():
  display.scroll("button pressed")

Scroll “button pressed” if button_b was pressed.

.get_presses()

How many times was the button pressed?

count = button_b.get_presses
display.scroll(str(count))

count variable stores value of number presses of button b. Scroll count variable as a string.

.reset_presses()

set get_presses counter to 0.

button_a.reset_presses()

set button_a presses counter to zero.

my_number =  11  # in all these examples.

# is my_number greater than 11 and less than 20?
if (my_number > 11) and (my_number < 20):
# False

# is my_number greater than 2 and less than 11?
if (my_number > 2) and (my_number < 11):
# False

# is my number greater than 1 and not equal to 11?
if (my_number > 1) and not (my_number == 11):
# False

# is my number equal to 22 or greater than 3?
if (my_number == 22) or (my_number > 3):
# True
my_number =  11  # used in all examples below.

# is my_number greater than 6?
if my_number > 6:
# True

# is my_number less than 6?
if my_number < 6:
# False

# does my_number equal 32?
if my_number == 32:
# False

# does my_number not equal 32?
if my_number != 32:
# True

# is my_number equal to or greater than 10?
if my_number >= 10:
# True

# is my_number equal to or less than 10?
if my_number <= 10:
# False
my_number =  11  # Used in all examples below.

# does my_number multiplied by 2 equal 21?
if my_number * 2 == 21:
# False

# is my number an even number? ie. divisible by 2?
if my_number % 2 == 0:
# False

#########################
#   Microbit Examples   #
#########################

# Show a happy face when a & b are pressed together.
while True:
    if button_a.is_pressed() and button_b.is_pressed():
        display.show(Image.HAPPY)


#############
#   Notes   #
#############

It's a good idea to slow down loops with sleep()
#
#   A while loop executes while the condition is true    
#    
#   Put inside a while True loop to repeatedly
# test condition

# Infinite loop (repeat forever)
while True:
    display.scroll("Hello!")

# repeats while button_a is pressed
while button_a.is_pressed():
    display.show(Image.HAPPY)

# repeat while both buttons are pressed
while button_a.is_pressed() and button_b.is_pressed():
    display.show(Image.SAD)

# repeat while microbit is shaken
while accelerometer.current_gesture() == "shake":
    display.show(Image.MEH)
    
# Show arrow pointing at button_a
# Wait until button a is pressed
# then start your program.

# Good way of getting the user to start the program.

    display.show(Image.ARROW_W) # poiting at button_a
    while not button_a.was_pressed():
        sleep(20)
    display.scroll("button_a was pressed now do this")
    display.scroll("and this...")
#
#   An if loop runs if the condition is true.
#

# if button a is pressed, show a happy face
# else, if button b is presesd, show a cow face
# if none of these, else show a cow.
if button_a.is_pressed():
    display.show(Image.HAPPY)
elif button_b.is_pressed():
    display.show(Image.SAD)
else:
    display.show(Image.COW)

# show happy face if temperature on the microbit
# greater than 25 degress
if temperature() > 25:
    display.show(Image.HAPPY)
else:
    display.show(Image.SAD)

#########################
#   Microbit Examples   #
#########################

# if button a is pressed show a happy face.
from microbit import * 

while True:
    if button_a.is_pressed():
        display.show(Image.HAPPY)
    else:
        disaply.show(Image.SAD)
###############################
#      ** Code Snippets **    #
#         User Feedback       #   
################################

# Prompt user to press button_a
#
# When button_a.was_pressed()
# run the program

display.show(Image.ARROW_W) # point at button

while not button_a.was_pressed(): 
    sleep(20)

display.scroll("button_a was pressed now do this")
display.scroll("and this...")


# Yes, No, Waiting
#
# Is button_a pressed? 
#   if yes -> show tick
#   if button_b pressed -> show cross
#   else -> show waiting animation of a clock
while True:
    if button_a.is_pressed():
        display.show(Image.YES)
    elif button_b.is_pressed():
        display.show(Image.NO)
    else:
        display.show(Image.ALL_CLOCKS,
                     wait=False,
                     loop=True,
                     delay=100)
###############################
#      ** Code Snippets **    #
#         Display Fun         #   
###############################

# Sequentially light each pixel on the 
# display.
for x in range(5):
    for y in range(5):
        display.set_pixel(x, y, 9)
        sleep(50)

# show animation of a spinning clock
# loop=True causes it to repeat
# wait=False makes it non-blocking;
display.show(Image.ALL_CLOCKS,
             delay=100,
             loop=True,
             wait=False)

# show a looping list of images
image_list = [Image.HAPPY,
              Image.SAD,
              Image.YES,
              Image.NO]

display.show(image_list, loop=True)
###############################
#      ** Code Snippets **    #
#         Scan I2C Bus        #   
################################

# Connect the microbit to the I2C Bus
#
# Microbit prints to REPL all devices it finds.

start = 0x08
end = 0x77

while True:
    display.show(Image.ARROW_W)
    if button_a.was_pressed():
        display.show(Image.MEH)
        print("Scanning I2C bus...")
        for i in range(start, end + 1):
            try:
                i2c.read(i, 1)
            except OSError:
                pass
            else:
                print("Found:  [%s]" % hex(i))
        print("Scanning complete")
        print("Magnetometer [0x0e] Accelerometer [0x1d]")
    sleep(10)
# scrolls 'hello world' across the microbit 
# display.

from microbit import *

display.scroll("Hello, World!")
# scroll the temperature

from microbit import *

while True:
    temp = temperature()
    display.scroll(str(temp))

# convert celsius to fahrenheit

from microbit import *

while True:
    celsius = temperature()
    fahrenheit = round(((celsius * 1.8) + 32), 1)
    display.scroll(str(fahrenheit))
# Button a to record a button press
# button b to show times button a was pressed
# hold button a and b to reset the count

from microbit import *

count = 0

while True:
    display.show(Image.ARROW_W)
    if button_a.was_pressed():
        count += 1
    elif button_b.was_pressed():
        display.scroll(str(count), delay=100)
    elif button_a.is_pressed() and button_b.is_pressed():
        count = 0
        display.scroll("Reset", delay=100)