.. _mpython.py: .. module:: mpython :synopsis: mPython Board onboard functions :mod:`mpython` --- mPython Board onboard functions ---------------------------------------------------- ``mpython`` is a proprietary module encapsulated for the mPython Board, containing functions related to the board's onboard resources. For the detailed code implementation, see :ref:`mpython.py source code `. Delay ------- .. method:: sleep(s) Delay in seconds - ``s`` - Unit: seconds. .. method:: sleep_ms(ms) Delay in milliseconds - ``ms`` - Unit: milliseconds. .. method:: sleep_us(us) Delay in microseconds - ``us`` - Unit: microseconds. Mapping ------- .. method:: numberMap(inputNum,bMin,bMax,cMin,cMax) Mapping function, parameters: - ``inputNum`` is the variable to be mapped - ``bMin`` is the minimum value of the source range - ``bMax`` is the maximum value of the source range - ``cMin`` is the minimum value of the target range - ``cMax`` is the maximum value of the target range Onboard Sensors --------------- Sound and Light --------------- .. method:: light.read() Read the onboard light sensor value, range 0~4095. .. method:: sound.read() Read the onboard microphone value, range 0~4095. Accelerometer ------------- Through the accelerometer object, you can get the 3-axis accelerometer values in units of g. The acceleration range is ±2g/±4g/±8g/±16g, defaulting to ±2g. .. method:: accelerometer.get_x() Get the acceleration measurement on the x-axis, a positive or negative integer depending on the direction. .. method:: accelerometer.get_y() Get the acceleration measurement on the y-axis, a positive or negative integer depending on the direction. .. method:: accelerometer.get_z() Get the acceleration measurement on the z-axis, a positive or negative integer depending on the direction. .. method:: accelerometer.set_range(range) Set the acceleration range. By default, if not modified, the range is ±2g. The acceleration range values are the following constants: ========= ===== ========== Constant Value Definition RANGE_2G 0 Range ±2g RANGE_4G 1 Range ±4g RANGE_8G 2 Range ±8g RANGE_16G 3 Range ±16g ========= ===== ========== .. method:: accelerometer.set_resolution(resolution) Set the acceleration resolution. By default, if not modified, it is 10-bit resolution. The resolution values are the following constants: ========== ===== ================= Constant Value Definition RES_14_BIT 0 14-bit resolution RES_12_BIT 1 12-bit resolution RES_10_BIT 2 10-bit resolution ========== ===== ================= .. method:: accelerometer.set_offset(x=None, y=None, z=None) This function is used to calibrate the acceleration deviation of the accelerometer's 3 axes (x, y, z). Calibration is generally not needed; correct it only when the acceleration deviation is large. Note that calibration data is not saved after power off. ``x``, ``y``, ``z`` are the deviation adjustment values, with a correctable range of ±1g. On mPython Board v2.3 and above, calibration data is saved on power off. .. method:: accelerometer.roll_pitch_angle() Return the Euler angles (roll and pitch) calculated from the accelerometer. Note that the yaw angle requires angular velocity and therefore cannot be measured. Returns a 2-tuple (roll, pitch) in degrees. Assume the mPython Board is an aircraft: - The roll angle is the angle between the plane containing the aircraft's two wings and the horizontal line; rolling the body to the right is positive, with a range of [-180, 180]. - The pitch angle is the angle between the nose and the horizontal plane; it is 0 when the aircraft is level and positive when the nose is up, with a range of [-180, 180]. .. Attention:: The calculation based only on 3-axis acceleration applies only to static measurements under gravity alone. In practice, it is affected by other accelerations, such as vibration. Motion Detection Events ~~~~~~~~~~~~~~~~~~~~~~~ Provides various motion posture events such as tilt, flip, tap (similar to a mouse click), and freefall. Users can set a callback function in advance; when an event occurs, the event callback is triggered. The callback function is defined as function_callback(event). The `event` parameter is the corresponding event constant. .. data:: accelerometer.event_tilt_left Tilt left .. data:: accelerometer.event_tilt_right Tilt right .. data:: accelerometer.event_tilt_up Tilt forward .. data:: accelerometer.event_tilt_down Tilt backward .. data:: accelerometer.event_face_up Face up .. data:: accelerometer.event_face_down Face down .. data:: accelerometer.event_single_click A single tap, similar to a mouse single-click. .. data:: accelerometer.event_double_click Two consecutive taps, similar to a mouse double-click. .. data:: accelerometer.event_freefall Freefall The events are defined as follows: ========================== ===== Event Value accelerometer.TILT_LEFT 0 accelerometer.TILT_RIGHT 1 accelerometer.TILT_UP 2 accelerometer.TILT_DOWN 3 accelerometer.FACE_UP 4 accelerometer.FACE_DOWN 5 accelerometer.SINGLE_CLICK 6 accelerometer.DOUBLE_CLICK 7 accelerometer.FREEFALL 8 ========================== ===== .. Attention:: On mPython Board v2.3 and above, the accelerometer motion detection events are removed. .. literalinclude:: /_static/products/mpython-s3/_static/examples/accelerometer/accelerometer_event.py :caption: A simple application of accelerometer events :linenos: Gyroscope -------------------- Through the gyroscope object, you can get the gyroscope angular velocity values. The unit of angular velocity is dps (°/s). The angular velocity range is ±16dps/±32dps/±64dps/±128dps/±256dps/±512dps/±1024dps/±2048dps, defaulting to ±256 dps. .. method:: gyroscope.get_x() Get the angular velocity measurement on the x-axis, depending on the direction. .. method:: gyroscope.get_y() Get the angular velocity measurement on the y-axis, depending on the direction. .. method:: gyroscope.get_z() Get the angular velocity measurement on the z-axis, depending on the direction. .. method:: gyroscope.set_range(range) Set the angular velocity range. By default, if not modified, the range is ±256 dps. The angular velocity range values are the following constants: ============== ===== =============== Constant Value Definition RANGE_16_DPS 0 Range ±16 dps RANGE_32_DPS 16 Range ±32 dps RANGE_64_DPS 32 Range ±64 dps RANGE_128_DPS 48 Range ±128 dps RANGE_256_DPS 64 Range ±256 dps RANGE_512_DPS 80 Range ±512 dps RANGE_1024_DPS 96 Range ±1024 dps RANGE_2048_DPS 112 Range ±2048 dps ============== ===== =============== .. method:: gyroscope.set_offset(x=None, y=None, z=None) This function is used to calibrate the angular velocity deviation of the gyroscope's 3 axes (x, y, z). Calibration is generally not needed; correct it only when the angular velocity deviation is large. ``x``, ``y``, ``z`` are the deviation adjustment values, with a correctable range of ±1024dps. .. Attention:: The gyroscope sensor is added on mPython Board v2.3 and above. Magnetometer ------------------- The MMC5983MA magnetometer function interface can get the 3-axis geomagnetic induction intensity, the geomagnetic field strength, and the electronic compass angle. .. Attention:: Only mPython Board v2.0 and above have the MMC5983MA magnetometer! .. method:: magnetic.get_x() Get the magnetic induction value on the x-axis, a positive or negative integer, range ±8191, unit mG (milligauss). .. method:: magnetic.get_y() Get the magnetic induction value on the y-axis, a positive or negative integer, range ±8191, unit mG (milligauss). .. method:: magnetic.get_z() Get the magnetic induction value on the z-axis, a positive or negative integer, range ±8191, unit mG (milligauss). .. method:: magnetic.get_field_strength() Return the calculated magnetic induction value, i.e. the sum of the 3-axis magnetic forces. The formula is the square root of x^2+y^2+z^2. .. method:: magnetic.peeling() Magnetic tare. Similar to the tare function of an electronic scale, after ``peeling()``, the next ``get_field_strength()`` returns the value calculated after subtracting the current magnetic value. It can be used for measurement applications that remove the geomagnetic induction value. .. method:: magnetic.clear_peeling() Cancel the magnetic tare function. After using ``peeling()``, use this function to restore normal geomagnetic measurement. .. method:: magnetic.get_heading() Get the electronic compass angle, i.e. the angle between the direction and the geomagnetic north pole. The top of the mPython Board, i.e. the USB position, is regarded as true north. Unit: degrees, range 0~360. .. Attention:: Since the angle calculation does not perform z-axis tilt compensation, keep the mPython Board level when using ``get_heading()`` to read the compass angle! .. Attention:: To obtain an accurate compass angle, ensure there is no strong magnetic field interference nearby, or calibrate with ``calibrate()`` before use. .. method:: magnetic.calibrate() Electronic compass calibration. When there is strong magnetic interference around the mPython Board, use this function to clear the strong magnetic component so that the accurate geomagnetic north deviation can be calculated. Note that the calibration offset is not saved after power off. Calibration method: follow the steps indicated on the mPython Board display: 1. Place the mPython Board horizontally and rotate it several times in the horizontal plane, taking about 15 seconds. 2. Place the mPython Board vertically and rotate it several times along the axis perpendicular to the ground, taking about 15 seconds. .. literalinclude:: /_static/products/mpython-s3/_static/examples/magnetic/compass.py :caption: Magnetometer application -- compass :linenos: Buzzer (music) ----------------- The ``music`` module drives the mPython Board buzzer. For details, see the :mod:`music` module. button_[a,b] Objects -------------------- The a and b buttons on the mPython Board. button_a/button_b are instance objects of the ``Button`` class, implemented using the :ref:`machine.Pin.irq` interrupt. They define the ``event_pressed`` and ``event_released`` button press and release events. Users can easily implement event callbacks. In addition, it also implements function methods such as the current or past button state and the number of presses. .. class:: Button(pin_num, reverse=False) The Button class, an abstract button class. - ``pin_num`` - The IO pin number - ``reverse`` - Defaults to False. Suitable for buttons triggered by a low level. For buttons triggered by a high level, set reverse to True to invert it. The instances of button_a and button_b on the mPython Board:: button_a = Button(Pin.P5) button_b = Button(Pin.P11) When a button event occurs, the event callback is triggered. The callback function is defined as function_callback(pin), where ``pin`` returns the machine.Pin object of that pin. .. data:: Button.event_pressed Button press event. .. data:: Button.event_released Button release event. .. literalinclude:: /_static/products/mpython-s3/_static/examples/button/button_event.py :caption: A simple application of Button event callbacks :linenos: .. method:: Button.value() Get the level state of the button pin. 1 is high level, 0 is low level. :: >>> button_a.value() >>> 1 >>> button_a.value() >>> 0 .. method:: Button.is_pressed() Return whether the button is currently held. ``True`` means the button is pressed, ``False`` means it is not pressed. .. method:: Button.was_pressed() Return ``True`` or ``False`` to indicate whether the button has been pressed since the device started or since the last call to this method. Calling this method clears the pressed state, so the button must be pressed again before it can return ``True`` again. .. method:: Button.get_presses() Return the total number of button presses and reset the total to zero before returning. Note that the counter stops counting after it exceeds 100. .. _button.irq: .. method:: Button.irq(handler=None, trigger=(Pin.IRQ_FALLING | Pin.IRQ_RISING), priority=1, wake=None) Configure an interrupt handler that is called when the pin's trigger source is active. The usage is the same as machine.Pin.irq. Parameters: - ``handler`` is an optional function that is called when the interrupt is triggered. - ``trigger`` configures the events that can trigger an interrupt. The possible values are: - ``Pin.IRQ_FALLING`` falling-edge interrupt - ``Pin.IRQ_RISING`` rising-edge interrupt - ``Pin.IRQ_LOW_LEVEL`` low-level interrupt - ``Pin.IRQ_HIGH_LEVEL`` high-level interrupt These values can be ``OR``-ed together to trigger multiple events. - ``priority`` sets the priority of the interrupt. The values it can take are port-specific, but a higher value always represents a higher priority. - ``wake`` selects the power modes from which this interrupt can wake the system. It can be ``machine.IDLE``, ``machine.SLEEP`` or ``machine.DEEPSLEEP``. These values can also be ``OR``-ed, allowing the pin to generate interrupts in multiple power modes. This method returns a callback object. :: >>> from mpython import * >>> button_a.irq(trigger=Pin.IRQ_FALLING, handler=lambda p:print("button-a press!")) touch Object ------------ The mPython Board has 6 touch pins: touchpad_p/y/t/h/o/n. They are instance objects of the Touch class, and the specific function methods are as follows. .. class:: Touch(pin) .. data:: Touch.event_pressed Touch sensor press event. When a key event occurs, the event callback is triggered. The callback function is defined as function_callback(value), where ``value`` is the state value of the touch sensor. .. data:: Touch.event_released Touch sensor release event. .. method:: Touch.read() Return the touch value .. method:: Touch.config(threshold) Set the touch threshold .. method:: Touch.is_pressed() Return whether it is currently held. ``True`` means the touch sensor is pressed, ``False`` means it is not pressed. .. method:: Touch.was_pressed() Return ``True`` or ``False`` to indicate whether the button has been pressed since the device started or since the last call to this method. Calling this method clears the pressed state, so the button must be pressed again before it can return ``True`` again. .. method:: Touch.get_presses() Return the total number of presses and reset the total to zero before returning. Note that the counter stops counting after it exceeds 100. rgb Object ------------ Used to control the 3 RGB ws2812 LEDs on the mPython Board. The rgb object is a derived class of neopixel and inherits neopixel's methods. For more usage, see :ref:`neopixel`. .. method:: rgb.write() Write data into the RGB LEDs. .. Hint:: Write RGB color values by assigning to the rgb[n] list. For example, rgb[0]=(50,0,0) :: from mpython import * rgb[0] = (255, 0, 0) # Set to red, full brightness rgb[1] = (0, 128, 0) # Set to green, half brightness rgb[2] = (0, 0, 64) # Set to blue, quarter brightness rgb.write() .. method:: rgb.fill(rgb_buf) Fill all LED pixels. .. method:: rgb.brightness(brightness) Brightness adjustment, range 0~1.0 i2c Object ---------- The mPython Board has already instantiated the ``I2C`` class; P19 and P20 are the SCL and SDA pins of I2C. I2C devices can be connected to the mPython Board I2C bus for operation. For details on I2C read and write operations, see the :ref:`machine.I2C` module or the :ref:`I2C basic tutorial` chapter. MPythonPin Class ---------------- .. class:: MPythonPin(pin, mode=PinMode.IN,pull=None) Construct a Pin object - ``pin`` The pin number defined by the mPython Board. For the specific definition, see :ref:`mPython Board pin definitions`. - ``mode`` The pin mode. When not set, the default is `mode` = `PinMode.IN` - ``PinMode.IN`` equals 1, digital input mode - ``PinMode.OUT`` equals 2, digital output mode - ``PinMode.PWM`` equals 3, analog output mode - ``PinMode.ANALOG``