Skip to content

uBit.compass

Overview

micro:bit V2 is equipped with the ST LSM303AGR combined accelerometer and magnetometer, which means it's possible to sense magnetic field strength, and tilt on 3 axes (x, y, and z).

The magnetometer provides information about the magnetic field where a micro:bit is situated, crucially providing an indication of where magnetic north is located.

Raw magnetic field information alone is not enough to provide accurate compass headings. Therefore, the accelerometer is used in conjunction with the magnetometer to reduce the inaccuracy of the magnetometer reading.

The magnetometer is inaccurate because it considers all 3 planes: x, y and z. The heading north only exists in the horizontal planes (x and y), therefore we only need values in these planes. The accelerometer is used to filter out the vertical plane (z) to make our headings far more accurate. You can see this in action when calibrating the compass.

After calibration has been performed, the end product is an e-compass!

Real time updates

When using the standard uBit presentation, the compass is continuously updated in the background using an idle thread (after it is first used), which is executed whenever the micro:bit has no other tasks to perform.

If for some reason there is no scheduler running, you can drive compass updates manually with requestUpdate().

Using the compass

As with most measuring components on the micro:bit, you can subscribe to events posted by the compass. See Message Bus for more information about events and handlers.

For most intents and purposes, you will use the compass to get the heading of the micro:bit, as following:

Example

uBit.compass.calibrate(); // This is done automatically the first time you try to read from the compass, but you can still call it manually later.
int heading = uBit.compass.heading();

Note

This returns the heading, in degrees, relative to magnetic north.

You can also supply a custom calibrator if the default one does not do what you require with setCalibrator().

Message Bus Info

Message Bus IDs

Constant Value
DEVICE_ID_COMPASS 6

Message Bus Events

Constant Value
COMPASS_EVT_DATA_UPDATE 1
COMPASS_EVT_CONFIG_NEEDED 2
COMPASS_EVT_CALIBRATE 3
COMPASS_EVT_CALIBRATION_NEEDED 4

API

heading

int
heading
()

Description

Gets the current heading of the device, relative to magnetic north.

If the compass is not calibrated, it will raise the COMPASS_EVT_CALIBRATE event.

Users wishing to implement their own calibration algorithms should listen for this event, using MESSAGE_BUS_LISTENER_IMMEDIATE model. This ensures that calibration is complete before the user program continues.

Returns

the current heading, in degrees. Or CALIBRATION_IN_PROGRESS if the compass is calibrating.

Example
 compass.heading(); 

getFieldStrength

int
getFieldStrength
()

Description

Determines the overall magnetic field strength based on the latest update from the magnetometer.

Returns

The magnetic force measured across all axis, in nano teslas.

Example
 compass.getFieldStrength(); 

calibrate

int
calibrate
()

Description

Perform a calibration of the compass.

This method will be called automatically if a user attempts to read a compass value when the compass is uncalibrated. It can also be called at any time by the user.

The method will only return once the compass has been calibrated.

Returns

MICROBIT_OK, MICROBIT_I2C_ERROR if the magnetometer could not be accessed, or MICROBIT_CALIBRATION_REQUIRED if the calibration algorithm failed to complete successfully.

Note

THIS MUST BE CALLED TO GAIN RELIABLE VALUES FROM THE COMPASS


setCalibration

void
setCalibration
(
CompassCalibration
calibration)

Description

Configure the compass to use the calibration data that is supplied to this call.

Calibration data is comprised of the perceived zero offset of each axis of the compass.

After calibration this should now take into account trimming errors in the magnetometer, and any "hard iron" offsets on the device.

calibration

A Sample3D containing the offsets for the x, y and z axis.

Parameters

CompassCalibration
calibration - A Sample3D containing the offsets for the x, y and z axis.


getCalibration

CompassCalibration
getCalibration
()

Description

Provides the calibration data currently in use by the compass.

More specifically, the x, y and z zero offsets of the compass.

Returns

A Sample3D containing the offsets for the x, y and z axis.


isCalibrated

int
isCalibrated
()

Description

Returns 0 or 1. 1 indicates that the compass is calibrated, zero means the compass requires calibration.


isCalibrating

int
isCalibrating
()

Description

Returns 0 or 1. 1 indicates that the compass is calibrating, zero means the compass is not currently calibrating.


