Advanced Micro:bit
Algorithms and ProgrammingCADImpact of Computing

Advanced Micro:bit

Grades 5–12
4 hrs
8 steps
Groups of 20
NC SCOS

Standards Alignment

NC SCOS

Computer Science

  • 68-DA-01: Represent data using multiple encoding schemes.
  • 68-CS-02: Design projects that combine hardware and software components to collect and exchange data.
  • 68-AP-03: Design and iteratively develop programs that combine control structures including nested loops and compound conditionals.
  • 68-AP-07: Create procedures with parameters to organize code and make it easier to reuse groups of instructions.
  • 68-AP-01: Implement flowcharts and/or pseudocode to address complex problems as algorithms.
  • 35-CS-02: Model how computer hardware and software work together as a system to accomplish tasks.
  • 35-AP-02: Create programs that use variables to store and modify data.
  • 35-AP-04: Construct programs using simple loops.
  • 68-AP-04: Construct programs that include events.
  • 68-DA-02: Collect data using computational tools.
  • 68-DA-03: Transform the collected data to make it more useful and reliable.
  • 68-AP-08: Assess feedback from team members and users to refine a solution that meets user needs.

Showing 12 of 14 standards.

Lesson Steps

1

Proximity Beacon

30 min

Step 1: Make it

 

What is it?

Use radio to sense how close another micro:bit is and then make a treasure hunt game or use it to help people know they’re at a safe social distance.

 

Introduction

 

Coding guide

 

How it works

  • You need at least 2 micro:bits for this. We’ll create two different programs, one for the beacon which constantly sends a low-power radio message. The other program goes on the receiver.
  • When the receiver picks up a message from the beacon, it stores its strength in a variable called signal and shows it on its LED display.
  • Radio signals get stronger the closer you are to the transmitter, so if the signal is strong it means the other micro:bit is probably close.
  • If the radio signal is weak, the other micro:bit is probably further away.
  • It displays a bar graph which gets bigger the stronger the signal and the closer you are. It uses the maths map block to map radio signal strength numbers from the range -95 (weak) to -42 (strong) to a range 0 to 9 we can use to draw a bar graph.

 

Python version

  • Python doesn’t have a built-in bar graph or map function, so it works a bit differently. All the LEDs light up when you get close to the beacon, and the closer you get the brighter they glow.
  • It takes radio strength readings using the radio.receive_full() command. This provides the message, the signal strength and a timestamp. We only want to know the signal strength, so we use signal = message[1] to extract this and store it in a variable called signal.
  • The signal strength may be in the range -98 (weakest) to -45 (strongest), and the Python program defines a function called map to convert numbers in this range to the range 0 – 9 which we can use for changing the brightness of the LEDs: 0 means off, 9 is the brightest an LED can be. (You might want to re-use this function in other Python projects as it works very much like the map block in MakeCode).
  • The Python program creates a blank 5x5 image called light using the command light = Image(5,5)
    Its brightness is changed using the light.fill() command.

 

What you need

  • 2 micro:bits and battery packs
  • MakeCode or Python editor
  • battery pack (optional)

 

Step 2: Code it

 

Transmitter / beacon

 

MakeCode

 

Python

from microbit import *
2import radio
3radio.config(group=1, power=1)
4radio.on()
5
6while True:
7    radio.send('1')
8    sleep(200)
9

 

Open in Python

Open in Classroom

Open in MakeCode

Download HEX

 

Receiver

 

MakeCode

 

Python

from microbit import *
2import radio
3radio.config(group=1)
4radio.on()
5light = Image(5,5) # create an empty image
6
7# function to map signal stength to LED brightness
8def map(value, fromMin, fromMax, toMin, toMax):
9    fromRange = fromMax - fromMin
10    toRange = toMax - toMin
11    valueScaled = float(value - fromMin) / float(fromRange)
12    return toMin + (valueScaled * toRange)
13
14while True:
15    message = radio.receive_full()
16    if message:
17        signal = message[1]
18        brightness = map(signal, -98, -44, 0, 9)
19        light.fill(round(brightness))
20        display.show(light)
21

 

