micro:bit(SR) → MakeCode(SR) → The accelerometer on the micro:bit: tilt, shaking and movement
The accelerometer on the micro:bit: tilt, shaking and movement
Lesson 8 of 14 · micro:bit
On the back of the micro:bit there is an accelerometer – a sensor that measures acceleration in three directions. Since gravity always acts on the device, the accelerometer "knows" how the micro:bit is tilted. That is why it can recognize shaking, turning the screen up or down and tilting left and right. In this lesson we make a dice for games, a spirit level (tilt meter) and a step counter.
Before you start: required prior knowledge – loops, branching and the Logic palette. How to learn: build every example in MakeCode and try it in the simulator (or on the device), and solve the tasks at the end on your own first; open the instructions and the solution only after that. The programs are given as blocks (description) and in JavaScript from MakeCode: in the editor click JavaScript, paste the code and go back to Blocks – you will get the same blocks.
Three axes: x, y and z
The accelerometer measures acceleration along three axes. The value is given in milli-g (mg): 1000 mg is the acceleration due to gravity.
Axis
Direction
When the value is large
x
left – right
the micro:bit is tilted to the right (positive) or to the left (negative)
y
forward – backward
tilted towards you or away from you
z
up – down
lying on the table: about −1000 (screen up)
strength
total strength
about 1000 at rest, more when shaken
The block acceleration (mg) x is in the palette Input → more. The following program shows the value of one axis when a button is pressed:
input.onButtonPressed(Button.A, function () {
basic.showNumber(input.acceleration(Dimension.X)) // tilt left-right
})
input.onButtonPressed(Button.B, function () {
basic.showNumber(input.acceleration(Dimension.Y)) // tilt forward-backward
})
input.onButtonPressed(Button.AB, function () {
basic.showNumber(input.acceleration(Dimension.Strength)) // total strength
})
Try it in the simulator: move the micro:bit in the picture with the mouse and watch how the numbers change. On a real device, tilt it and press a button.
Gestures: shaking, tilting, turning
For the most common movements we do not have to compare numbers – there is the block on shake (Input palette). Its drop-down list contains other gestures too:
Gesture
What it means
shake
the micro:bit has been shaken
logo up / logo down
the logo (top edge) is turned up / down
screen up / screen down
the screen faces the sky / the table
tilt left / tilt right
tilted to the left / to the right
free fall
the device is falling
3g, 6g, 8g
a strong hit (large acceleration)
Example: an electronic dice. When the micro:bit is shaken, it shows a random number from 1 to 6.
input.onGesture(Gesture.Shake, function () {
let number = randint(1, 6) // random number from 1 to 6
basic.showNumber(number)
})
With blocks:
on shake (Input)
inside it show number (Basic), and in the number field pick random 1 to 6 (Math)
Gestures can be combined. This program shows an arrow in the direction in which the device is tilted:
input.onGesture(Gesture.TiltLeft, function () {
basic.showArrow(ArrowNames.West) // arrow to the left
})
input.onGesture(Gesture.TiltRight, function () {
basic.showArrow(ArrowNames.East) // arrow to the right
})
input.onGesture(Gesture.ScreenDown, function () {
basic.clearScreen() // the screen faces the table – we turn it off
})
Tilt angle and the spirit level
The block rotation (°) pitch gives the forward-backward tilt angle, and rotation (°) roll the left-right angle, in degrees (from −180 to 180). When the micro:bit lies flat, both angles are close to 0.
A spirit level shows whether a surface is level. One dot lights up on the screen – the "bubble". When the device is level, the dot is in the middle (2, 2); when we tilt it, the dot runs to that side. We turn an angle from −45° to 45° into a column from 0 to 4 with the block map (Math palette):
let x = 2
let y = 2
basic.forever(function () {
// we turn an angle from -45 to 45 degrees into a column/row from 0 to 4
x = Math.round(Math.map(input.rotation(Rotation.Roll), -45, 45, 0, 4))
y = Math.round(Math.map(input.rotation(Rotation.Pitch), -45, 45, 0, 4))
x = Math.constrain(x, 0, 4) // we do not go outside the screen
y = Math.constrain(y, 0, 4)
basic.clearScreen()
led.plot(x, y) // the "bubble"
basic.pause(50)
})
The block constrain "cuts" the value to the given limits: if the angle is greater than 45°, map would give a number greater than 4, and there is no such column.
Step counter with a threshold
In the lesson about variables the step counter used on shake. Counting is more accurate when we set the threshold ourselves: a step is the moment when the total strength of the acceleration exceeds, for example, 1500 mg.
let steps = 0
basic.forever(function () {
if (input.acceleration(Dimension.Strength) > 1500) {
steps += 1
basic.showNumber(steps)
basic.pause(300) // we do not count one step twice
}
})
input.onButtonPressed(Button.A, function () {
steps = 0 // zero for a new measurement
basic.showNumber(steps)
})
The pause of 300 ms is important: one step is short, but without the pause the loop would count it several times. Try different thresholds (1300, 1800) and check which one counts your steps best.
Practice tasks
For every task there is an example, instructions and a solution. The solutions have been checked against the examples in the text.
TASK 01Difficulty: easy
Impact meter
Write a program that constantly shows a graph of the acceleration strength with the block plot bar graph (Led palette): at rest only a few LEDs are lit, and when the micro:bit is shaken – the whole screen.
Example
Output
at rest the bottom row is lit, when shaken hard the whole screen
Instructions
In the forever block use led.plotBarGraph(value, maximum). Use 3000 as the maximum value.
Solution (JavaScript in MakeCode)
basic.forever(function () {
// graph: how many LEDs are lit depends on the strength of the acceleration
led.plotBarGraph(input.acceleration(Dimension.Strength), 3000)
})
TASK 02Difficulty: medium
Keep it level!
A game: pressing A starts the measurement. For every second in which the micro:bit is level (both angles between −10° and 10°) you get a point. When the device is tilted more, the game ends and shows the number of points.
Example
Output
after A: a heart while the device is level; when it is tilted – the number of points won
Instructions
Use a while loop with a compound condition (and) and the function Math.abs for the absolute value of the angle.
Solution (JavaScript in MakeCode)
input.onButtonPressed(Button.A, function () {
let points = 0
// while both angles are small, the micro:bit is "level"
while (Math.abs(input.rotation(Rotation.Roll)) < 10 && Math.abs(input.rotation(Rotation.Pitch)) < 10) {
basic.showIcon(IconNames.Heart)
basic.pause(1000)
points += 1
}
basic.showNumber(points)
})
TASK 03Difficulty: medium
Dice with two dice
When the micro:bit is shaken, it "throws" two dice: it shows the first number, then the second, then their sum. If both numbers are the same, it also shows a happy face.
Example
Output
e.g. 3, 5, 8 – or 4, 4, 8 and a happy face
Instructions
Two variables get their values with the block pick random 1 to 6; for the same number use if with the condition ==.
Solution (JavaScript in MakeCode)
input.onGesture(Gesture.Shake, function () {
let first = randint(1, 6)
let second = randint(1, 6)
basic.showNumber(first)
basic.showNumber(second)
basic.showNumber(first + second) // sum
if (first == second) {
basic.showIcon(IconNames.Happy) // a double
}
})
Common mistakes and tips
The accelerometer also measures gravity – that is why a micro:bit resting on a table does not show zero on the z axis, but about −1000.
In a loop that measures movement, always put a short pause, otherwise one movement is counted several times.
If the block map can give a value outside the screen, limit it with the block constrain.
The shake gesture is enough for games; for accurate measurement use numbers and your own threshold.
Check your knowledge
Open the quiz
Accelerometer
1. What does the accelerometer measure?
2. Approximately what is acceleration strength when the micro:bit is at rest?
3. Which gesture happens when the micro:bit is tilted to the left?
4. What is constrain(x, 0, 4) for?
Podešavanja kolačića
Koristimo kolačiće da bismo vam pružili najbolje moguće iskustvo. Takođe nam omogućavaju da analiziramo ponašanje korisnika kako bismo stalno poboljšavali veb lokaciju za vas.