Skip to content

Bluetooth Low Energy on micro:bit V2

Introduction

The BBC micro:bit ships with a default Bluetooth profile included in the run-time firmware.

The profile consists of various "services" and "characteristics" designed to give easy access to the micro:bit's hardware so that initial exploration of the device's capabilities may take place using a corresponding application on another, compatible Bluetooth device such as a smartphone.

Given the nature of micro:bit and the tools which will be available to developers, it will be possible for the profile to be partly or completely changed and replaced with a profile of the developer's own design. The latter case is out of scope for this document which focuses on the standard, default profile only.

Profile Design

micro:bit acts as a Bluetooth GAP Peripheral and advertises so that GAP Central devices such as a smart phone can discover and connect to it.

Standard Bluetooth SIG "adopted" services have been used where appropriate in conjunction with custom services designed specifically for micro:bit.

The micro:bit default profile is based around the capabilities and features of the micro:bit device itself. It is not tightly coupled to any particular application of the device such as video control or telephony. It is however able to indicate actions it wishes a connected client device to perform or signal events that have occurred and which the client is expected to act upon in some way.

All services are "primary services" and so may be discovered and enumerated by a client wishing to determine the capabilities of the device.

Ease of use has been considered to be more important than having absolute configurability of all aspects of the hardware in the default profile.

The profile was designed using Bluetooth Developer Studio, a free of charge tool available for download from www.bluetooth.com

Bluetooth Security

micro:bit uses standard Bluetooth security. Bluetooth defines a series of optional security features of which the following are used for micro:bit:

  1. Pairing with passkey and MITM protection or "Just Works" pairing depending on micro:bit source code configuration

  2. White Listing

  3. Encrypted link for operations involving most characteristics

Pairing equips the micro:bit and a trusted peer device with the potential to perform security operations when interacting such as utilising an AES 128 bit encrypted link. All interactions involving custom services except for the DFU Control Service must be performed over an encrypted link. Note that encryption will be automatically applied whenever required. If a peer device is not paired with the micro:bit and a secure operation is attempted it will be rejected and the usual, expected behaviour of the peer is that it will initiate the pairing process automatically.

White listing allows paired devices only to connect to and interact with the micro:bit. Attempts to connect from devices not in the white list are ignored by the Bluetooth Link Layer.

Advertising

The micro:bit will advertise if in "pairing mode" or if it has been previously paired/bonded in which case it will advertise but a white list will be active and connections will only be accepted from previously paired devices. See below for more information on pairing.

In pairing mode the micro:bit will advertise with flags set indicating it is discoverable (LE General Discoverable Mode) as showing here:

Advertising in Pairing Mode

In “normal mode” (i.e. not pairing mode) advertising packets have neither the LE Limited Discoverable mode or the LE General Discoverable Mode flags set and so in this situation may not be listed in the “available Bluetooth devices” screen of some smartphones which have not paired with the micro:bit. This is by design.

Advertising in Normal Mode

Pairing

Code on a micro:bit may be created in such a way that pairing may or may not be required for interaction with Bluetooth services to be possible. If pairing is required, there are two forms which are supported.

Passkey Pairing involves the micro:bit displaying a randomly generated, 6 digit number to the user and the user then entering this into the other device. The video below shows this process.

Just Works Pairing does not require a passkey to be entered and pairing proceeds automatically, without further user interaction once it has been initiated with the micro:bit in pairing mode as usual.

How to pair your BBC micro:bit with an Android phone or tablet from Martin Woolley on Vimeo.

To pair with a micro:bit it must first be placed in "pairing mode". To do this, hold down both buttons A and B and press and hold the reset button. If powered by USB, let go of the reset button but keep holding both buttons A and B down. This will result in the micro:bit going into pairing mode and the words "PAIRING MODE" should be seen scrolling across the display followed by the graphical representation of the micro:bit 5 character identifier.

Next, initiate pairing on the peer device. On Android for example, go into Settings/Bluetooth and allow the system to scan for and discover the advertising micro:bit. Select it and pairing will commence. The micro:bit will indicate it's ready to pair by displaying an arrow which points left towards button A. What happens next depends on which pairing approach has been selected in the micro:bit configuration:

Passkey Pairing Press button A and a 6 digit number will be displayed on the micro:bit, one digit at a time. The peer device should now allow you to enter the 6 digit pass key. Do so and if the correct number was entered into the peer, micro:bit will display a tick/check to indicate pairing was achieved.

Just Works Pairing Press button A and the micro:bit and other device will automatically pair, with no further input required from the user. It just works. Hey, maybe that's where the name comes from!

A maximum of 4 devices may be paired with a micro:bit simultaneously (note though that only one paired device may connect to the micro:bit at a time).

Selecting Pairing Requirements

micro:bit code may stipulate that pairing is required and if so, which of the Just Works and Passkey pairing approaches is to be used. Alternatively, if may indicate that no pairing is required.

