Skip to content

uBit.accelerometer

Overview

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

The accelerometer on the micro:bit detects the acceleration (in milli-g) in 3 planes: x and y (the horizontal planes), and z (the vertical plane).

As well as detecting acceleration, accelerometers can also detect orientation, which is used in smartphones and tablets to rotate content as you tilt the device. This means that the micro:bit can infer its own orientation as well!

As well as being used to detect acceleration, accelerometers are also used to detect the rate of deceleration. A great example of an application of accelerometers are airbags in modern vehicles, where an accelerometer is used to detect the rapid deceleration of a vehicle. If rapid deceleration were to occur, the airbags are deployed.

Accelerometers can also be used to detect when an object is in free fall, which is when only the force gravity is acting upon an object. If you were to throw a ball directly into the air, free fall would begin as soon as the ball begins its decent after the acceleration from your throw has subsided.

Read more about the technicalities of this component on the tech site.

Real time updates

When using the standard uBit presentation, the accelerometer 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 accelerometer updates manually with requestUpdate().

Using the Accelerometer

With Events

While uBit.accelerometer provides a lot of internal values you can query, they can be quite cumbersome to deal with. In a lot of cases, we just want to know when something happens on a particular component. For this, CODAL has an event system you can use. The accelerometer continuously fires events on the Message Bus and you can listen for them. The full list is below, but this snippet shows how you could detect a shaking motion on your micro:bit:

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
void onShake(Event){
    uBit.display.scroll("Shake!");
}

int main()
{
    uBit.init();
    uBit.messageBus.listen(DEVICE_ID_GESTURE, ACCELEROMETER_EVT_SHAKE, onShake);
    release_fiber();
}

Flash this to your micro:bit and voilĂ ; the onShake() method is called and the text scrolls across the display.

You can use any of the events listed below for finer gesture controls; just subscribe to it as above and register your handler.

Note

For more information about events and handlers, have a look at the pages for Message Bus and Event.

Without Events

uBit.accelerometer contains everything you need to access orientation and motion readings from the LSM303AGR. It'll be more complex this way, but it will let you fine tune how you use the accelerometer. For example, here's how you could make a spirit level reader using raw accelerometer information.

First, you'd need to find a way of converting the raw milli-g information into a pixel value:

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
int g_to_pix(int g)
{
    int v = 2;
    if ( g < -200) v--;
    if ( g < -500) v--;
    if ( g > 200) v++;
    if ( g > 500) v++;

    return v;
} 

Then, you could simply query the accelerometer's X and Y values and display them as a point on the display:

Example

1
2
3
4
5
6
7
8
9
while(true) {
    int px = g_to_pix(uBit.accelerometer.getX());
    int py = g_to_pix(uBit.accelerometer.getY());

    uBit.display.image.clear(); // Without this, we'd be painting the screen!
    uBit.display.image.setPixelValue(px,py,255);

    uBit.sleep(100);
}

Flash this to your micro:bit and you'll see a nice dot whizzing around on your screen in relation to the tilt of your device!

Message Bus Info

Message Bus IDs

Name Value
DEVICE_ID_ACCELEROMETER 4
DEVICE_ID_GESTURE 27

Message Bus Events

DEVICE_ID_ACCELEROMETER

Name Value
ACCELEROMETER_EVT_DATA_UPDATE 1

DEVICE_ID_GESTURE

Name Value
ACCELEROMETER_EVT_TILT_UP 1
ACCELEROMETER_EVT_TILT_DOWN 2
ACCELEROMETER_EVT_TILT_LEFT 3
ACCELEROMETER_EVT_TILT_RIGHT 4
ACCELEROMETER_EVT_FACE_UP 5
ACCELEROMETER_EVT_FACE_DOWN 6
ACCELEROMETER_EVT_FREEFALL 7
ACCELEROMETER_EVT_3G 8
ACCELEROMETER_EVT_6G 9
ACCELEROMETER_EVT_8G 10
ACCELEROMETER_EVT_SHAKE 11

API

setPeriod

int
setPeriod
(
int
period)

Description

Attempts to set the sample rate of the accelerometer to the specified 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 accelerometer.

Returns

The time between samples, in milliseconds.


setRange

int
setRange
(
int
range)

Description

Attempts to set the sample range of the accelerometer to the specified value (in g).

Parameters

int
range - The requested sample range of samples, in g.

Returns

MICROBIT_OK on success, MICROBIT_I2C_ERROR is the request fails.