Open in Python

Open in Classroom

Open in MakeCode

Download HEX

 

Step 3: Improve it

  • Combine the beacon and receiver code so you can have one micro:bit that does both tasks.
  • Make wrist bands so you can wear your proximity detectors.
  • How strong is the signal when you're 1 or 2 metres apart? Modify the code to trigger a visual or audible alarm when someone is too close.
  • Use these programs to make a treasure hunt game: hide the beacon and put the receiver code on lots of micro:bits
  • If you're outdoors or in a large space, experiment by changing the transmitter power. It can be any number from 0 to 7
2

Guitar Touch Tunes

30 min

Step 1: Make it

 

What is it?

Play different tunes by using the micro:bit’s touch sensor.

These two videos show you what you'll make and how to code it:

 

Introduction

 

Coding guide

 

How it works

  • This project is the same as the Jukebox project but instead of using the micro:bit’s buttons, you’ll make your own input device using cardboard covered in strips of tin foil connected by crocodile clip leads to the micro:bit's pins.
  • Flash the program onto your micro:bit.
  • Attach one end of three crocodile clip leads to pins 1, 2 and GND (ground or Earth pin). Attach the other ends to a cardboard guitar or keyboard.
  • With one finger touch the foil connected to GND, and with another finger touch the foil connected to pin 1 and then pin 2. It should play a different tune depending on which strip of foil you touch.
  • The micro:bit is using pins 1 and 2 as touch inputs. When you touch either of these pins and the GND pin, you’re completing an electrical circuit. A small amount of electricity flows through you, the micro:bit can detect it and the program triggers the playing of a tune.
  • If you do not have a V2 micro:bit, which plays sound, attach headphones to pins 0 and GND.

 

photo showing how to connect silver foil pads to micro:bit pins 1, 2 and GND

 

What you need

  • micro:bit and optional battery pack
  • MakeCode or Python editor
  • three crocodile clip leads
  • cardboard, tin foil, glue stick and scissors to make a guitar or keyboard
  • optional headphones, buzzer, or speaker with additional two crocodile clip leads for V1 users

 

Step 2: Code it

 

MakeCode

 

Python

from microbit import *
2import music
3
4while True:
5    if pin1.is_touched():
6        music.play(music.ODE)
7    if pin2.is_touched():
8        music.play(music.BLUES)
9

 

Open in Python

Open in Classroom

Open in MakeCode

Download HEX

 

Step 3: Improve it

  • Change the tunes that are played when you touch the tin foil.
  • Program your own tunes.
  • Show different pictures, letters, numbers, or words depending on which tune you picked.
3

Tilt Alarm

30 min

Step 1: Make it

 

What is it?

Keep your precious things safe with this radio-controlled burglar alarm.

These two videos show you what you'll make and how to code it:

 

Introduction

 

Coding guide

 

 

How it works

  • When the micro:bit is shaken, the accelerometer detects movement and it shows an angry face on the LED display and plays an alarm sound.
  • It also sends a ‘thief!’ radio message, so that another micro:bit can warn you if someone is moving your valuable object.
  • If you have two micro:bits, flash this program onto both. Put one in, or on, a valuable thing you want to protect and keep the other near you.
  • As we want to show the angry face and play the ‘BADDY’ tune on both the movement sensor micro:bit and the alarm, this program uses a function (or procedure) called alarm.
  • Procedures and functions are really useful for sections of code we want to use at different points in a program. It saves duplicating code and makes the program more compact and efficient.

 

What you need

  • 2 micro:bits
  • a battery pack
  • something precious to keep safe
  • headphones, buzzers or powered speakers and two crocodile clip leads to attach them if using a V1 micro:bit

 

Step 2: Code it

 

MakeCode

 

