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 mpython.py source code.
Delay
- mpython.sleep(s)
Second-level delay.
s- Unit: seconds.
- mpython.sleep_ms(ms)
Millisecond-level delay.
ms- Unit: milliseconds.
- mpython.sleep_us(us)
Microsecond-level delay.
us- Unit: microseconds.
Mapping
- mpython.numberMap(inputNum, bMin, bMax, cMin, cMax)
Mapping function, parameters:
inputNumThe variable to be mappedbMinThe minimum value of the source rangebMaxThe maximum value of the source rangecMinThe minimum value of the target rangecMaxThe maximum value of the target range
Onboard Sensors
Sound and Light
- light.read()
Read the onboard light sensor value, range 0~4095.
- 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.
- accelerometer.get_x()
Get the acceleration measurement on the x-axis, positive or negative integer depending on direction.
- accelerometer.get_y()
Get the acceleration measurement on the y-axis, positive or negative integer depending on direction.
- accelerometer.get_z()
Get the acceleration measurement on the z-axis, positive or negative integer depending on direction.
- 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
- 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
- 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.
- 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.
- accelerometer.event_tilt_left
Tilt left
- accelerometer.event_tilt_right
Tilt right
- accelerometer.event_tilt_up
Tilt forward
- accelerometer.event_tilt_down
Tilt backward
- accelerometer.event_face_up
Face up
- accelerometer.event_face_down
Face down
- accelerometer.event_single_click
Single tap, similar to a mouse single-click operation.
- accelerometer.event_single_click
Double tap, similar to a mouse double-click operation.
- 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.
1# The MIT License (MIT)
2# Copyright (c) 2020, Tangliufeng for labplus Industries
3
4# accelerometer event simple example
5
6from mpython import *
7
8def motion_callback_function(event):
9 """ Motion event callback function """
10 if event == accelerometer.TILT_LEFT:
11 print("tilt left")
12 elif event == accelerometer.TILT_RIGHT:
13 print("tilt right")
14 elif event == accelerometer.TILT_UP:
15 print("tilt up")
16 elif event == accelerometer.TILT_DOWN:
17 print("tilt down")
18 elif event == accelerometer.FACE_UP:
19 print("face up")
20 elif event == accelerometer.FACE_DOWN:
21 print("face down")
22 elif event == accelerometer.SINGLE_CLICK:
23 print("single click")
24 elif event == accelerometer.DOUBLE_CLICK:
25 print("double click")
26 elif event == accelerometer.FREEFALL:
27 print("freefall")
28
29# Register event callbacks
30accelerometer.event_tilt_up = motion_callback_function
31accelerometer.event_tilt_down = motion_callback_function
32accelerometer.event_tilt_left = motion_callback_function
33accelerometer.event_tilt_right = motion_callback_function
34accelerometer.event_face_up = motion_callback_function
35accelerometer.event_face_down = motion_callback_function
36accelerometer.event_single_click = motion_callback_function
37accelerometer.event_double_click = motion_callback_function
38accelerometer.event_freefall = motion_callback_function
39
40
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.
- gyroscope.get_x()
Get the angular velocity measurement on the x-axis, depending on direction.
- gyroscope.get_y()
Get the angular velocity measurement on the y-axis, depending on direction.
- gyroscope.get_z()
Get the angular velocity measurement on the z-axis, depending on direction.
- 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
- 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!
- magnetic.get_x()
Get the x-axis magnetic induction value, positive or negative integer, range +/-8191, unit mG (milliGauss).
- magnetic.get_y()
Get the y-axis magnetic induction value, positive or negative integer, range +/-8191, unit mG (milliGauss).
- magnetic.get_z()
Get the z-axis magnetic induction value, positive or negative integer, range +/-8191, unit mG (milliGauss).
- 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.
- 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.
- magnetic.clear_peeling()
Cancel magnetic tare function. After using peeling(), use this function to restore normal geomagnetic measurement.
- 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.
- 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:
Place mPython Board horizontally, rotate several circles in the horizontal plane, takes about 15 seconds.
Place mPython Board vertically, rotate several circles along the axis perpendicular to the ground, takes about 15 seconds.
1# The MIT License (MIT)
2# Copyright (c) 2019, Tangliufeng for labplus Industries
3
4# mPython Board magnetometer Magnetic application -- compass
5
6from mpython import *
7import math
8
9# Draw the compass center coordinates and radius
10xc,yc,r= 64,32,30
11
12
13def draw_heading(angle):
14 """Draw the magnetic north pointer"""
15 global xc,yc,r
16 angle = 360 - angle
17 am = math.pi * 2.0 * angle / 360
18 xm = round(xc + r * math.sin(am))
19 ym = round(yc - r * math.cos(am))
20 oled.line(xc, yc, xm, ym, 1)
21
22# Electronic compass calibration
23magnetic.calibrate()
24sleep(2)
25oled.DispChar('Compass',0,0)
26# Draw the compass outline
27oled.circle(xc, yc, r+1, 1)
28oled.show()
29while True:
30 # Get the magnetometer electronic compass angle
31 angle = magnetic.get_heading()
32 # Clear the pointer
33 oled.fill_circle(xc, yc, r, 0)
34 # Display the compass pointer
35 draw_heading(angle)
36 oled.show()
37 print("Magnetic north angle: %d" %angle)
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!
- bme280.temperature()
Returns the temperature value in degrees Celsius.
- bme280.pressure()
Returns the atmospheric pressure value in Pa.
- bme280.humidity()
Returns the ambient humidity in %.
Buzzer
The mPython Board buzzer is driven by the music module. For details, see the music module.
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 mpython.Touch(pin)
- 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.
- Touch.event_released
Touch button release event.
- Touch.read()
Returns the touch value.
. method:: Touch.config(threshold)
Set the touch threshold.
- Touch.is_pressed()
Returns whether the button is currently pressed. True means pressed, False means not pressed.
- 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.
- 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 neopixel.
- 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()
- rgb.fill(rgb_buf)
Fill all LED pixels.
- rgb.brightness(brightness)
Brightness adjustment, range 0~1.0
oled Object
The oled object is a derived class of framebuf, inheriting framebuf’s methods. For more usage, see framebuf.
- oled.poweron()
Turn on the display power.
- oled.poweroff()
Turn off the display power.
- oled.contrast(brightness)
Set the display brightness.
brightnessBrightness, range 0~255
- 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.
- 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.
- oled.show()
Send the frame buffer to the OLED display.
1from mpython import *
2
3oled.DispChar('Hello World', 38, 0)
4oled.DispChar('hello,world', 32, 16)
5oled.DispChar('안녕하세요', 35, 32)
6oled.DispChar('こんにちは', 24, 48)
7oled.show()
1# Typing effect
2from mpython import *
3oled.fill(0)
4
5# The string to display
6_str = "The mPython Board is a teaching aid and learning tool jointly proposed by the Maker Education Expert Committee, Maoyouhui, and a large number of front-line teachers, and developed together with leading enterprises in the maker education industry. It is a piece of open-source hardware born for education, and also a public welfare project. The mPython Board is a MicroPython microcontroller board that integrates the high-performance ESP32 dual-core chip and uses the most popular Python programming language today, so you can easily transfer code from your desktop to the microcontroller or embedded system."
7
8# Starting coordinates
9axis = (0, 0)
10
11# Display character by character, continuing from the returned coordinates
12for c in _str:
13 response = oled.DispChar(c, axis[0], axis[1])
14 char_width = response[0]
15 axis = response[1]
16 oled.show()
17
18 # Clear the screen when it is full
19 if axis[1] >= 64 - 16 and char_width >= 128-axis[0]:
20 print('Clear screen')
21 oled.fill(0)
- 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.
1# The MIT License (MIT)
2# Copyright (c) 2019, Tangliufeng for labplus Industries
3
4# A simple example of custom font display with oled.DispChar_font() on the mPython Board
5
6from mpython import *
7
8# Import the converted fonts
9import simfang16
10import freescpt18
11import stxingkai20
12
13# Display using custom fonts
14oled.DispChar_font(simfang16,'Hello, World', 23, 0)
15oled.DispChar_font(stxingkai20,'Hello, World', 23, 21)
16oled.DispChar_font(freescpt18,'hello,world', 23, 42)
17
18oled.show()
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.
- oled.fill(c)
Fill the entire frame buffer with the specified color. When
cis 1, pixels light up; whencis 0, pixels turn off.
- 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; whencis 0, pixels turn off.
- 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; whencis 0, pixels turn off.
- 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; whencis 0, pixels turn off.
- 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; whencis 0, pixels turn off.
- 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;
- 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; whencis 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 machine.I2C module or I2C Tutorial section.
MPythonPin Class
- class mpython.MPythonPin(pin, mode=PinMode.IN, pull=None)
Construct a Pin object.
pinmPython Board defined pin number. For specific definitions, see mPython Board Pin Definition.modePin mode. When not set, default mode = PinMode.INPinMode.INEquals 1, digital input modePinMode.OUTEquals 2, digital output modePinMode.PWMEquals 3, analog output modePinMode.ANALOGEquals 4, analog input modePinMode.OUT_DRAINEquals 5, open-drain output mode
pullSpecifies whether the pin has a pull resistor attached, can be one of:None- No pull-up or pull-down resistorPin.PULL_UP- Pull-up resistor enabledPin.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
- MPythonPin.read_digital()
Returns the IO pin level value. 1 represents high level, 0 represents low level.
- MPythonPin.write_digital(value)
IO pin output level control. When value =1, outputs high level; when value =0, outputs low level.
- MPythonPin.read_analog()
Read the ADC and return the result. The returned value will be between 0 and 4095.
- MPythonPin.write_analog(duty, freq=1000):
Set the duty cycle of the output PWM signal.
duty0 <= duty <= 1023freqPWM frequency, 0 < freq <= 0x0001312D (decimal: 0 < freq <= 78125)
- 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:
handleris an optional function called when the interrupt triggers.
triggerconfigures the event that can trigger an interrupt. Possible values are:
Pin.IRQ_FALLINGFalling edge interrupt
Pin.IRQ_RISINGRising edge interrupt
Pin.IRQ_LOW_LEVELLow level interrupt
Pin.IRQ_HIGH_LEVELHigh level interruptThese values can be
OR’ed together to trigger on multiple events.
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 mpython.wifi
Construct a wifi object and create sta and ap objects. See the 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.
- 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
- wifi.disconnectWiFi()
Disconnect from the Wi-Fi network.
- 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
- wifi.disable_APWiFi()
Disable wireless AP.