Important! If you do decide to disable pairing, be aware that your micro:bit now has no Bluetooth security. All communication will be "in clear" and there will be no control over who or what can connect to your micro:bit. Remember that as a Bluetooth "peripheral", it can only accept one connection at a time so if something other than your own peer device connects to your micro:bit, you will not be able to. If this does happen, or you suspect it to have happened, resetting the micro:bit will break the connection. It is recommended that you use the micro:bit display and the Bluetooth connection events in code to provide a visual indication of the connection status whether you use pairing or not.

Specifying your pairing requirement is done through a config.json file which should be in your project file hierarchy as shown:

Advertising in Pairing Mode

The following config.json properties are used to select pairing behaviours:

{
    "microbit-dal": {
        "bluetooth": {
            "pairing_mode": 1,
            "open": 0,
            "security_level": "SECURITY_MODE_ENCRYPTION_WITH_MITM",
        },
    }
}
pairing_mode controls whether or not micro:bit is able to switch into pairing mode. Required if you want to be able to pair your micro:bit.

open takes a value of 0 or 1. A value of 1 means no pairing is required and the security_level property is ignored if this value is specified.

security_level takes values SECURITY_MODE_ENCRYPTION_WITH_MITM for passkey pairing or SECURITY_MODE_ENCRYPTION_NO_MITM for just works pairing.

Reference Documentation

Details of the micro:bit's Bluetooth services, characteristics, the operations they each support and any associated descriptors along with UUID values can be found in the associated micro:bit Bluetooth profile specification

A simplified overview appears below.

GATT Services

Service Type micro:bit optionality Description
Generic Access Service Adopted mandatory Provides generic information about the device. Mandatory in GATT profiles.
Generic Attribute Service Adopted mandatory Can inform clients of changes in the attribute table such as reassigned handle values.Mandatory in GATT profiles.
Device Information Service Adopted mandatory Provides more comprehensive details about the device and its manufacturer
Accelerometer Service Custom optional Provides access to the accelerometer sensor state and configuration of the frequency with which readings are reported.
Magnetometer Service Custom optional Provides access to the magnetometer sensor state and configuration of the frequency with which readings are reported. Provides access to a "current bearing" value in degrees. Allows a connected client to initiate compass calibration.
Temperature Service Custom optional Provides access to a simplified, integer temperature measurement in celsius, derived from several sensors in the micro:bit.
Button Service Custom optional Allow button state changes to be notified to the client
LED Service Custom optional Allows access to both the LED "display" grid and the system status LED
IO Pin Service Custom optional Allows access to and configuration of IO pins on the edge connector.
Event Service Custom optional Allows the micro:bit to inform the connected client of the types of event it wants to be informed about. Allows the client to inform the micro:bit of relevant events. Allows micro:bit to inform the client of events originating on the micro:bit.Event data includes both a type and a reason or origin.
DFU Control Service Custom mandatory Used to initiate device firmware update. Defined by Nordic Semiconductor.
UART Service Custom optional Provides pseudo serial data communications over Bluetooth low energy, allowing arbitrary byte sequences to be exchanged in either direction with a connected peer. Data from micro:bit to peer is transmitted using Bluetooth Indications. Data from the peer to the micro:bit is transmitted using Write or Write No Response PDUs. This is an implementation of Nordic Semicondutor's UART/Serial Port Emulation over Bluetooth low energy.
Partial Flashing Service Custom mandatory Allows a client to update the MakeCode program on the Micro:Bit via BLE.

The maximum number of bytes which may be transmitted in one PDU is limited to the MTU minus three or 20 octets to be precise.

See https://developer.nordicsemi.com/nRF5_SDK/nRF51_SDK_v8.x.x/doc/8.0.0/s110/html/a00072.html for the original Nordic Semiconductor documentation by way of background.

Note: This service was added after micro:bits initially shipped to school and so is not in the default image. |

Known issue: the firmware on micro:bits shipped initially to schools contains the full Bluetooth profile. Once the software has been changed by flashing an application created using any of the on-line code editors however, all services are lost except for Device Information Service, Event Service and DFU Control Service. If you need other services you must restore your micro:bit to its original state by installing the default hex file or better still this hex file which does not use the display so you can use it over Bluetooth instead. A DAL 2.1.1 version of the all services hex file can be found here.

The following sections elaborate on the description of a service and/or its characteristics. For full details see the micro:bit Bluetooth profile specification

All Services Enabled Hex File

The 'bluetooth-services' hex file (Either without Magnetometer Service or without DFU Service) (originally written in C++) enables all the Bluetooth services listed below and will indicate when the micro:bit is connected and disconnected via Bluetooth. The source can be found here.

About the Device Information Service