Python

from microbit import *
2import radio
3import music
4radio.config(group=1)
5radio.on()
6
7def alarm():
8    display.show(Image.ANGRY)
9    music.play(music.BADDY)
10    
11while True:
12    message = radio.receive()
13    if message:
14        alarm()
15    if accelerometer.was_gesture('shake'):
16        radio.send('thief!')
17        alarm()
18

 

Open in Python

Open in Classroom

Open in MakeCode

Download HEX

 

Step 3: Improve it

  • What else could you protect with an alarm like this? How could it help protect trees?
  • Make it more sensitive using accelerometer readings or other gestures.
  • Split the program in two, so you have different programs on the sensor on your valuable thing and on the alarm you keep with you.
  • Send different messages and show different pictures for different alarm sensors on different valuable objects.
4

Reaction Game

30 min

Step 1: Make it

 

What is it?

Make a reaction game with real physical switches you can bash as hard as you like!

 

two home-made pressure switches attached to micro:bit pins

 

How it works

  • Make two physical input switches using cardboard and tin foil – similar to the ones used in the Pressure switch alarm project.
  • Connect them to the micro:bit pins as in the picture – one tin foil pad on each switch goes to the micro:bit’s GND pin, and the other is connected to pin 1 or pin 2 depending on whether you are player A or player B.
  • The program waits a random time between 1 and 5 seconds, then shows a heart on the LED display output.
  • You can’t hit your button before it lights because it uses Boolean logic to stop anyone cheating! Boolean variables can only have two values: True or False. The game started variable prevents either player pressing their button too soon by only checking which button is pressed while the game has started.
  • An infinite loop keeps the game running so you can keep playing.

 

What you need

  • 1 micro:bit
  • 4 crocodile clip leads
  • Some scrap cardboard, tin foil, glue and scissors

 

Step 2: Code it

 

MakeCode

 

Python

from microbit import *
2import random
3
4while True:
5    gameStarted = False
6    sleep(random.randint(1000, 5000))
7    gameStarted = True
8    display.show(Image.HEART)
9    while gameStarted:
10        if pin1.is_touched():
11            display.show('A')
12            gameStarted = False
13        elif pin2.is_touched():
14            display.show('B')
15            gameStarted = False
16    sleep(3000)
17    display.clear()
18

 

Open in Python

Open in Classroom

Open in MakeCode

Download HEX

 

Step 3: Improve it

  • Use variables to keep track of each player’s score
  • Add a timer to show how quick each winner’s reaction was
  • Track which player has the fastest reaction time
5

MakeCode Data Logger

30 min

Step 1: Make it

 

What is it?

Use micro:bit as a wireless data logger recording readings from its sensors.

 

micro:bit showing graph and X, Y and Z axes going across front, up down and front to back resepctively

 

How it works

  • Flash the transmitter program onto a micro:bit with battery pack and either attach it to something that moves (like the inside of a salad spinner) or get ready to play catch with it.
  • The transmitter takes constant accelerometer readings of the forces in 3 dimensions (x, y and z axes) and transmits them by radio.
  • Connect the receiver micro:bit to a computer and flash the logger program in to it using the Chrome browser or standalone MakeCode app. This receives the accelerometer data and send as serial data to your computer.
  • You should now see a ‘show console device’ button appear below the micro:bit simulator, click on it and you should see graphs of the live data readings appear on the screen.
  • Hold the sensor micro:bit on each of its sides and see how the readings in each axis change. Throw it in the air, spin it in a salad spinner: what do you see?
  • Press ‘pause’ and you can download the numerical data as a CSV (comma separated values) file which you can open in a spreadsheet program to analyse. If you delete the second and third time columns, leaving only the first, you can plot the data on a scatter graph in your spreadsheet showing how the forces change over time.

 

spreadsheet showing line chart made from accelerometer readings

 

