Overview

The micro:bit is a great bit of kit for hobbyists, designers, educators and of course students.

Of course there is a plethora of devices that can do similar things to the micro:bit. Some are specific and promote particular features of chip manufactures while others like Arduino and Raspberry pi are general purpose but may require greater complexity and expense to achieve a requirement easy served by the micro:bit.

One of the strengths of the micro:bit is it's implementation of BLE. Martin Woolley, the principal architect for the micro:bit bluetooth implementation, has produced some very interesting articles:

Martin has written a number of applications for the Android Operating system that demonstrate how the micro:bit can be controlled using a smart phone. There are, however, few examples, at the time of writing, on developing applications for Apple devices such as iPhones and iPads. Apart from the fact there are lots of iPhones and iPads waiting to control micro:bits, there are a few other reasons for writing code for iOS devices:

This project describes an Application Programming Interface (API), that can be used to develop applications for Apple operating systems, that interact with the micro:bit.

The API is written in the Swift programming language and exploits the Apple Core Bluetooth framework. It's easily installed in any Xcode project by simply copying Microbit.swift into an Xcode project.

For further information about Microbit.swift see: Appendix A - Microbit API

The Microbit Playground

To demonstrate the API there is a micro:bit Swift Playground.

Usually when developing applications, you would use Xcode's powerful user interface building facilities, however, these are not available to Playgrounds so it is necessary to build user interfaces programmatically. The Micro:bit Playground includes the necessary view controllers and custom views to interact with the micro:bit API.

The view controllers are contained in a single file: MicrobitUIController and the custom views are in the file: MicrobitUI.swift.

Getting Started

To use the micro:bit Swift Playground you need to do a few things:

Download the micro:bit playground.

The micro:bit playground has been designed to run on any iPad that has Swift Playgrounds installed. You can install Swift Playgrounds for free by downloading it from the App Store.

Download Microbit.playground on an iPad that supports Swift Playgrounds. Tap on: Microbit.playground.zip to open, and, tap the Download button.

The Microbit.playground will be downloaded to the iPad. Providing Swift playgrounds is installed, you will see and option to Open in "Playgrounds".

Open the Microbit playground from the MyPlaygrounds screen. Test it works by tapping Run My Code at the bottom of the screen. You should see a screen that looks a bit like this:

microbit_playground_menu

Select the Log option and check for the message "Bluetooth is available". If you don't see this message, check that Bluetooth is turned on in settings.

Program the micro:bit

You will need to write a simple program to test the playground, if you are new to using the micro:bit read: Using micro:bit in 5 easy steps. The easiest way to write a program is with the online Javascript Blocks Editor.

By default the editor does not include the Bluetooth package, so you you will need to add it using the Add Package option in the Advanced section of the packages list. For further information on how this is done see this article.

As a test, write a program that implements the Bluetooth Button Service. Arrange the blocks as shown in the following: makecode_Button
To implement the button service, simply add the bluetooth button service block to the on start block. Also. add some code to indicate the 'state' of the program - 'S' program has started, 'C' program is connected to the iPad, 'D' the program has disconnected from the iPad.

There is one more thing to do before downloading the program to the micro:bit. The pairing option determines how the micro:bit will pair with the iPad. For details about the various pairing option see the section on Pairing. For performing this test, turn off pairing. Select the cog in the top right of the editor and then select Project Settings. Now select - No Pairing Required: Anyone can connect via Bluetooth.

You can now download the program to the micro:bit.

Edit the micro:bit playground

The micro:bit playground as supplied is very simple. It:

The Microbit initialiser requires a parameter which is the name the micro:bit advertises. Currently this is in the form of BBC micro:bit [identifier]. The identifier will vary between micro:bits. One way to find out the name of your micro:bit is to:

Providing the micro:bit is running a bluetooth program you should see the device name e.g.
BBC micro:bit [tizip]. You can now edit the playground to set the correct name e.g.

vc.microbit = Microbit("BBC micro:bit [tizip]")

Test the button service

The log at the bottom of the playground screen should show a number of messages, including messages that Button state characteristics have been found and the serial number and firmware revision. Also the micro:bit should show a C on the led matrix.

