How Measuring Rotation Angles Works

In addition to the microbit module, this script has to import the math module, which contains common trigonometry methods.  Then, sleep(1000) gives the terminal a second to set up communication with the micro:bit before it has to display any messages.

# test_accel_xy_angle

from microbit import *
import math

sleep(1000)

In the main loop, the x and y axis accelerometer measurements are stored in variables named x and y.

while True:
    x = accelerometer.get_x()
    y = accelerometer.get_y()

The next line performs a calculation called arctangent.  If you have never heard of it, the next page explains it.

The method call math.atan2(x, y) is what returns the angle result, but that result is in radians—a different kind of angle measurement where a half circle is approximately 3.14, or Pi (π), radians instead of 180°.  To convert radians to degrees in Python, use the math.degrees() method.* 

    angle = round( math.degrees( math.atan2(y, x) ) )

Another way to think about the line above is to break it into steps, each on an individual line.  For example:

    radians = math.atan2(y, x)
    degrees_fp = math.degrees( radians )
    angle = round( degrees_fp )

Now that the angle is calculated, the script displays labels for each variable, followed by its value.

    print("x =", x, ", y =", y, ", angle =", angle)

    sleep(750)

*Alternately, the script could multiply by 180 and divide by math.pi At this point, there’s a floating point result, and the round function will round to the nearest integer.  For example, if the result was 179.5 or higher, it would round to 180.  If the value was instead between 179 and 179.499…., it would round to 179 instead.