What you need

  • 2 micro:bits and one battery pack
  • laptop or desktop computer to record data on
  • MakeCode editor (standalone app or web version in Chrome v65 or later)
  • up-to-date firmware (0249 or higher) on the receiving micro:bit
  • optional salad spinner

 

Step 2: Code it

 

Sensor / transmitter

MakeCode

 

Open in Classroom

Open in MakeCode

Download HEX

 

Receiver

MakeCode

 

Open in Classroom

Open in MakeCode

Download HEX

 

Step 3: Improve it

  • Record other micro:bit sensor readings remotely this way, such as temperature, light or magnetic compass readings.
  • Conduct a physics experiment into the forces acting on a micro:bit as it spins in a salad spinner (centrifuge). Do you see what you expect? (Bear in mind that the accelerometer on the micro:bit can only read forces up to 2g, twice the force of the Earth’s gravity – if you spin it fast it may experience forces that are too large for it to register.)
6

Max-Min Temperature Logger

30 min

Step 1: Make it

 

What is it?

Turn your micro:bit into a self-contained data logger that records maximum and minimum temperature readings, and stores them so it keeps the data even if the batteries run out or you disconnect the power.

It's a Python program, but you don't need to understand anything about Python to use it.

 

What you'll learn

  • How to use Python to read and write data to non-volatile storage that stays on your micro:bit even when the power is removed
  • How to handle errors in Python programs
  • How to convert numerical variables to strings and back again

 

What you need

  • A micro:bit
  • optional battery pack

 

How to use it

  • Download the .hex program file and flash it onto your micro:bit.
  • If you have a battery pack, attach it and leave the micro:bit somewhere where the temperature will vary. You could test it by putting it outside or in a fridge and leaving it for a few minutes.
  • Shake it to show the current temperature.
  • Press button A to show the minimum recorded temperature.
  • Press button B to show the maximum recorded temperature.
  • Press GND and pin 2 at the same time with your fingers to reset the maximum and minimum temperature to the current temperature.

 

 

Step 2: Code it

 

Python

1from microbit import *
2
3# function to read data file:
4def get_nv_data(name):
5    try:
6        with open(name) as f:
7            v = int(f.read())
8    except OSError:
9        v = temperature()
10        try:
11            with open(name, 'w') as f:
12                f.write(str(v))
13        except OSError:
14            display.scroll('Cannot create file %s' % name)
15
16    except ValueError:
17        display.scroll('invalid data in file %s' % name)
18        v = temperature()
19
20    return v
21
22# function to write data file:
23def set_nv_data(name, value):
24    try:
25        with open(name, 'w') as f:
26            f.write(str(value))
27    except OSError:
28        display.scroll('Cannot write to file %s' % name)
29
30min = get_nv_data('min.txt')
31max = get_nv_data('max.txt')
32
33while True:
34    currentTemp = temperature()
35    if currentTemp < min:
36        min = currentTemp
37        set_nv_data('min.txt', min)
38    if currentTemp > max:
39        max = currentTemp
40        set_nv_data('max.txt', max)
41    if accelerometer.was_gesture('shake'):
42        display.scroll(currentTemp)
43    if button_a.was_pressed():
44        display.scroll(get_nv_data('min.txt'))
45    if button_b.was_pressed():
46        display.scroll(get_nv_data('max.txt'))
47    if pin2.is_touched():
48        display.scroll('clearing data')
49        set_nv_data('min.txt', currentTemp)
50        set_nv_data('max.txt', currentTemp)
51

 

Open in Classroom

Open in Python

Download HEX

 

How it works

This data logger stores its readings even when the power is disconnected from your micro:bit. It does this by storing the readings in non-volatile storage. This is computer memory that keeps its contents when the power is turned off, just like your micro:bit keeps a program you have flashed onto it when you unplug it from the computer.

It stores the data on your micro:bit in two text files called min.txt and max.txt which the Python program can read and update.

