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 mpython.py source code.
Delay
- mpython.sleep(s)
Delay in seconds
s- Unit: seconds.
- mpython.sleep_ms(ms)
Delay in milliseconds
ms- Unit: milliseconds.
- mpython.sleep_us(us)
Delay in microseconds
us- Unit: microseconds.
Mapping
- mpython.numberMap(inputNum, bMin, bMax, cMin, cMax)
Mapping function, parameters:
inputNumis the variable to be mappedbMinis the minimum value of the source rangebMaxis the maximum value of the source rangecMinis the minimum value of the target rangecMaxis the 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 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.
- accelerometer.get_x()
Get the acceleration measurement on the x-axis, a positive or negative integer depending on the direction.
- accelerometer.get_y()
Get the acceleration measurement on the y-axis, a positive or negative integer depending on the direction.
- accelerometer.get_z()
Get the acceleration measurement on the z-axis, a positive or negative integer depending on the direction.
- 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
- 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
- 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.
- 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.
- 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
A single tap, similar to a mouse single-click.
- accelerometer.event_double_click
Two consecutive taps, similar to a mouse double-click.
- 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.
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# Event callback registration
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 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.
- gyroscope.get_x()
Get the angular velocity measurement on the x-axis, depending on the direction.
- gyroscope.get_y()
Get the angular velocity measurement on the y-axis, depending on the direction.
- gyroscope.get_z()
Get the angular velocity measurement on the z-axis, depending on the direction.
- 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
- 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!
- magnetic.get_x()
Get the magnetic induction value on the x-axis, a positive or negative integer, range ±8191, unit mG (milligauss).
- magnetic.get_y()
Get the magnetic induction value on the y-axis, a positive or negative integer, range ±8191, unit mG (milligauss).
- magnetic.get_z()
Get the magnetic induction value on the z-axis, a positive or negative integer, range ±8191, unit mG (milligauss).
- 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.
- 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.
- magnetic.clear_peeling()
Cancel the 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 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.
- 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:
Place the mPython Board horizontally and rotate it several times in the horizontal plane, taking about 15 seconds.
Place the mPython Board vertically and rotate it several times along the axis perpendicular to the ground, taking about 15 seconds.
1# The MIT License (MIT)
2# Copyright (c) 2019, Tangliufeng for labplus Industries
3
4# mPython Board magnetometer application -- compass
5
6from mpython import *
7import math
8
9# Draw compass center coordinates and radius
10xc,yc,r= 64,32,30
11
12
13def draw_heading(angle):
14 """Draw 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 compass outline
27oled.circle(xc, yc, r+1, 1)
28oled.show()
29while True:
30 # Get magnetometer compass angle
31 angle = magnetic.get_heading()
32 # Clear pointer
33 oled.fill_circle(xc, yc, r, 0)
34 # Display compass pointer
35 draw_heading(angle)
36 oled.show()
37 print("Magnetic north angle: %d" %angle)
Buzzer (music)
The music module drives the mPython Board buzzer. For details, see the music module.
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 mpython.Touch(pin)
- 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.
- Touch.event_released
Touch sensor release event.
- Touch.read()
Return the touch value
- Touch.config(threshold)
Set the touch threshold
- Touch.is_pressed()
Return whether it is currently held. True means the touch sensor is pressed, False means it is not pressed.
- 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.
- 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 neopixel.
- 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()
- rgb.fill(rgb_buf)
Fill all LED pixels.
- 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 machine.I2C module or the I2C basic tutorial chapter.
MPythonPin Class
- class mpython.MPythonPin(pin, mode=PinMode.IN, pull=None)
Construct a Pin object
pinThe pin number defined by the mPython Board. For the specific definition, see mPython Board pin definitions.modeThe pin mode. When not set, the default is mode = PinMode.INPinMode.INequals 1, digital input modePinMode.OUTequals 2, digital output modePinMode.PWMequals 3, analog output modePinMode.ANALOG