This is an adopted service which defines 9 characteristics, all of which are optional members of of the service. For micro:bit we chose to include 3 of those characteristics only.

See https://developer.bluetooth.org/gatt/services/Pages/ServiceViewer.aspx?u=org.bluetooth.service.device_information.xml

About the Accelerometer Service

Characteristics

Accelerometer Data : Contains accelerometer measurements for X, Y and Z axes as 3 unsigned 16 bit values in that order and in little endian format. Data can be read on demand or notified periodically. Values are in the range +/-1000 and in milli-newtons.

Accelerometer Period: Determines the frequency with which accelerometer data is reported in milliseconds. Valid values are 1, 2, 5, 10, 20, 80, 160 and 640.

About the Magnetometer Service

Characteristics

Magnetometer Data : Contains magnetometer measurements for X, Y and Z axes as 3 unsigned 16 bit values in that order and in little endian format. Data can be read on demand or notified periodically.

Magnetometer Period : Determines the frequency with which magnetometer data is reported in milliseconds. Valid values are 1, 2, 5, 10, 20, 80, 160 and 640.

Magnetometer Bearing : Compass bearing in degrees from North.

Magnetometer Calibration : Used to trigger a magnetometer calibration. This is done by writing 0x01 to the characteristic.

Note: to deliver meaningful data the micro:bit magnetometer must first be calibrated. *.

* from v2.0.0 of the runtime onwards.

About the Temperature Service

Characteristics

Temperature : Signed integer 8 bit value in celsius.

Temperature Period : Determines the frequency with which temperature data is updated in milliseconds.

About the Button Service

The Button Service exposes the two buttons on the micro:bit and allows their state to be read on demand by a connected client or the client to subscribe to notifications of state change. 3 button states are defined and represented by a simple numeric enumeration: 0 = not pressed, 1 = pressed, 2 = long press.

About the LED Service

The service provides the client with direct control of each individual LED in the display grid. The client may also work at a higher level of abstraction and send strings of text to be displayed one character at a time on the LED display, with configurable scrolling transitions from one character to the next.

The LED Matrix State characteristic contains a bit mask which represents the on|off state of all 25 LEDs with a 0 bit value indicating LED OFF and a 1 indicating LED ON. The characteristic may be written or read in a single GATT operation allowing efficient manipulation of all LEDs in the grid.

The characteristic value consists of an array of 5 x utf8 octets, each representing one row of 5 LEDs.

Octet 0 represents the first row of LEDs i.e. the top row when the micro:bit is viewed with the edge connector at the bottom and USB connector at the top.

Octet 1 represents the second row and so on.

In each octet, bit 4 corresponds to the first LED in the row, bit 3 the second and so on.

Bit values represent the state of the related LED: off (0) or on (1).

So in summary, we have:

Octet 0, LED Row 1: bit4 bit3 bit2 bit1 bit0
Octet 1, LED Row 2: bit4 bit3 bit2 bit1 bit0
Octet 2, LED Row 3: bit4 bit3 bit2 bit1 bit0
Octet 3, LED Row 4: bit4 bit3 bit2 bit1 bit0
Octet 4, LED Row 5: bit4 bit3 bit2 bit1 bit0

Other characteristics allow a text string to be written to it by the client for display and the scrolling delay may be set.

Characteristics

LED Matrix State : Allows the state of any|all LEDs in the 5x5 grid to be set to on or off with a single GATT operation. Consists of a 32 bit field with bits 0 - 24 representing the off (0) or on (1) state of the corresponding LED.

LED Text : A UTF-8 string to be shown on the LED display. Maximum length 20 octets.

Scrolling Delay : Specifies a millisecond delay to wait for in between showing each character on the display.

About the IO Pin Service

Characteristics

Pin Data : Contains data relating to zero or more pins. Structured as a variable length array of up to 19 Pin Number / Value pairs. Pin Number and Value are each uint8 fields. Note however that the micro:bit has a 10 bit ADC and so values are compressed to 8 bits with a loss of resolution.

WRITE: Clients may write values to one or more pins in a single GATT write operation. A pin to which a value is to be written must have been configured for output using the Pin IO Configuration characteristic. Any attempt to write to a pin which is configured for input will be ignored.

NOTIFY: Notifications will deliver Pin Number / Value pairs for those pins defined as input pins by the Pin IO Configuration characteristic and whose value when read differs from the last read of the pin.

READ: A client reading this characteristic will receive Pin Number / Value pairs for all those pins defined as input pins by the Pin IO Configuration characteristic.

The associated Pin AD Configuration characteristic allows the client to indicate how each pin is to be used, as either an analogue or a digital pin.

Pin IO Configuration : A bit mask (32 bit) which defines which inputs will be read. If the Pin AD Configuration bit mask is also set the pin will be read as an analogue input, if not it will be read as a digital input.

