TigerJython4Kids | robotics |
YOU LEARN HERE... |
how to use the accelerometer to detect changes in position and movements of the micro:bit. |
SENSOR VALUES |
The acceleration sensor (also called accelerometer) measures the constant gravitational acceleration of approx 10 m/s2, which points vertically downwards and the accelerations caused by movements (changes of velocity).
It is similar to the values displayed in a aircraft (artificial horizon). If you tilt the board forwards or backwards, the pitch angle will change, while the sideways tilt will change the roll angle. In the program you use the accelerometer object and call accelerometer.get_x(), accelerometer.get_y() or accelerometer.get_z(). The sensor values are in the range of about -2000 to 2000 and correspond to the accelerations -20 m/x2 and 20 m/s2. |
EXAMPLES |
Retrieve sensor values Start the program below, tilt the micro:bit from the horizontal position to the left or to the right and observe the sensor values that are written out in the terminal window.
Program: from microbit import * while True: acc = accelerometer.get_x() print (acc) if acc > 0: display.show(Image.ARROW_E) else: display.show(Image.ARROW_W) sleep(100)
Only one pixel is displayed, which shifts to the right, left, up or down depending on the inclination. The aim is to align the spirit level so that the middle LED lights up. Program: from microbit import * x = 1 y = 1 while True: accX = accelerometer.get_x() accY = accelerometer.get_y() if accX > 100 and x < 4: x += 1 elif accX < -100 and x > 0: x -= 1 elif accY > 100 and y < 4: y += 1 elif accY < -100 and y > 0: y -= 1 display.clear() display.set_pixel(x, y, 9) sleep(100) |
MEMO |
With the accelerometer you determine the movements and the position of the micro:bit. Usually you request the sensor value regularly every 10 to 100 milliseconds in a endless loop. You say that you are "polling" sensor values in a measurement loop. |
EXERCISES |
|
Acceleration generally means the rate of change of velocity, that is, one-dimensional
where v is the speed.
From the three acceleration components you can calculate pitch and roll angles as shown below. Start the following program and tilt the board sideways or forwards and backwards. In the terminal window, the values of pitch and roll are written out in degrees.
from microbit import * from math import * def getPitch(): a = accelerometer.get_values() pitch = atan2(a[1], -a[2]) return int(degrees(pitch)) def getRoll(): a = accelerometer.get_values() anorm = sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2]) roll = asin(a[0] / anorm) return int(degrees(roll)) while True: pitch = getPitch() roll = getRoll() print("p: " + str(pitch)) print("r: " + str(roll)) print() sleep(100)