An accelerometer measures the acceleration of micro:bit; this component senses when the micro:bit is moved.

Accelerometer measures movement along three axes:

  • X – tilting from left to right.
  • Y – tilting forwards and backwards.
  • Z – moving up and down.
from microbit import *

while True:
    reading = accelerometer.get_x()
    if reading > 20:
        display.show("R")
    elif reading < -20:
        display.show("L")
    else:
        display.show("-")

The method get_x, get_y, and get_z returns a positive or negative number indicating a measurement for each axis.

DIY

Program the micro:bit to scroll the message ‘Don’t shake me!’ when you move the micro:bit.

Help: the method accelerometer.was_gesture("shake") is True if micro:bit card was shake.