Note that in practice, setting a pin's mask bit means that it will be read by the micro:bit runtime and, if notifications have been enabled on the Pin Data characteristic, data read will be transmitted to the connected Bluetooth peer device in a Pin Data notification. If the pin's bit is clear, it simply means that it will not be read by the micro:bit runtime. By default, pins are configured for output.

Pin AD Configuration : A bit mask which allows each pin to be configured for analogue or digital use. Bit n corresponds to pin n where 0 <= n < 19. A value of 0 means digital and 1 means analogue.

PWM Control : Allows a client to use up to 2 micro:bit pins at a time for PWM output and to set the period and value of the pin(s). This is useful for applications such as the analogue control of LEDs and simple audio tone generation. Note that not all pins support PWM on micro:bit.

About the Event Service

The Event Service allows events or commands to be notified to the micro:bit by a connected client and it allows micro:bit to notify the connected client of events or commands originating from with the micro:bit. The micro:bit can inform the client of the types of event it is interested in being informed about (e.g. an incoming call) and the client can inform the micro:bit of types of event it wants to be notified about. The term "event" will be used here for both event and command types of data.

Events may have an associated value.

Note that specific event ID values including any special values such as those which may represent wild cards are not defined here. The micro:bit run time documentation should be consulted for this information.

Multiple events of different types may be notified to the client or micro:bit at the same time.

Event data is encoded as an array of structs each encoding an event of a given type together with an associated value. Event Type and Event Value are both defined as uint16 and therefore the length of this array will always be a multiple of 4.

struct event { uint16 event_type; uint16 event_value;};

event_type and event_value are each encoded in little endian format.

The Event Service has four characteristics in total:

micro:bit Requirements is a variable length list of event data structures which indicates the types of client event, potentially with a specific value which the micro:bit wishes to be informed of when they occur. The client should read this characteristic when it first connects to the micro:bit. It may also subscribe to notifications to that it can be informed if the value of this characteristic is changed by the micro:bit firmware.

Note that an event_type of zero means ANY event type and an event_value part set to zero means ANY event value.

Client Requirements is a variable length list of event data structures which indicates the types of micro:bit event, potentially with a specific value which the client wishes to be informed of when they occur. The client should write to this characteristic when it first connects to the micro:bit.

Note that an event_type of zero means ANY event type and an event_value part set to zero means ANY event value.

micro:bit Event contains one or more event structures which should be notified to the client. It supports notifications and as such the client should subscribe to notifications from this characteristic.

Client Event is a writable characteristic which the client may write one or more event structures to, to inform the micro:bit of events which have occurred on the client. These should be of types indicated in the micro:bit Requirements characteristic bit mask.

About the DFU Control Service

Allows clients to initiate the micro:bit pairing and over the air firmware update procedures. Firmware updates are actually handled by the Nordic Semiconductor DFU service which is not part of this profile, after the micro:bit enters an alternate bootloader.

Characteristics

DFU Control : Writing 0x01 initiates rebooting the micro:bit into the Nordic Semiconductor bootloader if the DFU Flash Code characteristic has been written to with the correct secret key. Writing 0x02 to this characteristic means "request flash code".

About the UART Service

Provides a pseudo serial interface to the micro:bit for the exchange of arbitrary sequences of bytes. A maximum of 20 octets (MTU of 23 minus 3) can be transmitted in a single operation but a series of operations can be executed to affect something like serial data communications.

This is an implementation of the Nordic Semiconductor UART service:

https://developer.nordicsemi.com/nRF5_SDK/nRF51_SDK_v8.x.x/doc/8.0.0/s110/html/a00072.html

Characteristics

TX Characteristic: Allows the micro:bit to transmit a byte array containing an arbitrary number of arbitrary octet values to a connected device. Uses Indications for this purpose.

RX Characteristic: Allows a connected client to send a byte array containing an arbitrary number of arbitrary octet values to a connected micro:bit using with Write Requests or Write Commands.

About the Partial Flashing Service

Allows clients to update the MakeCode section of firmware over a BLE connection. This is a faster method than using the DFU Control service but will not work across different versions of the DAL e.g. Bluetooth vs Radio.

Characteristics

Partial Flash Characteristic : This is used to control the memory map and transfer data to be written to the flash storage. A write request beginning 0x00 is used to request for information from the Memory Map, and a request beginning 0x01 is used to transfer data to be written to the flash.

Using the Bluetooth Profile

Click on the Bluetooth menu and then select one of the Bluetooth services for a page of information dedicated to that service including information for application developers.

Martin Woolley's personal blog contains a series of micro:bit Bluetooth demonstration videos. See http://bluetooth-mdw.blogspot.co.uk/p/bbc-microbit.html

The Android application featured in the videos was written by Martin and contains a series of demonstrations, each exercising at least one of the micro:bit Bluetooth services. The application available in github. Information regarding the use of each service appears in the individual service pages of this site.