clearCalibration

void
clearCalibration
()

Description

Clears the calibration held in persistent storage, and sets the calibrated flag to zero.


configure

int
configure
()

Description

Configures the device for the sample rate defined in this object. The nearest values are chosen to those defined that are supported by the hardware. The instance variables are then updated to reflect reality.

Returns

MICROBIT_OK on success, MICROBIT_I2C_ERROR if the compass could not be configured.


setAccelerometer

void
setAccelerometer
(
MicroBitAccelerometer &
accelerometer)

Description

Defines the accelerometer to be used for tilt compensation.

acceleromter

Reference to the accelerometer to use.

Parameters

MicroBitAccelerometer &
accelerometer


setPeriod

int
setPeriod
(
int
period)

Description

Attempts to set the sample rate of the compass to the specified period value (in ms).

Parameters

int
period - the requested time between samples, in milliseconds.

Returns

MICROBIT_OK on success, MICROBIT_I2C_ERROR is the request fails.

Note

The requested rate may not be possible on the hardware. In this case, the nearest lower rate is chosen.


getPeriod

int
getPeriod
()

Description

Reads the currently configured sample rate of the compass.

Returns

The time between samples, in milliseconds.


requestUpdate

int
requestUpdate
()

Description

Poll to see if new data is available from the hardware. If so, update it. n.b. it is not necessary to explicitly call this funciton to update data (it normally happens in the background when the scheduler is idle), but a check is performed if the user explicitly requests up to date data.

Returns

MICROBIT_OK on success, MICROBIT_I2C_ERROR if the update fails.

Note

This method should be overidden by the hardware driver to implement the requested changes in hardware.


update

int
update
()

Description

Stores data from the compass sensor in our buffer.

On first use, this member function will attempt to add this component to the list of fiber components in order to constantly update the values stored by this object.

This lazy instantiation means that we do not obtain the overhead from non-chalantly adding this component to fiber components.

Returns

MICROBIT_OK on success, MICROBIT_I2C_ERROR if the read request fails.


getSample

Sample3D
getSample
(
CoordinateSystem
coordinateSystem)

Description

Reads the last compass value stored, and provides it in the coordinate system requested.

Parameters

CoordinateSystem
coordinateSystem

Returns

The force measured in each axis, in milli-g.


getX

int
getX
()

Description

reads the value of the x axis from the latest update retrieved from the compass, using the default coordinate system as specified in the constructor.

Returns

the force measured in the x axis, in milli-g.


getY

int
getY
()

Description

reads the value of the y axis from the latest update retrieved from the compass, using the default coordinate system as specified in the constructor.

Returns

the force measured in the y axis, in milli-g.


getZ

int
getZ
()

Description

reads the value of the z axis from the latest update retrieved from the compass, using the default coordinate system as specified in the constructor.

Returns

the force measured in the z axis, in milli-g.


updateSample

void
updateSample
()

Description

updateSample() method maintained here as an inline method purely for backward compatibility.


heading

int
heading
()

Description

Gets the current heading of the device, relative to magnetic north.

If the compass is not calibrated, it will raise the COMPASS_EVT_CALIBRATE event.

Users wishing to implement their own calibration algorithms should listen for this event, using MESSAGE_BUS_LISTENER_IMMEDIATE model. This ensures that calibration is complete before the user program continues.

Returns

the current heading, in degrees. Or CALIBRATION_IN_PROGRESS if the compass is calibrating.

Example
 compass.heading(); 

getFieldStrength

int
getFieldStrength
()

Description

Determines the overall magnetic field strength based on the latest update from the magnetometer.

Returns

The magnetic force measured across all axis, in nano teslas.

Example
 compass.getFieldStrength(); 

calibrate

int
calibrate
()

Description

Perform a calibration of the compass.

This method will be called automatically if a user attempts to read a compass value when the compass is uncalibrated. It can also be called at any time by the user.

The method will only return once the compass has been calibrated.

Returns

DEVICE_OK, DEVICE_I2C_ERROR if the magnetometer could not be accessed, or DEVICE_CALIBRATION_REQUIRED if the calibration algorithm failed to complete successfully.

Note

THIS MUST BE CALLED TO GAIN RELIABLE VALUES FROM THE COMPASS


