b = None
a = None

from mpython import *

import math

from bluebit import *

def get_tilt_angle(_axis):
    _Ax = accelerometer.get_x()
    _Ay = accelerometer.get_y()
    _Az = accelerometer.get_z()
    if 'X' == _axis:
        _T = math.sqrt(_Ay ** 2 + _Az ** 2)
        if _Az < 0: return math.degrees(math.atan2(_Ax , _T))
        else: return 180 - math.degrees(math.atan2(_Ax , _T))
    elif 'Y' == _axis:
        _T = math.sqrt(_Ax ** 2 + _Az ** 2)
        if _Az < 0: return math.degrees(math.atan2(_Ay , _T))
        else: return 180 - math.degrees(math.atan2(_Ay , _T))
    elif 'Z' == _axis:
        _T = math.sqrt(_Ax ** 2 + _Ay ** 2)
        if (_Ax + _Ay) < 0: return 180 - math.degrees(math.atan2(_T , _Az))
        else: return math.degrees(math.atan2(_T , _Az)) - 180
    return 0

ultrasonic = Ultrasonic()
oled.fill(0)
while True:
    oled.fill_rect(0, 0, 128, 16, 0)
    oled.DispChar(('倾斜角x：' + str(int(get_tilt_angle('X')))), 0, 0, 1)
    b = ultrasonic.distance()
    oled.fill_rect(0, 16, 128, 16, 0)
    oled.DispChar(('距离b：' + str(int(b))), 0, 16, 1)
    a = b * math.tan(get_tilt_angle('X') / 180.0 * math.pi)
    oled.fill_rect(0, 32, 128, 16, 0)
    oled.DispChar(('高度a：' + str(int(a))), 0, 32, 1)
    oled.show()