You can now try pressing the A button on the micro:bit and see if the indicator on the playground changes from black to red. Release the button and the indicator should return to black. Now press the button and hold it down for more than 2 seconds. The indicator should change from red to blue. Repeat the process using button B. If that works you have successfully set up your Swift playground to communicate with a micro:bit.

You should be able to disconnect the micro:bit by pressing Disconnect. Check that the micro:bit now displays a D. Try connecting again by pressing the Start Scan. Disconnection and reconnection may cause the micro:bit program to fail particularly if a lot is running on the micro:bit e.g. managing a number of bluetooth services. If the communication has stoped, or, perhaps random LEDs are on, press the reset button on the micro:bit so that it shows S and press Start Scan to reconnect.

Pairing

Bluetooth pairing creates a trusted relationship between two devices and allows them to exchange encrypted data. The pairing procedure does add a level of complication that might not be necessary and, unfortunately, each time the micro:bit is reloaded with a program over USB, the pairing procedure must be repeated. Flashing the micro:bit 'over the air' maintains pairing details so avoids repeating the pairing procedure. To flash the micro:bit over the air you need the free micro:bit app available from the Apple app store.

The Javascript Blocks Editor allows you to set one of three types of pairing when compiling a bluetooth program:

These options are set in the Project Setting menu accessed by pressing the cog icon at the top right of the Javascript Blocks Editor.

For for general information about pairing the micro:bit with devices such as smart phones and tablets see: Bluetooth Pairing.

Note: The official micro:bit pairing documentation refers to the need for an application such as 'nRF Master Control Panel' to trigger pairing when using an IOS device. This is not necessary if using the Microbit class described in this document. Initialisation of a Microbit object causes the Event Service - client requirements characteristic to be written, forcing the pairing to be triggered.

The following is specific to pairing the micro:bit playground.

No Pairing

This option is ideal for testing, particularly if you need to repeatedly download code to the micro:bit. All you need to do is ensure the the Microbit class initialiser is called with the correct name of the micro:bit. See Edit the micro:bit playground above to find out how to find the name of your micro:bit.

JustWorks pairing

This option is the default if using the Javascript Blocks Editor. It provides security without the need for a passcode, but it does mean the following process must be repeated each time you download code to the micro:bit. To use 'JustWorks pairing' follow these steps:

vc.microbit = Microbit("BBC micro:bit")

Passkey Pairing

Passkey pairing requires a 6 digit random passkey, displayed on the micro:bit, to be entered on the iPad. To use Passkey pairing follow these steps.

vc.microbit = Microbit("BBC micro:bit")

Bluetooth Services

The Micro:bit Playground demonstrates the various Services available on the micro:bit.

For further information regarding the Bluetooth Services available to the micro:bit see The micro:bit GATT profile

Accelerometer

For information on programming the micro:bit to use the accelerometer service see: accelerometer reference.

The micro:bit reports the acceleration (milli g-force) in three directions:

Button

For information on programming the micro:bit to use the button service see: Button Service.

The indicators change on the Playground depending on which button is pressed and how long it's pressed for.

Event

Unlike the other micro:bit services, the Event service is enabled by default when you include the Bluetooth package, you do not have to explicitly enable the service . The service extends the micro:bit message bus over Bluetooth (see the micro:bit runtime for further information about the micro:bit message bus).

The service allows the Playground (or any smart phone or tablet of course) to interact with a micro:bit program and the micro:bit to communicate with the Playground. To demonstrate this, the Playground has been setup to respond to a specific set of user defined Event Service IDs (9010, 9011, 9012, 9013, 9014). You are free to define your own Events IDs for your own projects. The Playground also defines the following Events it can raise on the micro:bit message bus:

The following micro:bit program demonstrates the Event service as implemented by the Micro:bit Playground:

makecode-Events

To demonstrate micro:bit Events:

The micro:bit program counts from -60 raising event 9010 on the micro:bit message bus every second. The Bluetooth Event Service will transmit the event and its corresponding value to the Playground.

If you press button A on the micro:bit, it will raise event 9011 with the current contents of 'value1', if you press button B, event 9011 will be raised with an value of 0.

The Playground allows you to select one of 4 events the will be transmitted to the micro:bit message bus. If you select MES_DPAD_CONTROLLER_ID and enter a number between 0 and 65535 it will displayed on the micro:bit LED matrix.

LED

For information on programming the micro:bit to use the LED service see: LED Service.

