BBC micro:bit
First MicroPython Program

Introduction

If you have taken the trouble to download the Mu software and have installed the driver, you need a quick way to test that everything works. We will start by displaying some information on the LED matrix.

Programming

Type the following into the editor and then press the Flash button.

from microbit import *
display.scroll("I am a micro:bit.")

The first line of this program imports the library of micro:bit functions. The second line scrolls a message across the screen. This happens only once.

This next program uses a while loop to repeatedly scroll the message across the screen. The sleep statement causes the micro:bit to pause for a set number of milliseconds.

from microbit import *
while True:
    display.scroll("I am a micro:bit.")
    sleep(5000)

While loops repeat as long as the specified condition evaluates to true. In this case, we have said that the condition is true. That creates an infinite loop. The code that needs to be repeated is indented. You can use this technique for a game loop and as an equivalent to the loop() procedure that you write with an Arduino sketch.

Python is case sensitive. You will need to write the code exactly as you see in the examples or you will get an error.

We can use a break statement if there is a reason that we need to break out of the infinite loop. The following script does just that.

from microbit import *
while True:
    if button_a.is_pressed():
        break
    display.scroll("I am a micro:bit.")
    sleep(5000)   
display.show(Image.HAPPY)

If you hold down the A button, the program breaks out of the loop and displays a happy face on the LED matrix.

Challenge

Take your first steps and play around with the statements on this page. You need to check that the editor and COM port driver are working anyway.