The program uses three variables to track and compare the temperature:

  • currentTemp is the current temperature reading from the micro:bit's built-in temperature sensor
  • max is the maximum temperature. This gets assigned a new value if the current temperature is greater than (>) the current value of max.
  • min is the minimum temperature. This gets assigned a new value if the current temperature is less than (<) the current value of min.

Two functions, get_nv_data and set_nv_data, read and write numerical data to the non-volatile text files. These functions convert numbers to text and back:

  • int() converts text (also called a string) to a numerical (integer) variable we can use to compare with the current temperature.
  • str() converts a numerical variable, like a temperature reading, to a text string so it can be saved in a text file.

The functions use try and except to catch errors reading or writing the data files. If there is no text file saved with the maximum and minimum temperatures, for example when you first run it, it sets the max and min variables to be the current temperature.

The main part of the program runs inside the while True: loop. This behaves like the forever block in MakeCode.

 

Step 3: Improve it

  • The micro:bit's temperature sensor is inside the processor and usually gives temperature readings higher than the surrounding air. Measure the difference using a normal thermometer and add an offset to the program by subtracting the difference from the temperature() reading
  • Convert the program to log different kinds of data, such as forces measured by the accelerometer.
  • Add radio functionality to also send data to another micro:bit in another location.

 

Learn more about storing data in Python

7

Fireflies

30 min

Step 1: Make it

 

Turn a set of micro:bits into a magical glowing swarm of fireflies using radio communication

 

a set of micro:bits triggering each other by radio to glow briefly

 

What you'll learn

  • how to use radio communication between micro:bits to trigger events
  • that the micro:bit's LED display can be made brighter and dimmer
  • how to use random numbers and chance to mimic real-world behaviour

 

What is it?

Fireflies are insects that use bioluminescence (light made in their bodies) to communicate with each other.

This project mimics the behaviour of real fireflies using the micro:bit's radio communication feature. The Python version was created by Nicholas H. Tollervey, and the MakeCode version is based on this.

Flash the program on at least three micro:bits in the same room. Press button A on any micro:bit and you should see a 'swarm' of micro:bits lighting up as they receive a radio message. It works best in a dark room with lots of micro:bits.

Once a micro:bit has received the radio message it has a one in ten chance of transmitting its own radio message and starting another wave of glowing lights in the other micro:bits.

When the lights eventually stop, press button A on any micro:bit to restart the 'swarm' of communication.

 

How it works

  • The program uses radio communication to send a message 'flash' when you press button A on one of the micro:bits.
  • When each micro:bit receives the message, it waits a random amount of time between 50 and 350 milliseconds. It then makes the LED display flash bright then gradually dim to mimic the glow of a firefly.
  • Next it generates a random number between 0 and 9. If the number is 0, it then sends its own 'flash' radio message, triggering more micro:bit fireflies to glow. So it has a one in ten chance of triggering more glows in other micro:bits.
  • You can use a mixture of old and new micro:bits, but they must all have either the MakeCode or Python versions of the program flashed on to them. (Radio communication works slightly differently in each programming language. MakeCode programs can't communicate over radio with Python ones and vice versa.)

 

What you need

  • at least 3 micro:bits, the more the better
  • micro:bit battery packs (optional)

 

Step 2: Code it

 

MakeCode

 

Python

# A micro:bit Firefly.
2# By Nicholas H.Tollervey. Released to the public domain.
3import radio
4import random
5from microbit import display, Image, button_a, sleep
6
7# Create the "flash" animation frames. Can you work out how it's done?
8flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]
9
10# The radio won't work unless it's switched on.
11radio.on()
12
13# Event loop.
14while True:
15    # Button A sends a "flash" message.
16    if button_a.was_pressed():
17        radio.send('flash')  # a-ha
18    # Read any incoming messages.
19    incoming = radio.receive()
20    if incoming == 'flash':
21        # If there's an incoming "flash" message display
22        # the firefly flash animation after a random short
23        # pause.
24        sleep(random.randint(50, 350))
25        display.show(flash, delay=100, wait=False)
26        # Randomly re-broadcast the flash message after a
27        # slight delay.
28        if random.randint(0, 9) == 0:
29            sleep(500)
30            radio.send('flash')  # a-ha
31            
32

 