setCalibration

void
setCalibration
(
CompassCalibration
calibration)

Description

Configure the compass to use the calibration data that is supplied to this call.

Calibration data is comprised of the perceived zero offset of each axis of the compass.

After calibration this should now take into account trimming errors in the magnetometer, and any "hard iron" offsets on the device.

calibration

A Sample3D containing the offsets for the x, y and z axis.

Parameters

CompassCalibration
calibration - A Sample3D containing the offsets for the x, y and z axis.


getCalibration

CompassCalibration
getCalibration
()

Description

Provides the calibration data currently in use by the compass.

More specifically, the x, y and z zero offsets of the compass.

Returns

A Sample3D containing the offsets for the x, y and z axis.


isCalibrated

int
isCalibrated
()

Description

Returns 0 or 1. 1 indicates that the compass is calibrated, zero means the compass requires calibration.


isCalibrating

int
isCalibrating
()

Description

Returns 0 or 1. 1 indicates that the compass is calibrating, zero means the compass is not currently calibrating.


clearCalibration

void
clearCalibration
()

Description

Clears the calibration held in persistent storage, and sets the calibrated flag to zero.


setAccelerometer

void
setAccelerometer
(
Accelerometer &
accelerometer)

Description

Defines the accelerometer to be used for tilt compensation.

acceleromter

Reference to the accelerometer to use.

Parameters

Accelerometer &
accelerometer


configure

int
configure
()

Description

Configures the device for the sample rate defined in this object. The nearest values are chosen to those defined that are supported by the hardware. The instance variables are then updated to reflect reality.

Returns

DEVICE_OK on success, DEVICE_I2C_ERROR if the compass could not be configured.


setPeriod

int
setPeriod
(
int
period)

Description

Attempts to set the sample rate of the compass to the specified period value (in ms).

Parameters

int
period - the requested time between samples, in milliseconds.

Returns

DEVICE_OK on success, DEVICE_I2C_ERROR is the request fails.

Note

The requested rate may not be possible on the hardware. In this case, the nearest lower rate is chosen.


getPeriod

int
getPeriod
()

Description

Reads the currently configured sample rate of the compass.

Returns

The time between samples, in milliseconds.


requestUpdate

int
requestUpdate
()

Description

Poll to see if new data is available from the hardware. If so, update it. n.b. it is not necessary to explicitly call this function to update data (it normally happens in the background when the scheduler is idle), but a check is performed if the user explicitly requests up to date data.

Returns

DEVICE_OK on success, DEVICE_I2C_ERROR if the update fails.

Note

This method should be overidden by the hardware driver to implement the requested changes in hardware.


update

int
update
()

Description

Stores data from the compass sensor in our buffer.

On first use, this member function will attempt to add this component to the list of fiber components in order to constantly update the values stored by this object.

This lazy instantiation means that we do not obtain the overhead from non-chalantly adding this component to fiber components.

Returns

DEVICE_OK on success, DEVICE_I2C_ERROR if the read request fails.


getSample

Sample3D
getSample
(
CoordinateSystem
coordinateSystem)

Description

Reads the last compass value stored, and provides it in the coordinate system requested.

Parameters

CoordinateSystem
coordinateSystem

Returns

The force measured in each axis, in milli-g.


Component Constructor

Advanced users only

Do not use this unless you really know what you're doing. It's usually best to use uBit.

MicroBitCompass(
MicroBitI2C &
i2c)

Description

Constructor. Create a software abstraction of an e-compass.

id

the unique EventModel id of this component. Defaults to: MICROBIT_ID_COMPASS

coordinateSpace

the orientation of the sensor. Defaults to: SIMPLE_CARTESIAN

Parameters

MicroBitI2C &
i2c

MicroBitCompass(
MicroBitI2C &
i2c,
uint16_t
id)

Description

Constructor. Create a software abstraction of an e-compass.

id

the unique EventModel id of this component. Defaults to: MICROBIT_ID_COMPASS

coordinateSpace

the orientation of the sensor. Defaults to: SIMPLE_CARTESIAN

Parameters

MicroBitI2C &
i2c

uint16_t
id - the unique EventModel id of this component. Defaults to: MICROBIT_ID_COMPASS