The matrix on the left-hand side of the Playground depicts the micro:bit LED matrix with each dot representing one of the 25 LEDs. If you press one of the dots the corresponding LED should light.

You can also enter up to 20 characters of text which will be scrolled across the LED matrix. The speed of the scroll can be set as:

Magnetometer

For information on programming the micro:bit to use the Magnetometer service see: Magnetometer Service.

When you connect to the micro:bit for the first time after reloading a program, the micro:bit will request that you calibrate the magnetometer see calibrate compass.

The playground reports magnetometer data at specified intervals:

The playground also reports the compass bearing in degrees from North.

IO Pin

For information on programming the micro:bit to use the IO Pin service see: IO Pin service.

The Playground User Interface represents I/O pins 0 to 9 on the edge connector of the micro:bit. Each pin can be switched on (3 volts) by pressing the black dot or off (0 volts) by pressing the red dot.

Pins 0 - 3 can be switched to Analogue (A) or Digital (D) by pressing the yellow buttons. In analogue mode the pin voltages can be set by moving the corresponding sliders.

The voltage on the pins can be Written (W) or Read (R) by pressing the grey button.

Temperature

For information on programming the micro:bit to use the Temperature service see: Temperature service.

The playground reports the temperature of the micro:bit processor in centigrade. The interval the temperature is reported can be adjusted from 100 milliseconds to 1 minute. An indicator flashes to show a temperature reading has been taken.

UART

For information on using the UART service see: UART service.

The following micro:bit program can be used with the playground to demonstrate the UART service:

makecode_UART

Press button A on the micro:bit and see the text ('Hello') sent to the playground.

Type some text in the UART input field followed by '$' and press return on the iPad. The text will be transmitted to the micro:bit and scrolled across the LED matrix.

Beacon

Beacons are not Bluetooth services, they utilise a bluetooth peripherals ability to advertise services. Beacons advertise small amounts of information, allowing devices like smartphones to detect their proximity to the beacon. There are various beacon message formats, which define the way bluetooth advertising packets are used. The micro:bit uses the
Eddystone format, whereas Apple operating systems use the iBeacon format.

The full potential of beacon technology is exploited on Apple platforms using the 'Core Location' API which is not supported by the micro:bit, however, it's still possible to demonstrate beacons using the micro:bit playground and Eddystone protocols.

For programming information using Beacons see : Advertise URL and

Advertise UID.

The following micro:bit program broadcasts a UID every second. Each time the UID is broadcast it increments the instance element. This is necessary because, by default, the Apple software amalgamates similar messages, so if the UID remains constant, the playground would not show each broadcast message.

makecode-Beacon

To demonstrate the program:

The playground will show micro:bit advertisement data and the received signal strength indication (RSSI). The RSSI can be used as a crude indication of the proximity to the micro:bit.

Appendix A - Microbit API

The Microbit API is contained in the Microbit.swift file which is simply added to an Xcode project. The file contains:

MicrobitDelegate Protocol

Classes implementing the Microbit API should conform to the MicrobitDelegate protocol. Dummy implementations of the protocol functions are included in the Microbit.swift file eliminating the need to implement functions that are not required.

The following delegate functions are available:

Microbit Class

The Microbit class forms the entire API. It should be initialised only once.

Initialiser

init(_ deviceName:String)

Parameters:

example:

let microbit = Microbit("BBC micro:bit [tizip]")

startScanning

func startScanning()

stopScanning

func stopScanning()

disconnect

func disconnect()

ledText

func ledText(message:String,scrollRate:Int16)

Parameters:

ledWrite

func ledWrite(matrix:[UInt8])

Parameter:

uartSend

func uartSend(message:String)

Parameter:

pinConfigure

func pinConfigure(analougePins:[UInt8:Bool])

Parameter:

func pinConfigure(readPins:[UInt8:Bool])

Parameter:

pinSet

func pinSet(pinValues:[UInt8:UInt8])

Parameter:

accelerometer

func accelerometer(period:PeriodType)

Parameter:

magnetometer

func magnetometer(period:PeriodType)

Parameter:

temperature

func temperature(period:UInt16)

Parameter:

raiseEvent

func raiseEvent(event:MicrobitEvent,value:UInt16

Parameters:

registerEvents

func registerEvents(events:[Int16])

Parameter: