Skip to content

Writing your first program

First things first

In the example project directory, navigate into the source folder. Here you will find main.cpp, where you can start writing a program. You'll find that an example hello world program has been written for you.

Example project?

Make sure you've set up your build environment. If you haven't, see here for how to set one up.

Breaking down 'Hello World!'

Here is the sample program for reference:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#include "MicroBit.h"

MicroBit uBit;

int 
main()
{
    uBit.init();

    while(1)
        uBit.display.scroll("HELLO WORLD!");
}

The uBit Object

The majority of the functionality of the micro:bit has been abstracted for you into the MicroBit class. By convention, this is normally called uBit, and is how it is referred to in the rest of the documentation.

In this case, we access the display, which we use to show things on the 9x9 LED grid on the front of the micro:bit; in this case, we scroll the string "HELLO WORLD!".

Important!

Before using the uBit object, make sure you run its initialiser method, init!

This sets up the object to work with the micro:bit peripherals.

Warning

There should only be one instance of uBit in your program, defined in main.cpp. If you have other files in which you need also to access a uBit object, write extern MicroBit uBit;. This ensures you use the same object instance throughout the program as in main.cpp.

int main()

This is the entry point for your program. When your micro:bit starts or is reset, it will look to this function first. If you want to extrapolate your code somewhere else, make sure it's referenced here.

Compiling

You can simply run build.py in the root directory of your project, as per 'Setting up your build environment'. You can also hit the 'build' button directly at the bottom of the VSCode window if you've set that up, as per 'Working with VS Code'.

Running on the micro:bit

The build will have outputted a file called MICROBIT.hex into the project root directory. Thanks to DAPLink, you can simply move this file straight into the micro:bit drive, either via command line or GUI, as in Windows Explorer in the example.

Dragging the .hex file straight into the MICROBIT device

If everything is set up correctly, you should see "HELLO WORLD!" scrolling across your screen indefinitely.

Explore

Have a look at the uBit documentation to see the possibilities on the micro:bit.

uBit Documentation