Note

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


getRange

int
getRange
()

Description

Reads the currently configured sample range of the accelerometer.

Returns

The sample range, in g.


configure

int
configure
()

Description

Configures the accelerometer for G range and 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 accelerometer could not be configured.

Note

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


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.


getSample

Sample3D
getSample
(
CoordinateSystem
coordinateSystem)

Description

Reads the last accelerometer 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 accelerometer, 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 accelerometer, 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 accelerometer, using the default coordinate system as specified in the constructor.

Returns

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


getPitch

int
getPitch
()

Description

Provides a rotation compensated pitch of the device, based on the latest update retrieved from the accelerometer.

Returns

The pitch of the device, in degrees.

Example
 accelerometer.getPitch(); 

getPitchRadians

float
getPitchRadians
()

Description

Provides a rotation compensated pitch of the device, based on the latest update retrieved from the accelerometer.

Returns

The pitch of the device, in radians.

Example
 accelerometer.getPitchRadians(); 

getRoll

int
getRoll
()

Description

Provides a rotation compensated roll of the device, based on the latest update retrieved from the accelerometer.

Returns

The roll of the device, in degrees.

Example
 accelerometer.getRoll(); 

getRollRadians

float
getRollRadians
()

Description

Provides a rotation compensated roll of the device, based on the latest update retrieved from the accelerometer.

Returns

The roll of the device, in radians.

Example
 accelerometer.getRollRadians(); 

getGesture

uint16_t
getGesture
()

Description

Retrieves the last recorded gesture.

Returns

The last gesture that was detected.

Example
 if (accelerometer.getGesture() == SHAKE) 
 display.scroll("SHAKE!"); 

setPeriod

int
setPeriod
(
int
period)

Description

Attempts to set the sample rate of the accelerometer to the specified 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 accelerometer.

Returns

The time between samples, in milliseconds.


setRange

int
setRange
(
int
range)

Description

Attempts to set the sample range of the accelerometer to the specified value (in g).

Parameters

int
range - The requested sample range of samples, in g.

Returns

DEVICE_OK on success, DEVICE_I2C_ERROR is the request fails.

Note

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


getRange

int
getRange
()

Description

Reads the currently configured sample range of the accelerometer.

Returns

The sample range, in g.


configure

int
configure
()

Description

Configures the accelerometer for G range and 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 accelerometer could not be configured.

Note

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


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 accelerometer sensor in our buffer, and perform gesture tracking.

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 accelerometer value stored, and provides it in the coordinate system requested.

Parameters

CoordinateSystem
coordinateSystem

Returns

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


getPitch

int
getPitch
()

Description

Provides a rotation compensated pitch of the device, based on the latest update retrieved from the accelerometer.

Returns

The pitch of the device, in degrees.

Example
 accelerometer.getPitch(); 

getPitchRadians

float
getPitchRadians
()

Description

Provides a rotation compensated pitch of the device, based on the latest update retrieved from the accelerometer.

Returns

The pitch of the device, in radians.

Example
 accelerometer.getPitchRadians(); 

getRoll

int
getRoll
()

Description

Provides a rotation compensated roll of the device, based on the latest update retrieved from the accelerometer.

Returns

The roll of the device, in degrees.

Example
 accelerometer.getRoll(); 

getRollRadians

float
getRollRadians
()

Description

Provides a rotation compensated roll of the device, based on the latest update retrieved from the accelerometer.

Returns

The roll of the device, in radians.

Example
 accelerometer.getRollRadians(); 

getGesture

uint16_t
getGesture
()

Description

Retrieves the last recorded gesture.

Returns

The last gesture that was detected.

Example
 if (accelerometer.getGesture() == SHAKE) 
 display.scroll("SHAKE!"); 

Component Constructor

Advanced users only

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

MicroBitAccelerometer(
MicroBitI2C &
i2c)

Description

Constructor. Create a software abstraction of an accelerometer.

coordinateSpace

the orientation of the sensor. Defaults to: SIMPLE_CARTESIAN

id

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

Parameters

MicroBitI2C &
i2c

MicroBitAccelerometer(
MicroBitI2C &
i2c,
uint16_t
id)

Description

Constructor. Create a software abstraction of an accelerometer.

coordinateSpace

the orientation of the sensor. Defaults to: SIMPLE_CARTESIAN

id

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

Parameters

MicroBitI2C &
i2c

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