/* jquery */ /* jquery accordion style*/ /* jquery init */

Spirit Level (micro:bit MicroPython)

This time we'll create a spirit level that uses x-axis data from the micro:bit's built-in accelerometer sensor.

from microbit import *

while True:
   # obtain the accelerometer x-axis value
   x = accelerometer.get_x()
   # perform an integer division
   val = x // 20
   # test the value
   if val > 0:
      display.show(Image.ARROW_E)
   elif x < 0:
      display.show(Image.ARROW_W)
   else:
      # Yes – I am level
      display.show(Image.YES)

The micro:bit's accelerometer is sensitive to the slightest movement. In fact, it is too sensitive for our purposes. So here we take the returned accelerometer x value and divide it by 20 using the integer divide // symbol.

For a simple coding challenge try changing the integer division value from twenty to something smaller or larger, then discover how much harder or easier it is keep level.

A more advanced coding challenge would be to create a dual axis spirit level using both the get_x() and get_y() accelerometer functions.

Return to the BBC micro:bit MicroPython Coding Tutorials page.

No comments: