
Code to Note
Let’s take a look at the code blocks in this experiment.
If you are having a hard time viewing this code, click on the image above to get a better look!
Acceleration
The
acceleration
block can be found under the input blocks group. This block returns the force of
gravity pulling on a specific axis of the micro:bit (X, Y or Z) and represents that value as a range of
numbers between -1023 and 1023. In this case, we measure the X axis, which is the side-to-side tilt
of the micro:bit. If you tilt the micro:bit all the way to the left, you will get a -1023 value and all the
way to the right is positive 1023.
Map
The
map
block looks intimidating, but it is one of the most useful blocks in MakeCode. The
map
block
takes a given variable that has a known range — in this case -1023 to 1023 — and “maps” or scales
that value range to another given range. The given range we want is 15 to 165, which is a
good
safe
range of rotation for the servo. So, in the end -1023 ends up to equal 0, and 1023 ends up
as 165 from the
map
block.
What You Should See
At the beginning of the program the servo should move to 90 degrees and then react to the
orientation of the micro:bit. If you hold the micro:bit flat, the servo will be at 90 degrees. Then if you
tilt the servo to the left, it will move less than 90 degrees toward the value of 15. If you move it to the
right, the servo will move toward 165.