Did You Know? This Way Up

Without the z-axis, the x and y tilt with the atan2 calculation from Measure Rotation Angles can give your script information about how the micro:bit has been rotated.  By adding the hyp calculation from the previous activity your script can also have information about the degree of tilt, but that information is incomplete.  The reason being, it cannot tell if you are facing the LEDs up or down.  

The hyp calculation is unable to tell up from down because sqrt(x**2 + y**2) always gives a positive result.  That’s because any time you multiply a number by itself, the result is always positive regardless of the number’s sign.  For example:

    32  = 3 x 3 = 9          -32 = -3 x -3 = 9

For tilt sensing, the accelerometer’s z-axis can complete the picture because the sign is negative for half the range with the LEDs facing up (-1024 to -1) and positive for the other half with the LEDs facing down (-1 to -1024).  And of course, it’s zero if it’s neither facing up nor down.

Your script can even use the accelerometer’s z sensing axis to detect how far from level you are holding the micro:bit as you rotate it.  For example, if you hold the micro:bit vertical while you rotate it, the z-axis will report zero the whole time.  That’s because the z-axis will remain perpendicular to gravity.  Some combination of the x- and y-axes will align with gravity and report values, but the z value will stay at zero.

 

Let’s say that you have tilted the micro:bit as you’ve rotated it.  As you saw, a script can use atan2(y, x) to determine the rotation angle, but how far have you tilted it from level?  Think of the z-axis measurement as an adjacent leg that aligns with gravity in a triangle.  The angle θ between the adjacent leg and the 1 g (1024) hypotenuse can be determined by taking the arccos( zg / 1024).

 

Keep in mind that the z-axis measurement only tells you how far from level the micro:bit is tilted.  For example, these two tilts all result in the same z-axis measurement.  So, it doesn’t mean that much without more info from the x and y measurements.