.. _mpython.py: .. module:: mpython :synopsis: mPython Board onboard function library :mod:`mpython` --- mPython Board Onboard Functions ================================================== ``mpython`` is a proprietary module encapsulated for mPython Board, containing functions related to onboard resources. For detailed code implementation, see :ref:`mpython.py source code `. Delay ------- .. method:: sleep(s) Second-level delay. - ``s`` - Unit: seconds. .. method:: sleep_ms(ms) Millisecond-level delay. - ``ms`` - Unit: milliseconds. .. method:: sleep_us(us) Microsecond-level delay. - ``us`` - Unit: microseconds. Mapping ------- .. method:: numberMap(inputNum,bMin,bMax,cMin,cMax) Mapping function, parameters: - ``inputNum`` The variable to be mapped - ``bMin`` The minimum value of the source range - ``bMax`` The maximum value of the source range - ``cMin`` The minimum value of the target range - ``cMax`` 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, range 0~4095. Accelerometer +++++++++++++ Through the accelerometer object, you can get 3-axis accelerometer values in units of g. Acceleration range: +/-2g/+/-4g/+/-8g/+/-16g, default is +/-2g. .. method:: accelerometer.get_x() Get the acceleration measurement on the x-axis, positive or negative integer depending on direction. .. method:: accelerometer.get_y() Get the acceleration measurement on the y-axis, positive or negative integer depending on direction. .. method:: accelerometer.get_z() Get the acceleration measurement on the z-axis, positive or negative integer depending on direction. .. method:: accelerometer.set_range(range) Set the acceleration range. Default, if not modified, the range is +/-2g. 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. Default, if not modified, is 10-bit resolution. 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 value offset of the 3 axes (x, y, z) of the accelerometer. Generally no calibration is needed; only correct when the acceleration deviation is large. Note that calibration data is not saved after power off. ``x``, ``y``, ``z`` are adjustment offset values, correctable range +/-1g. mPython Board v2.3 and above will save calibration data after power off. .. method:: accelerometer.roll_pitch_angle() Returns Euler angles (roll angle, pitch angle) calculated from the accelerometer. Note that yaw angle requires angular velocity and cannot be measured. Returns a 2-tuple (roll, pitch) in degrees. Assuming mPython Board is an airplane: - Roll angle refers to the angle between the plane of the wings and the horizontal line. Positive when the body rolls right, range [-180, 180]. - Pitch angle refers to the angle between the nose and the horizontal plane. Zero when level, positive when pitching up, range [-180, 180]. .. Attention:: The 3-axis acceleration calculation method is only applicable for static measurements under gravity only. In practice, it will be affected by other acceleration interference, such as vibration. Motion Detection Events ~~~~~~~~~~~~~~~~~~~~~~~ Provides various motion posture events including tilt, flip, tap (similar to mouse click), and freefall. Users can pre-set callback functions; when an event occurs, the event callback is triggered. Callback function definition: 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 Single tap, similar to a mouse single-click operation. .. data:: accelerometer.event_single_click Double tap, similar to a mouse double-click operation. .. data:: accelerometer.event_freefall Freefall Event definitions are 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:: mPython Board v2.3 and above removed accelerometer motion detection events. .. literalinclude:: /_static/products/ledong-v2/_static/examples/accelerometer/accelerometer_event.py :caption: Simple application of accelerometer events :linenos: gyroscope ----------------- Through the gyroscope object, you can get gyroscope angular velocity values. The unit of angular velocity is dps (degrees/second). Angular velocity range: +/-16dps/+/-32dps/+/-64dps/+/-128dps/+/-256dps/+/-512dps/+/-1024dps/+/-2048dps, default is +/-256 dps. .. method:: gyroscope.get_x() Get the angular velocity measurement on the x-axis, depending on direction. .. method:: gyroscope.get_y() Get the angular velocity measurement on the y-axis, depending on direction. .. method:: gyroscope.get_z() Get the angular velocity measurement on the z-axis, depending on direction. .. method:: gyroscope.set_range(range) Set the angular velocity range. Default, if not modified, the range is +/-256 dps. 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 offset of the 3 axes (x, y, z) of the gyroscope. Generally no calibration is needed; only correct when the angular velocity deviation is large. ``x``, ``y``, ``z`` are adjustment offset values, correctable range +/-1024dps. .. Attention:: mPython Board v2.3 and above added gyroscope sensor. magnetic ----------- MMC5983MA magnetometer function interface. Can get 3-axis magnetic induction intensity, geomagnetic field strength, and electronic compass angle. .. Attention:: mPython Board v2.0 and above has the MMC5983MA magnetometer! .. method:: magnetic.get_x() Get the x-axis magnetic induction value, positive or negative integer, range +/-8191, unit mG (milliGauss). .. method:: magnetic.get_y() Get the y-axis magnetic induction value, positive or negative integer, range +/-8191, unit mG (milliGauss). .. method:: magnetic.get_z() Get the z-axis magnetic induction value, positive or negative integer, range +/-8191, unit mG (milliGauss). .. method:: magnetic.get_field_strength() Returns the calculated magnetic induction value, i.e. the sum of 3-axis magnetic force. Formula: square root of x^2+y^2+z^2. .. method:: magnetic.peeling() Magnetic tare. Similar to the tare function on an electronic scale. After ``peeling()``, the next ``get_field_strength()`` call returns the result calculated after subtracting the current magnetic value. Can be used to remove geomagnetic induction values for measurement applications. .. method:: magnetic.clear_peeling() Cancel 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 current direction and geomagnetic north. The top of mPython Board (USB port position) is considered true north. Unit: degrees, range 0~360. .. Attention:: Since the angle calculation does not perform z-axis tilt compensation, mPython Board should be placed horizontally when using ``get_heading()`` to read compass angle! .. Attention:: For accurate compass angles, ensure there is no strong magnetic field interference nearby, or use ``calibrate()`` to calibrate before use. .. method:: magnetic.calibrate() Electronic compass calibration. When strong magnetic interference exists around mPython Board, use this function to clear the strong magnetic component in order to calculate accurate geomagnetic declination. Note that calibration offset values are not saved after power off. Calibration method, follow the steps indicated on the mPython Board display: 1. Place mPython Board horizontally, rotate several circles in the horizontal plane, takes about 15 seconds. 2. Place mPython Board vertically, rotate several circles along the axis perpendicular to the ground, takes about 15 seconds. .. literalinclude:: /_static/products/ledong-v2/_static/examples/magnetic/compass.py :caption: Magnetometer application -- compass :linenos: bme280 ------- BME280 is an integrated environmental sensor combining temperature, humidity, and barometric pressure. It features high precision, multi-functionality, and small size. * Temperature detection range: -40C~+85C, resolution 0.1C, accuracy +/-0.5C * Humidity detection range: 0~100%RH, resolution 0.1%RH, accuracy +/-2%RH * Pressure detection range: 300~1100hPa * Humidity measurement response time: 1s .. Attention:: mPython Board does not have an integrated BME280 sensor. mPython Board will scan the I2C bus for a 0x77(119) I2C device to determine whether to construct a bme280 object! .. method:: bme280.temperature() Returns the temperature value in degrees Celsius. .. method:: bme280.pressure() Returns the atmospheric pressure value in Pa. .. method:: bme280.humidity() Returns the ambient humidity in %. Buzzer ------- The mPython Board buzzer is driven by the ``music`` module. For details, see the :mod:`music` module. button_[a,b] Objects -------------------- Buttons A and B on mPython Board. button_a/button_b are instance objects of the ``Button`` class. Implemented using :ref:`machine.Pin.irq` interrupts. Defines ``event_pressed`` and ``event_released`` button press/release events. Users can easily implement event callbacks. Additionally, functions for current or past button state and press count are provided. .. class:: Button(pin_num, reverse=False) Button class, button abstraction class. - ``pin_num`` - IO pin number - ``reverse`` - Default is False. Applicable for buttons triggered on low level. If the button is triggered on high level, set reverse to True to invert. mPython Board button_a and button_b instances:: button_a = Button(Pin.P5) button_b = Button(Pin.P11) When a button event occurs, the event callback is triggered. Callback function definition: function_callback(pin), ``pin`` returns the machine.Pin object for that pin. .. data:: Button.event_pressed Button press event. .. data:: Button.event_released Button release event. .. literalinclude:: /_static/products/ledong-v2/_static/examples/button/button_event.py :caption: Simple application of Button event callback :linenos: .. method:: Button.value() Get the button pin level state. 1 is high level, 0 is low level. :: >>> button_a.value() >>> 1 >>> button_a.value() >>> 0 .. method:: Button.is_pressed() Returns whether the button is currently pressed. ``True`` means the button is pressed, ``False`` means it is not pressed. .. method:: Button.was_pressed() Returns ``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() Returns the total number of button presses and resets the count to zero before returning. Note that the counter stops counting after exceeding 100. .. _button.irq: .. method:: Button.irq(handler=None, trigger=(Pin.IRQ_FALLING | Pin.IRQ_RISING), priority=1, wake=None) Configure an interrupt handler to be called when the trigger source of the pin is active. Usage is the same as machine.Pin.irq. Parameters: - ``handler`` is an optional function called when the interrupt triggers. - ``trigger`` configures the event that can trigger an interrupt. 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 on multiple events. - ``priority`` sets the priority level of the interrupt. The values it can take are port-specific, but higher values always represent higher priorities. - ``wake`` selects the power mode in which this interrupt can wake up the system. It can be ``machine.IDLE``, ``machine.SLEEP`` or ``machine.DEEPSLEEP``. These values can also be OR'ed together to make a pin generate interrupts in more than one power mode. This method returns a callback object. :: >>> from mpython import * >>> button_a.irq(trigger=Pin.IRQ_FALLING, handler=lambda p:print("button-a press!")) touch Objects ------------- mPython Board has 6 touch pins: touchpad_p/y/t/h/o/n. They are instance objects of the Touch class with the following methods. .. class:: Touch(pin) .. data:: Touch.event_pressed Touch button press event. When a button event occurs, the event callback is triggered. Callback function definition: function_callback(value), ``value`` is the state value of the touch button. .. data:: Touch.event_released Touch button release event. .. method:: Touch.read() Returns the touch value. . method:: Touch.config(threshold) Set the touch threshold. .. method:: Touch.is_pressed() Returns whether the button is currently pressed. ``True`` means pressed, ``False`` means not pressed. .. method:: Touch.was_pressed() Returns ``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() Returns the total number of button presses and resets the count to zero before returning. Note that the counter stops counting after exceeding 100. rgb Object ---------- Used to control the 3 RGB WS2812 LEDs on mPython Board. The rgb object is a derived class of neopixel, inheriting neopixel's methods. For more usage, see :ref:`neopixel`. .. method:: rgb.write() Write data to 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 .. _oled: oled Object ----------- The oled object is a derived class of framebuf, inheriting framebuf's methods. For more usage, see :mod:`framebuf`. .. method:: oled.poweron() Turn on the display power. .. method:: oled.poweroff() Turn off the display power. .. method:: oled.contrast(brightness) Set the display brightness. - ``brightness`` Brightness, range 0~255 .. method:: oled.invert(n) Invert pixels. When n=1, unfilled pixels light up and filled pixels turn off. When n=0, the opposite. Default on startup is filled pixels light up. .. method:: oled.DispChar(s, x, y,mode=TextMode.normal,auto_return=False) Display text on the OLED screen. Uses `Google Noto Sans CJK `_ open-source sans-serif font. Font height is 16 pixels, supports English, Simplified Chinese, Traditional Chinese, Japanese and Korean. Returns a 2-tuple of (total character pixel width, x,y coordinates for continued display). - ``s`` - Text to display. - ``x``, ``y`` - Starting coordinates using the top-left corner of the text. - ``mode`` - Set text mode, default is TextMode.normal - ``TextMode.normal`` - Equals 1. Normal mode, text displayed in white, background is black. - ``TextMode.rev`` - Equals 2. Reverse mode, text displayed in black, background is white. - ``TextMode.trans`` - Equals 3. Transparent mode, transparent text means text is written on top of what is already visible on the display. The difference is that previous screen content remains visible, while for normal mode the background is replaced by the currently selected background color. - ``TextMode.xor`` - Equals 4. XOR mode, if the background is black the effect is the same as default mode (normal). If the background is white, the text is inverted. - ``auto_return`` - Auto line wrap. When the displayed string exceeds the display width, it automatically wraps to the next line. Default is no wrapping. .. method:: oled.show() Send the frame buffer to the OLED display. .. literalinclude:: /_static/products/ledong-v2/_static/examples/display/helloworld.py :caption: hello world :linenos: .. literalinclude:: /_static/products/ledong-v2/_static/examples/display/oled_effect of typing.py :caption: Typing effect :linenos: .. method:: oled.DispChar_font(font, s, x, y, invert=False) Custom font display. Users can convert `otf` or `ttf` standard font files on PC using the Python script `font_to_py.py `_ to output Python source code containing font Bitmap data for use. Returns a 2-tuple of (total character pixel width, x,y coordinates for continued display). - ``font`` - Font object. The Python source code converted by the `font_to_py.py` script, placed in the file system. Note: the font file must be imported before using this function. - ``s`` - String to display - ``x``, ``y`` - Starting coordinates using the top-left corner of the text. - ``invert`` - Invert display pixels. .. literalinclude:: /_static/products/ledong-v2/_static/examples/display/custom_font/main.py :caption: Custom font display :linenos: * :download:`Custom font example files simfang16, freescpt18, stxingkai20` .. figure:: /_static/products/ledong-v2/_static/image/tutorials/helloworld_customfont.jpg :width: 400px :align: center .. admonition:: `font_to_py.py` Script Usage Instructions - This script requires Python 3.2 or higher runtime environment. Depends on the `freetype` Python package. Installation: `pip3 install freetype-py` - By default, only the ASCII character set is converted (characters from `chr(32)` to `chr(126)`). Use the command-line parameter `-c` to modify this range as needed to specify arbitrary Unicode character sets, including non-English and non-contiguous character sets. - The `oled.DispChar_font()` function only supports hmap (horizontal mapping) fonts, so when converting, use the command-line parameter `-x` to force horizontal mapping output. - Fixed parameters: font file path, converted font height, output file path. For example: font_to_py.py FreeSans.ttf 20 myfont.py Using the font_to_py.py script on PC to convert fonts:: # Convert to 16-pixel height with ASCII character set only font_to_py.py -x FreeSans.ttf 16 myfont.py # Convert to 16-pixel height with specified Unicode character set, -c parameter followed by your specified character set font_to_py.py -x simfang.ttf 16 simfang.py -c ¬!"#£$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~°Ωαβγδθλμπωϕ£ This function's implementation references the `peterhinch/micropython-font-to `_ open-source project. For more detailed `font_to_py.py` usage instructions, visit that project for more information. .. method:: oled.fill(c) Fill the entire frame buffer with the specified color. When ``c`` is 1, pixels light up; when ``c`` is 0, pixels turn off. .. method:: oled.circle(x, y, radius , c) Draw a circle. - ``x``, ``y`` - Starting coordinates using the top-left corner. - ``radius`` - Circle radius - ``c`` - When 1, pixels light up; when ``c`` is 0, pixels turn off. .. method:: oled.fill_circle(x, y, radius , c) Draw a filled circle. - ``x``, ``y`` - Starting coordinates using the top-left corner. - ``radius`` - Circle radius - ``c`` - When 1, pixels light up; when ``c`` is 0, pixels turn off. .. method:: oled.triangle(x0, y0, x1, y1, x2, y2, c) Draw a triangle. - ``x0``, ``y0`` - Top vertex coordinates of the triangle. - ``x1``, ``y1`` - Left vertex coordinates of the triangle. - ``x2``, ``y2`` - Right vertex coordinates of the triangle. - ``c`` - When 1, pixels light up; when ``c`` is 0, pixels turn off. .. method:: oled.fill_triangle(x0, y0, x1, y1, x2, y2, c) Draw a filled triangle. - ``x0``, ``y0`` - Top vertex coordinates of the triangle. - ``x1``, ``y1`` - Left vertex coordinates of the triangle. - ``x2``, ``y2`` - Right vertex coordinates of the triangle. - ``c`` - When 1, pixels light up; when ``c`` is 0, pixels turn off. .. method:: oled.bitmap(x, y, bitmap, w, h,c) Draw a bitmap image. - ``x``, ``y`` - Starting coordinates using the top-left corner - ``bitmap`` - Bitmap bytearray of the image - ``w`` - Image width - ``h`` - Image height - ``c`` - When 1, pixels light up; .. method:: oled.RoundRect( x, y, w, h, r, c) Draw a rounded rectangle. - ``x``, ``y`` - Starting coordinates using the top-left corner - ``w`` - Rectangle width - ``h`` - Rectangle height - ``r`` - Corner arc radius - ``c`` - When 1, pixels light up; when ``c`` is 0, pixels turn off. i2c Object ---------- mPython Board has already instantiated the ``I2C`` class. P19 and P20 are the I2C SCL and SDA pins. I2C devices can be connected to the mPython Board I2C bus for operation. For detailed I2C read/write operations, see the :ref:`machine.I2C` module or :ref:`I2C Tutorial` section. MPythonPin Class ---------------- .. class:: MPythonPin(pin, mode=PinMode.IN,pull=None) Construct a Pin object. - ``pin`` mPython Board defined pin number. For specific definitions, see :ref:`mPython Board Pin Definition`. - ``mode`` Pin mode. When not set, default `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`` Equals 4, analog input mode - ``PinMode.OUT_DRAIN`` Equals 5, open-drain output mode - ``pull`` Specifies whether the pin has a pull resistor attached, can be one of: - ``None`` - No pull-up or pull-down resistor - ``Pin.PULL_UP`` - Pull-up resistor enabled - ``Pin.PULL_DOWN`` - Pull-down resistor enabled Example:: >>> from mpython import MPythonPin #Import MPython module >>> P0=MPythonPin(0,PinMode.IN) #Construct pin 0 object, set digital input mode .. method:: MPythonPin.read_digital() Returns the IO pin level value. 1 represents high level, 0 represents low level. .. method:: MPythonPin.write_digital(value) IO pin output level control. When ``value`` =1, outputs high level; when ``value`` =0, outputs low level. .. method:: MPythonPin.read_analog() Read the ADC and return the result. The returned value will be between 0 and 4095. .. method:: MPythonPin.write_analog(duty, freq=1000): Set the duty cycle of the output PWM signal. - ``duty`` 0 <= duty <= 1023 - ``freq`` PWM frequency, 0 < freq <= 0x0001312D (decimal: 0 < freq <= 78125) .. _MPythonPin.irq: .. method:: MPythonPin.irq(handler=None, trigger=Pin.IRQ_RISING): If the pin mode is configured as ``IN``, an interrupt handler can be configured to be called when the trigger source of the pin is active. Parameters: - ``handler`` is an optional function called when the interrupt triggers. - ``trigger`` configures the event that can trigger an interrupt. 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 on multiple events. .. _mpython.wifi: wifi Class ---------- Provides convenient Wi-Fi network connection or wireless AP functionality. Note that enabling Wi-Fi increases power consumption. When not in use, disabling Wi-Fi can reduce power consumption. .. class:: wifi() Construct a wifi object and create ``sta`` and ``ap`` objects. See the :mod:`network` module for more usage methods. - sta is used for client connection to a router to access the network. - ap is used for mPython Board as a wireless AP access point. .. method:: wifi.connectWiFi(ssid,password,timeout=10) Connect to a Wi-Fi network. - ``ssid`` - Wi-Fi network name - ``password`` - Wi-Fi password - ``timeout`` - Connection timeout, default 10 seconds .. method:: wifi.disconnectWiFi() Disconnect from the Wi-Fi network. .. method:: wifi.enable_APWiFi(essid,password,channel=10) Enable Wi-Fi wireless AP mode. - ``essid`` - Wi-Fi network name to create - ``password`` - Password - ``channel`` - Set Wi-Fi channel, channel 1~13 .. method:: wifi.disable_APWiFi() Disable wireless AP.