Open in Python

Open in Classroom

Open in MakeCode

Download HEX

 

Step 3: Improve it

  • Change the image that's displayed when the display flashes
  • Modify the code to make it more or less likely to trigger another flash event in other micro:bits. The range of random numbers could match the number of micro:bits you have: make it more likely if you have fewer micro:bits
  • Make smaller groups of fireflies using different radio group numbers. Only the micro:bits with the same group number will be able to communicate with each other.
  • Experiment with changing the power of the radio signal.
    Use the 'radio set transmit power' block in MakeCode.
    In Python use radio.config(power=7)
    Pick a number between 0 (weakest radio signal) and 7 (strongest).
    What effect does changing the radio power have?
8

Energy Light Meter

30 min

Step 1: Make it

 

What is it?

A project to find out about energy use in your home or school by measuring how much light you use.

This light meter will help you measure how light levels vary around you when lights are turned on and off and find the best location to place a light timer.

 

 

What you'll learn

  • How to take readings from the micro:bit's sensors and store them in a variable so that you can repeatedly view the same reading even after conditions have changed
  • Find locations for recording reliable environmental data

 

How to use it

  • With the lights turned off, place your micro:bit where you want to take the light reading, and press button A.
  • Move the micro:bit so you can see its display easily, and press button B to see the light level reading. This will be a number between 0 (dark) and 255 (the most intense light the micro:bit can measure) .
  • You can press B again if you're not sure of the reading.
  • Turn the lights on and make another measurement by pressing A again, then press button B to read the number.
  • Find a place where there is a big difference between the readings when the lights are off and on. Away from a window where daylight might come in, and closer to the electric light source would be best. A cupboard would be ideal, if it has electric lighting.
  • Take a few readings and find the average of the readings when the light is turned on. You'll need this number for the next project, the Energy light timer.

 

How it works

  • The program uses a variable called reading to store the light level. It sets this at the start and whenever you press button A.
  • Storing the light sensor reading in a variable, rather than just showing it straight away, is a good idea because it means you can view the reading over and over again when you note it down.
  • Using a variable also means you can take a light reading in a place where it might be difficult to see the display and view the light measurement in a more convenient place.

 

What you need

  • micro:bit (or MakeCode simulator)

  • MakeCode or Python editor
  • battery pack (recommended)

 

Step 2: Code it

MakeCode

 

Python

from microbit import *
2
3display.show('M')
4reading = display.read_light_level()
5sleep(100)
6
7while True:
8    if button_a.was_pressed():
9        # take a light measurement and store it
10        reading = display.read_light_level()
11        display.show(Image.DIAMOND_SMALL)
12        sleep(400)
13        display.show(Image.DIAMOND)
14        sleep(400+500)
15        display.show('M')
16
17    elif button_b.was_pressed():
18        # display the stored light measurement
19        display.clear()
20        display.scroll(reading)
21        sleep(500)
22        display.show('M')
23

 

Open in Python

Open in Classroom

Open in MakeCode

Download HEX

 

Step 3: Improve it

  • Modify the code to calculate an average reading for you.
  • Add a second micro:bit and radio functionality to allow remote reading of light levels.
  • If you have access to a light meter that measures light levels in other units, compare the micro:bit's readings with it.
  • Use the light meter readings to make a timer to record how long lights are left on.

 

This content is published under a Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) licence.

Materials

  • Micro:bit Club Pack (10x) — 2 per classroom

Related Supply Kit

Micro:bit Pack

All the hands-on materials you need for this lesson, delivered to your classroom.

More robotics lessons

Ready to bring this lesson to your classroom?

Sign up to save this lesson, order supplies, and track student progress.