Merge pull request #43 from amirgon/merge-v1.17

Merge Upstream Micropython v1.17
This commit is contained in:
Amir Gonnen 2021-09-07 18:10:32 +03:00 committed by GitHub
commit b765a2bb45
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
601 changed files with 12278 additions and 1965 deletions

3
.gitmodules vendored
View File

@ -1,7 +1,6 @@
[submodule "lib/axtls"] [submodule "lib/axtls"]
path = lib/axtls path = lib/axtls
url = https://github.com/pfalcon/axtls url = https://github.com/micropython/axtls.git
branch = micropython
[submodule "lib/libffi"] [submodule "lib/libffi"]
path = lib/libffi path = lib/libffi
url = https://github.com/atgreen/libffi url = https://github.com/atgreen/libffi

View File

@ -38,10 +38,6 @@ used during the build process and is not part of the compiled source code.
/cc3000 (BSD-3-clause) /cc3000 (BSD-3-clause)
/cc3100 (BSD-3-clause) /cc3100 (BSD-3-clause)
/wiznet5k (BSD-3-clause) /wiznet5k (BSD-3-clause)
/extmod
/crypto-algorithms (NONE)
/re15 (BSD-3-clause)
/uzlib (Zlib)
/lib /lib
/asf4 (Apache-2.0) /asf4 (Apache-2.0)
/axtls (BSD-3-clause) /axtls (BSD-3-clause)
@ -52,6 +48,7 @@ used during the build process and is not part of the compiled source code.
/berkeley-db-1xx (BSD-4-clause) /berkeley-db-1xx (BSD-4-clause)
/btstack (See btstack/LICENSE) /btstack (See btstack/LICENSE)
/cmsis (BSD-3-clause) /cmsis (BSD-3-clause)
/crypto-algorithms (NONE)
/libhydrogen (ISC) /libhydrogen (ISC)
/littlefs (BSD-3-clause) /littlefs (BSD-3-clause)
/lwip (BSD-3-clause) /lwip (BSD-3-clause)
@ -60,9 +57,11 @@ used during the build process and is not part of the compiled source code.
/nxp_driver (BSD-3-Clause) /nxp_driver (BSD-3-Clause)
/oofatfs (BSD-1-clause) /oofatfs (BSD-1-clause)
/pico-sdk (BSD-3-clause) /pico-sdk (BSD-3-clause)
/re15 (BSD-3-clause)
/stm32lib (BSD-3-clause) /stm32lib (BSD-3-clause)
/tinytest (BSD-3-clause) /tinytest (BSD-3-clause)
/tinyusb (MIT) /tinyusb (MIT)
/uzlib (Zlib)
/logo (uses OFL-1.1) /logo (uses OFL-1.1)
/ports /ports
/cc3200 /cc3200

View File

@ -74,7 +74,7 @@ copyright = '- The MicroPython Documentation is Copyright © 2014-2021, Damien P
# #
# We don't follow "The short X.Y version" vs "The full version, including alpha/beta/rc tags" # We don't follow "The short X.Y version" vs "The full version, including alpha/beta/rc tags"
# breakdown, so use the same version identifier for both to avoid confusion. # breakdown, so use the same version identifier for both to avoid confusion.
version = release = '1.16' version = release = '1.17'
# The language for content autogenerated by Sphinx. Refer to documentation # The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages. # for a list of supported languages.

View File

@ -34,7 +34,7 @@ An example is the ``gc`` module discussed in :ref:`memorymanagement`.
>>> gc.enable() >>> gc.enable()
>>> >>>
MicroPython has several other builtin standard/core modules like ``io``, ``uarray`` etc. MicroPython has several other builtin standard/core modules like ``io``, ``array`` etc.
Adding a new core module involves several modifications. Adding a new core module involves several modifications.
First, create the ``C`` file in the ``py/`` directory. In this example we are adding a First, create the ``C`` file in the ``py/`` directory. In this example we are adding a

View File

@ -42,8 +42,8 @@ The basic MicroPython firmware is implemented in the main port file, e.g ``main.
#include "py/gc.h" #include "py/gc.h"
#include "py/mperrno.h" #include "py/mperrno.h"
#include "py/stackctrl.h" #include "py/stackctrl.h"
#include "lib/utils/gchelper.h" #include "shared/runtime/gchelper.h"
#include "lib/utils/pyexec.h" #include "shared/runtime/pyexec.h"
// Allocate memory for the MicroPython GC heap. // Allocate memory for the MicroPython GC heap.
static char heap[4096]; static char heap[4096];
@ -106,10 +106,10 @@ We also need a Makefile at this point for the port:
SRC_C = \ SRC_C = \
main.c \ main.c \
mphalport.c \ mphalport.c \
lib/mp-readline/readline.c \ shared/readline/readline.c \
lib/utils/gchelper_generic.c \ shared/runtime/gchelper_generic.c \
lib/utils/pyexec.c \ shared/runtime/pyexec.c \
lib/utils/stdout_helpers.c \ shared/runtime/stdout_helpers.c \
# Define the required object files. # Define the required object files.
OBJ = $(PY_CORE_O) $(addprefix $(BUILD)/, $(SRC_C:.c=.o)) OBJ = $(PY_CORE_O) $(addprefix $(BUILD)/, $(SRC_C:.c=.o))
@ -245,8 +245,8 @@ That should give a MicroPython REPL. You can then run commands like:
.. code-block:: bash .. code-block:: bash
MicroPython v1.13 on 2021-01-01; example-board with unknown-cpu MicroPython v1.13 on 2021-01-01; example-board with unknown-cpu
>>> import usys >>> import sys
>>> usys.implementation >>> sys.implementation
('micropython', (1, 13, 0)) ('micropython', (1, 13, 0))
>>> >>>

View File

@ -98,7 +98,7 @@ A useful function for connecting to your local WiFi network is::
pass pass
print('network config:', wlan.ifconfig()) print('network config:', wlan.ifconfig())
Once the network is established the :mod:`socket <usocket>` module can be used Once the network is established the :mod:`socket <socket>` module can be used
to create and use TCP/UDP sockets as usual, and the ``urequests`` module for to create and use TCP/UDP sockets as usual, and the ``urequests`` module for
convenient HTTP requests. convenient HTTP requests.
@ -113,7 +113,7 @@ to reconnect forever).
Delay and timing Delay and timing
---------------- ----------------
Use the :mod:`time <utime>` module:: Use the :mod:`time <time>` module::
import time import time
@ -361,7 +361,7 @@ accessed via the :ref:`machine.SoftI2C <machine.SoftI2C>` class::
i2c.writeto(0x3a, '12') # write '12' to device with address 0x3a i2c.writeto(0x3a, '12') # write '12' to device with address 0x3a
buf = bytearray(10) # create a buffer with 10 bytes buf = bytearray(10) # create a buffer with 10 bytes
i2c.writeto(0x3a, buf) # write the given buffer to the slave i2c.writeto(0x3a, buf) # write the given buffer to the peripheral
Hardware I2C bus Hardware I2C bus
---------------- ----------------
@ -385,6 +385,24 @@ has the same methods as software I2C above::
i2c = I2C(0) i2c = I2C(0)
i2c = I2C(1, scl=Pin(5), sda=Pin(4), freq=400000) i2c = I2C(1, scl=Pin(5), sda=Pin(4), freq=400000)
I2S bus
-------
See :ref:`machine.I2S <machine.I2S>`. ::
from machine import I2S, Pin
i2s = I2S(0, sck=Pin(13), ws=Pin(14), sd=Pin(34), mode=I2S.TX, bits=16, format=I2S.STEREO, rate=44100, ibuf=40000) # create I2S object
i2s.write(buf) # write buffer of audio samples to I2S device
i2s = I2S(1, sck=Pin(33), ws=Pin(25), sd=Pin(32), mode=I2S.RX, bits=16, format=I2S.MONO, rate=22050, ibuf=40000) # create I2S object
i2s.readinto(buf) # fill buffer with audio samples from I2S device
The I2S class is currently available as a Technical Preview. During the preview period, feedback from
users is encouraged. Based on this feedback, the I2S class API and implementation may be changed.
ESP32 has two I2S buses with id=0 and id=1
Real time clock (RTC) Real time clock (RTC)
--------------------- ---------------------
@ -441,15 +459,15 @@ SD card
See :ref:`machine.SDCard <machine.SDCard>`. :: See :ref:`machine.SDCard <machine.SDCard>`. ::
import machine, uos import machine, os
# Slot 2 uses pins sck=18, cs=5, miso=19, mosi=23 # Slot 2 uses pins sck=18, cs=5, miso=19, mosi=23
sd = machine.SDCard(slot=2) sd = machine.SDCard(slot=2)
uos.mount(sd, "/sd") # mount os.mount(sd, "/sd") # mount
uos.listdir('/sd') # list directory contents os.listdir('/sd') # list directory contents
uos.umount('/sd') # eject os.umount('/sd') # eject
RMT RMT
--- ---

View File

@ -117,7 +117,7 @@ Real-time clock
RTC in ESP8266 has very bad accuracy, drift may be seconds per minute. As RTC in ESP8266 has very bad accuracy, drift may be seconds per minute. As
a workaround, to measure short enough intervals you can use a workaround, to measure short enough intervals you can use
``utime.time()``, etc. functions, and for wall clock time, synchronize from ``time.time()``, etc. functions, and for wall clock time, synchronize from
the net using included ``ntptime.py`` module. the net using included ``ntptime.py`` module.
Due to limitations of the ESP8266 chip the internal real-time clock (RTC) Due to limitations of the ESP8266 chip the internal real-time clock (RTC)
@ -203,7 +203,7 @@ limitation with usage of TLS on the low-memory devices:
communication with other devices. communication with other devices.
There are also some not implemented features specifically in MicroPython's There are also some not implemented features specifically in MicroPython's
``ussl`` module based on axTLS: ``ssl`` module based on axTLS:
6. Certificates are not validated (this makes connections susceptible 6. Certificates are not validated (this makes connections susceptible
to man-in-the-middle attacks). to man-in-the-middle attacks).

View File

@ -78,13 +78,13 @@ A useful function for connecting to your local WiFi network is::
pass pass
print('network config:', wlan.ifconfig()) print('network config:', wlan.ifconfig())
Once the network is established the :mod:`socket <usocket>` module can be used Once the network is established the :mod:`socket <socket>` module can be used
to create and use TCP/UDP sockets as usual. to create and use TCP/UDP sockets as usual.
Delay and timing Delay and timing
---------------- ----------------
Use the :mod:`time <utime>` module:: Use the :mod:`time <time>` module::
import time import time
@ -171,15 +171,15 @@ attaches the REPL).
To detach the REPL from UART0, use:: To detach the REPL from UART0, use::
import uos import os
uos.dupterm(None, 1) os.dupterm(None, 1)
The REPL is attached by default. If you have detached it, to reattach The REPL is attached by default. If you have detached it, to reattach
it use:: it use::
import uos, machine import os, machine
uart = machine.UART(0, 115200) uart = machine.UART(0, 115200)
uos.dupterm(uart, 1) os.dupterm(uart, 1)
PWM (pulse width modulation) PWM (pulse width modulation)
---------------------------- ----------------------------
@ -270,11 +270,11 @@ alias of :ref:`machine.SoftI2C <machine.SoftI2C>`)::
# construct an I2C bus # construct an I2C bus
i2c = I2C(scl=Pin(5), sda=Pin(4), freq=100000) i2c = I2C(scl=Pin(5), sda=Pin(4), freq=100000)
i2c.readfrom(0x3a, 4) # read 4 bytes from slave device with address 0x3a i2c.readfrom(0x3a, 4) # read 4 bytes from peripheral device with address 0x3a
i2c.writeto(0x3a, '12') # write '12' to slave device with address 0x3a i2c.writeto(0x3a, '12') # write '12' to peripheral device with address 0x3a
buf = bytearray(10) # create a buffer with 10 bytes buf = bytearray(10) # create a buffer with 10 bytes
i2c.writeto(0x3a, buf) # write the given buffer to the slave i2c.writeto(0x3a, buf) # write the given buffer to the peripheral
Real time clock (RTC) Real time clock (RTC)
--------------------- ---------------------

View File

@ -109,10 +109,12 @@ PC. You may also need to reduce the baudrate if you get errors when flashing
that you have. that you have.
For some boards with a particular FlashROM configuration (e.g. some variants of For some boards with a particular FlashROM configuration (e.g. some variants of
a NodeMCU board) you may need to use the following command to deploy a NodeMCU board) you may need to manually set a compatible
the firmware (note the ``-fm dio`` option):: `SPI Flash Mode <https://github.com/espressif/esptool/wiki/SPI-Flash-Modes>`_.
You'd usually pick the fastest option that is compatible with your device, but
the ``-fm dout`` option (the slowest option) should have the best compatibility::
esptool.py --port /dev/ttyUSB0 --baud 460800 write_flash --flash_size=detect -fm dio 0 esp8266-20170108-v1.8.7.bin esptool.py --port /dev/ttyUSB0 --baud 460800 write_flash --flash_size=detect -fm dout 0 esp8266-20170108-v1.8.7.bin
If the above commands run without error then MicroPython should be installed on If the above commands run without error then MicroPython should be installed on
your board! your board!

View File

@ -18,9 +18,9 @@ the REPL directly from your PC. Otherwise you will need to have a way of
communicating with the UART. communicating with the UART.
To access the prompt over USB-serial you need to use a terminal emulator program. To access the prompt over USB-serial you need to use a terminal emulator program.
On Windows TeraTerm is a good choice, on Mac you can use the built-in screen On Windows TeraTerm is a good choice, on Mac you can use the built-in ``screen``
program, and Linux has picocom and minicom. Of course, there are many other program, and Linux has ``picocom`` and ``minicom``. Of course, there are many
terminal programs that will work, so pick your favourite! other terminal programs that will work, so pick your favourite!
For example, on Linux you can try running:: For example, on Linux you can try running::

View File

@ -14,3 +14,4 @@ MicroPython documentation and references
rp2/quickref.rst rp2/quickref.rst
wipy/quickref.rst wipy/quickref.rst
unix/quickref.rst unix/quickref.rst
zephyr/quickref.rst

View File

@ -1,7 +1,7 @@
:mod:`uarray` -- arrays of numeric data :mod:`array` -- arrays of numeric data
======================================= ======================================
.. module:: uarray .. module:: array
:synopsis: efficient arrays of numeric data :synopsis: efficient arrays of numeric data
|see_cpython_module| :mod:`python:array`. |see_cpython_module| :mod:`python:array`.

View File

@ -1,7 +1,7 @@
:mod:`ubinascii` -- binary/ASCII conversions :mod:`binascii` -- binary/ASCII conversions
============================================ ===========================================
.. module:: ubinascii .. module:: binascii
:synopsis: binary/ASCII conversions :synopsis: binary/ASCII conversions
|see_cpython_module| :mod:`python:binascii`. |see_cpython_module| :mod:`python:binascii`.

View File

@ -1,7 +1,7 @@
:mod:`ubluetooth` --- low-level Bluetooth :mod:`bluetooth` --- low-level Bluetooth
========================================= ========================================
.. module:: ubluetooth .. module:: bluetooth
:synopsis: Low-level Bluetooth radio functionality :synopsis: Low-level Bluetooth radio functionality
This module provides an interface to a Bluetooth controller on a board. This module provides an interface to a Bluetooth controller on a board.
@ -110,7 +110,7 @@ Event Handling
**Note:** As an optimisation to prevent unnecessary allocations, the ``addr``, **Note:** As an optimisation to prevent unnecessary allocations, the ``addr``,
``adv_data``, ``char_data``, ``notify_data``, and ``uuid`` entries in the ``adv_data``, ``char_data``, ``notify_data``, and ``uuid`` entries in the
tuples are read-only memoryview instances pointing to ubluetooth's internal tuples are read-only memoryview instances pointing to :mod:`bluetooth`'s internal
ringbuffer, and are only valid during the invocation of the IRQ handler ringbuffer, and are only valid during the invocation of the IRQ handler
function. If your program needs to save one of these values to access after function. If your program needs to save one of these values to access after
the IRQ handler has returned (e.g. by saving it in a class instance or global the IRQ handler has returned (e.g. by saving it in a class instance or global
@ -293,7 +293,7 @@ For the ``_IRQ_PASSKEY_ACTION`` event, the available actions are::
_PASSKEY_ACTION_NUMERIC_COMPARISON = const(4) _PASSKEY_ACTION_NUMERIC_COMPARISON = const(4)
In order to save space in the firmware, these constants are not included on the In order to save space in the firmware, these constants are not included on the
:mod:`ubluetooth` module. Add the ones that you need from the list above to your :mod:`bluetooth` module. Add the ones that you need from the list above to your
program. program.
@ -485,10 +485,14 @@ writes from a client to a given characteristic, use
Reads the local value for this handle (which has either been written by Reads the local value for this handle (which has either been written by
:meth:`gatts_write <BLE.gatts_write>` or by a remote client). :meth:`gatts_write <BLE.gatts_write>` or by a remote client).
.. method:: BLE.gatts_write(value_handle, data, /) .. method:: BLE.gatts_write(value_handle, data, send_update=False, /)
Writes the local value for this handle, which can be read by a client. Writes the local value for this handle, which can be read by a client.
If *send_update* is ``True``, then any subscribed clients will be notified
(or indicated, depending on what they're subscribed to and which operations
the characteristic supports) about this write.
.. method:: BLE.gatts_notify(conn_handle, value_handle, data=None, /) .. method:: BLE.gatts_notify(conn_handle, value_handle, data=None, /)
Sends a notification request to a connected client. Sends a notification request to a connected client.
@ -499,17 +503,20 @@ writes from a client to a given characteristic, use
Otherwise, if *data* is ``None``, then the current local value (as Otherwise, if *data* is ``None``, then the current local value (as
set with :meth:`gatts_write <BLE.gatts_write>`) will be sent. set with :meth:`gatts_write <BLE.gatts_write>`) will be sent.
**Note:** The notification will be sent regardless of the subscription
status of the client to this characteristic.
.. method:: BLE.gatts_indicate(conn_handle, value_handle, /) .. method:: BLE.gatts_indicate(conn_handle, value_handle, /)
Sends an indication request to a connected client. Sends an indication request containing the characteristic's current value to
a connected client.
**Note:** This does not currently support sending a custom value, it will
always send the current local value (as set with :meth:`gatts_write
<BLE.gatts_write>`).
On acknowledgment (or failure, e.g. timeout), the On acknowledgment (or failure, e.g. timeout), the
``_IRQ_GATTS_INDICATE_DONE`` event will be raised. ``_IRQ_GATTS_INDICATE_DONE`` event will be raised.
**Note:** The indication will be sent regardless of the subscription
status of the client to this characteristic.
.. method:: BLE.gatts_set_buffer(value_handle, len, append=False, /) .. method:: BLE.gatts_set_buffer(value_handle, len, append=False, /)
Sets the internal buffer size for a value in bytes. This will limit the Sets the internal buffer size for a value in bytes. This will limit the

View File

@ -22,7 +22,7 @@ Example::
# First, we need to open a stream which holds a database # First, we need to open a stream which holds a database
# This is usually a file, but can be in-memory database # This is usually a file, but can be in-memory database
# using uio.BytesIO, a raw flash partition, etc. # using io.BytesIO, a raw flash partition, etc.
# Oftentimes, you want to create a database file if it doesn't # Oftentimes, you want to create a database file if it doesn't
# exist and open if it exists. Idiom below takes care of this. # exist and open if it exists. Idiom below takes care of this.
# DO NOT open database with "a+b" access mode. # DO NOT open database with "a+b" access mode.

View File

@ -1,5 +1,5 @@
Builtin functions and exceptions :mod:`builtins` -- builtin functions and exceptions
================================ ===================================================
All builtin functions and exceptions are described here. They are also All builtin functions and exceptions are described here. They are also
available via ``builtins`` module. available via ``builtins`` module.

View File

@ -1,7 +1,7 @@
:mod:`ucollections` -- collection and container types :mod:`collections` -- collection and container types
===================================================== ====================================================
.. module:: ucollections .. module:: collections
:synopsis: collection and container types :synopsis: collection and container types
|see_cpython_module| :mod:`python:collections`. |see_cpython_module| :mod:`python:collections`.
@ -49,7 +49,7 @@ Classes
a string with space-separated field named (but this is less efficient). a string with space-separated field named (but this is less efficient).
Example of use:: Example of use::
from ucollections import namedtuple from collections import namedtuple
MyTuple = namedtuple("MyTuple", ("id", "name")) MyTuple = namedtuple("MyTuple", ("id", "name"))
t1 = MyTuple(1, "foo") t1 = MyTuple(1, "foo")
@ -63,7 +63,7 @@ Classes
added. When ordered dict is iterated over, keys/items are returned in added. When ordered dict is iterated over, keys/items are returned in
the order they were added:: the order they were added::
from ucollections import OrderedDict from collections import OrderedDict
# To make benefit of ordered keys, OrderedDict should be initialized # To make benefit of ordered keys, OrderedDict should be initialized
# from sequence of (key, value) pairs. # from sequence of (key, value) pairs.

View File

@ -1,7 +1,7 @@
:mod:`ucryptolib` -- cryptographic ciphers :mod:`cryptolib` -- cryptographic ciphers
========================================== =========================================
.. module:: ucryptolib .. module:: cryptolib
:synopsis: cryptographic ciphers :synopsis: cryptographic ciphers
Classes Classes
@ -21,9 +21,9 @@ Classes
* *key* is an encryption/decryption key (bytes-like). * *key* is an encryption/decryption key (bytes-like).
* *mode* is: * *mode* is:
* ``1`` (or ``ucryptolib.MODE_ECB`` if it exists) for Electronic Code Book (ECB). * ``1`` (or ``cryptolib.MODE_ECB`` if it exists) for Electronic Code Book (ECB).
* ``2`` (or ``ucryptolib.MODE_CBC`` if it exists) for Cipher Block Chaining (CBC). * ``2`` (or ``cryptolib.MODE_CBC`` if it exists) for Cipher Block Chaining (CBC).
* ``6`` (or ``ucryptolib.MODE_CTR`` if it exists) for Counter mode (CTR). * ``6`` (or ``cryptolib.MODE_CTR`` if it exists) for Counter mode (CTR).
* *IV* is an initialization vector for CBC mode. * *IV* is an initialization vector for CBC mode.
* For Counter mode, *IV* is the initial value for the counter. * For Counter mode, *IV* is the initial value for the counter.

View File

@ -1,7 +1,7 @@
:mod:`uerrno` -- system error codes :mod:`errno` -- system error codes
=================================== ==================================
.. module:: uerrno .. module:: errno
:synopsis: system error codes :synopsis: system error codes
|see_cpython_module| :mod:`python:errno`. |see_cpython_module| :mod:`python:errno`.
@ -20,9 +20,9 @@ Constants
where ``exc`` is an instance of `OSError`. Usage example:: where ``exc`` is an instance of `OSError`. Usage example::
try: try:
uos.mkdir("my_dir") os.mkdir("my_dir")
except OSError as exc: except OSError as exc:
if exc.errno == uerrno.EEXIST: if exc.errno == errno.EEXIST:
print("Directory already exists") print("Directory already exists")
.. data:: errorcode .. data:: errorcode
@ -30,5 +30,5 @@ Constants
Dictionary mapping numeric error codes to strings with symbolic error Dictionary mapping numeric error codes to strings with symbolic error
code (see above):: code (see above)::
>>> print(uerrno.errorcode[uerrno.EEXIST]) >>> print(errno.errorcode[errno.EEXIST])
EEXIST EEXIST

View File

@ -91,7 +91,7 @@ methods to enable over-the-air (OTA) updates.
These methods implement the simple and :ref:`extended These methods implement the simple and :ref:`extended
<block-device-interface>` block protocol defined by <block-device-interface>` block protocol defined by
:class:`uos.AbstractBlockDev`. :class:`os.AbstractBlockDev`.
.. method:: Partition.set_boot() .. method:: Partition.set_boot()

View File

@ -103,16 +103,23 @@ Other methods
Shift the contents of the FrameBuffer by the given vector. This may Shift the contents of the FrameBuffer by the given vector. This may
leave a footprint of the previous colors in the FrameBuffer. leave a footprint of the previous colors in the FrameBuffer.
.. method:: FrameBuffer.blit(fbuf, x, y[, key]) .. method:: FrameBuffer.blit(fbuf, x, y, key=-1, palette=None)
Draw another FrameBuffer on top of the current one at the given coordinates. Draw another FrameBuffer on top of the current one at the given coordinates.
If *key* is specified then it should be a color integer and the If *key* is specified then it should be a color integer and the
corresponding color will be considered transparent: all pixels with that corresponding color will be considered transparent: all pixels with that
color value will not be drawn. color value will not be drawn.
This method works between FrameBuffer instances utilising different formats, The *palette* argument enables blitting between FrameBuffers with differing
but the resulting colors may be unexpected due to the mismatch in color formats. Typical usage is to render a monochrome or grayscale glyph/icon to
formats. a color display. The *palette* is a FrameBuffer instance whose format is
that of the current FrameBuffer. The *palette* height is one pixel and its
pixel width is the number of colors in the source FrameBuffer. The *palette*
for an N-bit source needs 2**N pixels; the *palette* for a monochrome source
would have 2 pixels representing background and foreground colors. The
application assigns a color to each pixel in the *palette*. The color of the
current pixel will be that of that *palette* pixel whose x position is the
color of the corresponding source pixel.
Constants Constants
--------- ---------

View File

@ -1,7 +1,7 @@
:mod:`uhashlib` -- hashing algorithms :mod:`hashlib` -- hashing algorithms
===================================== ====================================
.. module:: uhashlib .. module:: hashlib
:synopsis: hashing algorithms :synopsis: hashing algorithms
|see_cpython_module| :mod:`python:hashlib`. |see_cpython_module| :mod:`python:hashlib`.
@ -27,15 +27,15 @@ be implemented:
Constructors Constructors
------------ ------------
.. class:: uhashlib.sha256([data]) .. class:: hashlib.sha256([data])
Create an SHA256 hasher object and optionally feed ``data`` into it. Create an SHA256 hasher object and optionally feed ``data`` into it.
.. class:: uhashlib.sha1([data]) .. class:: hashlib.sha1([data])
Create an SHA1 hasher object and optionally feed ``data`` into it. Create an SHA1 hasher object and optionally feed ``data`` into it.
.. class:: uhashlib.md5([data]) .. class:: hashlib.md5([data])
Create an MD5 hasher object and optionally feed ``data`` into it. Create an MD5 hasher object and optionally feed ``data`` into it.
@ -53,5 +53,5 @@ Methods
.. method:: hash.hexdigest() .. method:: hash.hexdigest()
This method is NOT implemented. Use ``ubinascii.hexlify(hash.digest())`` This method is NOT implemented. Use ``binascii.hexlify(hash.digest())``
to achieve a similar effect. to achieve a similar effect.

View File

@ -1,7 +1,7 @@
:mod:`uheapq` -- heap queue algorithm :mod:`heapq` -- heap queue algorithm
===================================== ====================================
.. module:: uheapq .. module:: heapq
:synopsis: heap queue algorithm :synopsis: heap queue algorithm
|see_cpython_module| :mod:`python:heapq`. |see_cpython_module| :mod:`python:heapq`.

View File

@ -7,47 +7,39 @@ MicroPython libraries
Important summary of this section Important summary of this section
* MicroPython implements a subset of Python functionality for each module. * MicroPython provides built-in modules that mirror the functionality of the
* To ease extensibility, MicroPython versions of standard Python modules Python standard library (e.g. :mod:`os`, :mod:`time`), as well as
usually have ``u`` ("micro") prefix. MicroPython-specific modules (e.g. :mod:`bluetooth`, :mod:`machine`).
* Any particular MicroPython variant or port may miss any feature/function * Most standard library modules implement a subset of the functionality of
described in this general documentation (due to resource constraints or the equivalent Python module, and in a few cases provide some
other limitations). MicroPython-specific extensions (e.g. :mod:`array`, :mod:`os`)
* Due to resource constraints or other limitations, some ports or firmware
versions may not include all the functionality documented here.
* To allow for extensibility, the built-in modules can be extended from
Python code loaded onto the device.
This chapter describes modules (function and class libraries) which are built This chapter describes modules (function and class libraries) which are built
into MicroPython. There are a few categories of such modules: into MicroPython. This documentation in general aspires to describe all modules
and functions/classes which are implemented in the MicroPython project.
However, MicroPython is highly configurable, and each port to a particular
board/embedded system may include only a subset of the available MicroPython
libraries.
* Modules which implement a subset of standard Python functionality and are not With that in mind, please be warned that some functions/classes in a module (or
intended to be extended by the user. even the entire module) described in this documentation **may be unavailable**
* Modules which implement a subset of Python functionality, with a provision in a particular build of MicroPython on a particular system. The best place to
for extension by the user (via Python code). find general information of the availability/non-availability of a particular
* Modules which implement MicroPython extensions to the Python standard libraries. feature is the "General Information" section which contains information
* Modules specific to a particular :term:`MicroPython port` and thus not portable. pertaining to a specific :term:`MicroPython port`.
Note about the availability of the modules and their contents: This documentation
in general aspires to describe all modules and functions/classes which are
implemented in MicroPython project. However, MicroPython is highly configurable, and
each port to a particular board/embedded system makes available only a subset
of MicroPython libraries. For officially supported ports, there is an effort
to either filter out non-applicable items, or mark individual descriptions
with "Availability:" clauses describing which ports provide a given feature.
With that in mind, please still be warned that some functions/classes
in a module (or even the entire module) described in this documentation **may be
unavailable** in a particular build of MicroPython on a particular system. The
best place to find general information of the availability/non-availability
of a particular feature is the "General Information" section which contains
information pertaining to a specific :term:`MicroPython port`.
On some ports you are able to discover the available, built-in libraries that On some ports you are able to discover the available, built-in libraries that
can be imported by entering the following at the REPL:: can be imported by entering the following at the :term:`REPL`::
help('modules') help('modules')
Beyond the built-in libraries described in this documentation, many more Beyond the built-in libraries described in this documentation, many more
modules from the Python standard library, as well as further MicroPython modules from the Python standard library, as well as further MicroPython
extensions to it, can be found in `micropython-lib`. extensions to it, can be found in :term:`micropython-lib`.
Python standard libraries and micro-libraries Python standard libraries and micro-libraries
--------------------------------------------- ---------------------------------------------
@ -55,46 +47,33 @@ Python standard libraries and micro-libraries
The following standard Python libraries have been "micro-ified" to fit in with The following standard Python libraries have been "micro-ified" to fit in with
the philosophy of MicroPython. They provide the core functionality of that the philosophy of MicroPython. They provide the core functionality of that
module and are intended to be a drop-in replacement for the standard Python module and are intended to be a drop-in replacement for the standard Python
library. Some modules below use a standard Python name, but prefixed with "u", library.
e.g. ``ujson`` instead of ``json``. This is to signify that such a module is
micro-library, i.e. implements only a subset of CPython module functionality.
By naming them differently, a user has a choice to write a Python-level module
to extend functionality for better compatibility with CPython (indeed, this is
what done by the `micropython-lib` project mentioned above).
On some embedded platforms, where it may be cumbersome to add Python-level
wrapper modules to achieve naming compatibility with CPython, micro-modules
are available both by their u-name, and also by their non-u-name. The
non-u-name can be overridden by a file of that name in your library path (``sys.path``).
For example, ``import json`` will first search for a file ``json.py`` (or package
directory ``json``) and load that module if it is found. If nothing is found,
it will fallback to loading the built-in ``ujson`` module.
.. toctree:: .. toctree::
:maxdepth: 1 :maxdepth: 1
array.rst
binascii.rst
builtins.rst builtins.rst
cmath.rst cmath.rst
collections.rst
errno.rst
gc.rst gc.rst
hashlib.rst
heapq.rst
io.rst
json.rst
math.rst math.rst
uarray.rst os.rst
re.rst
select.rst
socket.rst
ssl.rst
struct.rst
sys.rst
time.rst
uasyncio.rst uasyncio.rst
ubinascii.rst zlib.rst
ucollections.rst
uerrno.rst
uhashlib.rst
uheapq.rst
uio.rst
ujson.rst
uos.rst
ure.rst
uselect.rst
usocket.rst
ussl.rst
ustruct.rst
usys.rst
utime.rst
uzlib.rst
_thread.rst _thread.rst
@ -107,13 +86,14 @@ the following libraries.
.. toctree:: .. toctree::
:maxdepth: 1 :maxdepth: 1
bluetooth.rst
btree.rst btree.rst
cryptolib.rst
framebuf.rst framebuf.rst
machine.rst machine.rst
micropython.rst micropython.rst
neopixel.rst
network.rst network.rst
ubluetooth.rst
ucryptolib.rst
uctypes.rst uctypes.rst
@ -131,7 +111,7 @@ To access platform-specific hardware use the appropriate library, e.g.
Libraries specific to the pyboard Libraries specific to the pyboard
--------------------------------- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following libraries are specific to the pyboard. The following libraries are specific to the pyboard.
@ -143,7 +123,7 @@ The following libraries are specific to the pyboard.
Libraries specific to the WiPy Libraries specific to the WiPy
------------------------------ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following libraries and classes are specific to the WiPy. The following libraries and classes are specific to the WiPy.
@ -156,7 +136,7 @@ The following libraries and classes are specific to the WiPy.
Libraries specific to the ESP8266 and ESP32 Libraries specific to the ESP8266 and ESP32
------------------------------------------- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following libraries are specific to the ESP8266 and ESP32. The following libraries are specific to the ESP8266 and ESP32.
@ -168,7 +148,7 @@ The following libraries are specific to the ESP8266 and ESP32.
Libraries specific to the RP2040 Libraries specific to the RP2040
-------------------------------- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following libraries are specific to the RP2040, as used in the Raspberry Pi Pico. The following libraries are specific to the RP2040, as used in the Raspberry Pi Pico.
@ -176,3 +156,34 @@ The following libraries are specific to the RP2040, as used in the Raspberry Pi
:maxdepth: 2 :maxdepth: 2
rp2.rst rp2.rst
Libraries specific to Zephyr
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following libraries are specific to the Zephyr port.
.. toctree::
:maxdepth: 2
zephyr.rst
Extending built-in libraries from Python
----------------------------------------
In most cases, the above modules are actually named ``umodule`` rather than
``module``, but MicroPython will alias any module prefixed with a ``u`` to the
non-``u`` version. However a file (or :term:`frozen module`) named
``module.py`` will take precedence over this alias.
This allows the user to provide an extended implementation of a built-in library
(perhaps to provide additional CPython compatibility). The user-provided module
(in ``module.py``) can still use the built-in functionality by importing
``umodule`` directly. This is used extensively in :term:`micropython-lib`. See
:ref:`packages` for more information.
This applies to both the Python standard libraries (e.g. ``os``, ``time``, etc),
but also the MicroPython libraries too (e.g. ``machine``, ``bluetooth``, etc).
The main exception is the port-specific libraries (``pyb``, ``esp``, etc).
*Other than when you specifically want to force the use of the built-in module,
we recommend always using ``import module`` rather than ``import umodule``.*

View File

@ -1,7 +1,7 @@
:mod:`uio` -- input/output streams :mod:`io` -- input/output streams
================================== =================================
.. module:: uio .. module:: io
:synopsis: input/output streams :synopsis: input/output streams
|see_cpython_module| :mod:`python:io`. |see_cpython_module| :mod:`python:io`.

View File

@ -1,7 +1,7 @@
:mod:`ujson` -- JSON encoding and decoding :mod:`json` -- JSON encoding and decoding
========================================== =========================================
.. module:: ujson .. module:: json
:synopsis: JSON encoding and decoding :synopsis: JSON encoding and decoding
|see_cpython_module| :mod:`python:json`. |see_cpython_module| :mod:`python:json`.
@ -12,14 +12,20 @@ data format.
Functions Functions
--------- ---------
.. function:: dump(obj, stream) .. function:: dump(obj, stream, separators=None)
Serialise *obj* to a JSON string, writing it to the given *stream*. Serialise *obj* to a JSON string, writing it to the given *stream*.
.. function:: dumps(obj) If specified, separators should be an ``(item_separator, key_separator)``
tuple. The default is ``(', ', ': ')``. To get the most compact JSON
representation, you should specify ``(',', ':')`` to eliminate whitespace.
.. function:: dumps(obj, separators=None)
Return *obj* represented as a JSON string. Return *obj* represented as a JSON string.
The arguments have the same meaning as in `dump`.
.. function:: load(stream) .. function:: load(stream)
Parse the given *stream*, interpreting it as a JSON string and Parse the given *stream*, interpreting it as a JSON string and

View File

@ -28,15 +28,15 @@ Example usage::
# depending on the port, extra parameters may be required # depending on the port, extra parameters may be required
# to select the peripheral and/or pins to use # to select the peripheral and/or pins to use
i2c.scan() # scan for slaves, returning a list of 7-bit addresses i2c.scan() # scan for peripherals, returning a list of 7-bit addresses
i2c.writeto(42, b'123') # write 3 bytes to slave with 7-bit address 42 i2c.writeto(42, b'123') # write 3 bytes to peripheral with 7-bit address 42
i2c.readfrom(42, 4) # read 4 bytes from slave with 7-bit address 42 i2c.readfrom(42, 4) # read 4 bytes from peripheral with 7-bit address 42
i2c.readfrom_mem(42, 8, 3) # read 3 bytes from memory of slave 42, i2c.readfrom_mem(42, 8, 3) # read 3 bytes from memory of peripheral 42,
# starting at memory-address 8 in the slave # starting at memory-address 8 in the peripheral
i2c.writeto_mem(42, 2, b'\x10') # write 1 byte to memory of slave 42 i2c.writeto_mem(42, 2, b'\x10') # write 1 byte to memory of peripheral 42
# starting at address 2 in the slave # starting at address 2 in the peripheral
Constructors Constructors
------------ ------------
@ -95,7 +95,7 @@ General Methods
Primitive I2C operations Primitive I2C operations
------------------------ ------------------------
The following methods implement the primitive I2C master bus operations and can The following methods implement the primitive I2C controller bus operations and can
be combined to make any I2C transaction. They are provided if you need more be combined to make any I2C transaction. They are provided if you need more
control over the bus, otherwise the standard methods (see below) can be used. control over the bus, otherwise the standard methods (see below) can be used.
@ -115,7 +115,7 @@ These methods are only available on the `machine.SoftI2C` class.
read is the length of *buf*. An ACK will be sent on the bus after read is the length of *buf*. An ACK will be sent on the bus after
receiving all but the last byte. After the last byte is received, if *nack* receiving all but the last byte. After the last byte is received, if *nack*
is true then a NACK will be sent, otherwise an ACK will be sent (and in this is true then a NACK will be sent, otherwise an ACK will be sent (and in this
case the slave assumes more bytes are going to be read in a later call). case the peripheral assumes more bytes are going to be read in a later call).
.. method:: I2C.write(buf) .. method:: I2C.write(buf)
@ -126,18 +126,18 @@ These methods are only available on the `machine.SoftI2C` class.
Standard bus operations Standard bus operations
----------------------- -----------------------
The following methods implement the standard I2C master read and write The following methods implement the standard I2C controller read and write
operations that target a given slave device. operations that target a given peripheral device.
.. method:: I2C.readfrom(addr, nbytes, stop=True, /) .. method:: I2C.readfrom(addr, nbytes, stop=True, /)
Read *nbytes* from the slave specified by *addr*. Read *nbytes* from the peripheral specified by *addr*.
If *stop* is true then a STOP condition is generated at the end of the transfer. If *stop* is true then a STOP condition is generated at the end of the transfer.
Returns a `bytes` object with the data read. Returns a `bytes` object with the data read.
.. method:: I2C.readfrom_into(addr, buf, stop=True, /) .. method:: I2C.readfrom_into(addr, buf, stop=True, /)
Read into *buf* from the slave specified by *addr*. Read into *buf* from the peripheral specified by *addr*.
The number of bytes read will be the length of *buf*. The number of bytes read will be the length of *buf*.
If *stop* is true then a STOP condition is generated at the end of the transfer. If *stop* is true then a STOP condition is generated at the end of the transfer.
@ -145,7 +145,7 @@ operations that target a given slave device.
.. method:: I2C.writeto(addr, buf, stop=True, /) .. method:: I2C.writeto(addr, buf, stop=True, /)
Write the bytes from *buf* to the slave specified by *addr*. If a Write the bytes from *buf* to the peripheral specified by *addr*. If a
NACK is received following the write of a byte from *buf* then the NACK is received following the write of a byte from *buf* then the
remaining bytes are not sent. If *stop* is true then a STOP condition is remaining bytes are not sent. If *stop* is true then a STOP condition is
generated at the end of the transfer, even if a NACK is received. generated at the end of the transfer, even if a NACK is received.
@ -153,7 +153,7 @@ operations that target a given slave device.
.. method:: I2C.writevto(addr, vector, stop=True, /) .. method:: I2C.writevto(addr, vector, stop=True, /)
Write the bytes contained in *vector* to the slave specified by *addr*. Write the bytes contained in *vector* to the peripheral specified by *addr*.
*vector* should be a tuple or list of objects with the buffer protocol. *vector* should be a tuple or list of objects with the buffer protocol.
The *addr* is sent once and then the bytes from each object in *vector* The *addr* is sent once and then the bytes from each object in *vector*
are written out sequentially. The objects in *vector* may be zero bytes are written out sequentially. The objects in *vector* may be zero bytes
@ -170,19 +170,19 @@ Memory operations
Some I2C devices act as a memory device (or set of registers) that can be read Some I2C devices act as a memory device (or set of registers) that can be read
from and written to. In this case there are two addresses associated with an from and written to. In this case there are two addresses associated with an
I2C transaction: the slave address and the memory address. The following I2C transaction: the peripheral address and the memory address. The following
methods are convenience functions to communicate with such devices. methods are convenience functions to communicate with such devices.
.. method:: I2C.readfrom_mem(addr, memaddr, nbytes, *, addrsize=8) .. method:: I2C.readfrom_mem(addr, memaddr, nbytes, *, addrsize=8)
Read *nbytes* from the slave specified by *addr* starting from the memory Read *nbytes* from the peripheral specified by *addr* starting from the memory
address specified by *memaddr*. address specified by *memaddr*.
The argument *addrsize* specifies the address size in bits. The argument *addrsize* specifies the address size in bits.
Returns a `bytes` object with the data read. Returns a `bytes` object with the data read.
.. method:: I2C.readfrom_mem_into(addr, memaddr, buf, *, addrsize=8) .. method:: I2C.readfrom_mem_into(addr, memaddr, buf, *, addrsize=8)
Read into *buf* from the slave specified by *addr* starting from the Read into *buf* from the peripheral specified by *addr* starting from the
memory address specified by *memaddr*. The number of bytes read is the memory address specified by *memaddr*. The number of bytes read is the
length of *buf*. length of *buf*.
The argument *addrsize* specifies the address size in bits (on ESP8266 The argument *addrsize* specifies the address size in bits (on ESP8266
@ -192,7 +192,7 @@ methods are convenience functions to communicate with such devices.
.. method:: I2C.writeto_mem(addr, memaddr, buf, *, addrsize=8) .. method:: I2C.writeto_mem(addr, memaddr, buf, *, addrsize=8)
Write *buf* to the slave specified by *addr* starting from the Write *buf* to the peripheral specified by *addr* starting from the
memory address specified by *memaddr*. memory address specified by *memaddr*.
The argument *addrsize* specifies the address size in bits (on ESP8266 The argument *addrsize* specifies the address size in bits (on ESP8266
this argument is not recognised and the address size is always 8 bits). this argument is not recognised and the address size is always 8 bits).

View File

@ -0,0 +1,162 @@
.. currentmodule:: machine
.. _machine.I2S:
class I2S -- Inter-IC Sound bus protocol
========================================
I2S is a synchronous serial protocol used to connect digital audio devices.
At the physical level, a bus consists of 3 lines: SCK, WS, SD.
The I2S class supports controller operation. Peripheral operation is not supported.
The I2S class is currently available as a Technical Preview. During the preview period, feedback from
users is encouraged. Based on this feedback, the I2S class API and implementation may be changed.
I2S objects can be created and initialized using::
from machine import I2S
from machine import Pin
# ESP32
sck_pin = Pin(14) # Serial clock output
ws_pin = Pin(13) # Word clock output
sd_pin = Pin(12) # Serial data output
or
# PyBoards
sck_pin = Pin("Y6") # Serial clock output
ws_pin = Pin("Y5") # Word clock output
sd_pin = Pin("Y8") # Serial data output
audio_out = I2S(2,
sck=sck_pin, ws=ws_pin, sd=sd_pin,
mode=I2S.TX,
bits=16,
format=I2S.MONO,
rate=44100,
ibuf=20000)
audio_in = I2S(2,
sck=sck_pin, ws=ws_pin, sd=sd_pin,
mode=I2S.RX,
bits=32,
format=I2S.STEREO,
rate=22050,
ibuf=20000)
3 modes of operation are supported:
- blocking
- non-blocking
- uasyncio
blocking::
num_written = audio_out.write(buf) # blocks until buf emptied
num_read = audio_in.readinto(buf) # blocks until buf filled
non-blocking::
audio_out.irq(i2s_callback) # i2s_callback is called when buf is emptied
num_written = audio_out.write(buf) # returns immediately
audio_in.irq(i2s_callback) # i2s_callback is called when buf is filled
num_read = audio_in.readinto(buf) # returns immediately
uasyncio::
swriter = uasyncio.StreamWriter(audio_out)
swriter.write(buf)
await swriter.drain()
sreader = uasyncio.StreamReader(audio_in)
num_read = await sreader.readinto(buf)
Constructor
-----------
.. class:: I2S(id, *, sck, ws, sd, mode, bits, format, rate, ibuf)
Construct an I2S object of the given id:
- ``id`` identifies a particular I2S bus.
``id`` is board and port specific:
- PYBv1.0/v1.1: has one I2S bus with id=2.
- PYBD-SFxW: has two I2S buses with id=1 and id=2.
- ESP32: has two I2S buses with id=0 and id=1.
Keyword-only parameters that are supported on all ports:
- ``sck`` is a pin object for the serial clock line
- ``ws`` is a pin object for the word select line
- ``sd`` is a pin object for the serial data line
- ``mode`` specifies receive or transmit
- ``bits`` specifies sample size (bits), 16 or 32
- ``format`` specifies channel format, STEREO or MONO
- ``rate`` specifies audio sampling rate (samples/s)
- ``ibuf`` specifies internal buffer length (bytes)
For all ports, DMA runs continuously in the background and allows user applications to perform other operations while
sample data is transfered between the internal buffer and the I2S peripheral unit.
Increasing the size of the internal buffer has the potential to increase the time that user applications can perform non-I2S operations
before underflow (e.g. ``write`` method) or overflow (e.g. ``readinto`` method).
Methods
-------
.. method:: I2S.init(sck, ...)
see Constructor for argument descriptions
.. method:: I2S.deinit()
Deinitialize the I2S bus
.. method:: I2S.readinto(buf)
Read audio samples into the buffer specified by ``buf``. ``buf`` must support the buffer protocol, such as bytearray or array.
"buf" byte ordering is little-endian. For Stereo format, left channel sample precedes right channel sample. For Mono format,
the left channel sample data is used.
Returns number of bytes read
.. method:: I2S.write(buf)
Write audio samples contained in ``buf``. ``buf`` must support the buffer protocol, such as bytearray or array.
"buf" byte ordering is little-endian. For Stereo format, left channel sample precedes right channel sample. For Mono format,
the sample data is written to both the right and left channels.
Returns number of bytes written
.. method:: I2S.irq(handler)
Set a callback. ``handler`` is called when ``buf`` is emptied (``write`` method) or becomes full (``readinto`` method).
Setting a callback changes the ``write`` and ``readinto`` methods to non-blocking operation.
``handler`` is called in the context of the MicroPython scheduler.
.. staticmethod:: I2S.shift(buf, bits, shift)
bitwise shift of all samples contained in ``buf``. ``bits`` specifies sample size in bits. ``shift`` specifies the number of bits to shift each sample.
Positive for left shift, negative for right shift.
Typically used for volume control. Each bit shift changes sample volume by 6dB.
Constants
---------
.. data:: I2S.RX
for initialising the I2S bus ``mode`` to receive
.. data:: I2S.TX
for initialising the I2S bus ``mode`` to transmit
.. data:: I2S.STEREO
for initialising the I2S bus ``format`` to stereo
.. data:: I2S.MONO
for initialising the I2S bus ``format`` to mono

View File

@ -27,10 +27,10 @@ vary from platform to platform.
This class provides access to SD or MMC storage cards using either This class provides access to SD or MMC storage cards using either
a dedicated SD/MMC interface hardware or through an SPI channel. a dedicated SD/MMC interface hardware or through an SPI channel.
The class implements the block protocol defined by :class:`uos.AbstractBlockDev`. The class implements the block protocol defined by :class:`os.AbstractBlockDev`.
This allows the mounting of an SD card to be as simple as:: This allows the mounting of an SD card to be as simple as::
uos.mount(machine.SDCard(), "/sd") os.mount(machine.SDCard(), "/sd")
The constructor takes the following parameters: The constructor takes the following parameters:

View File

@ -1,14 +1,14 @@
.. currentmodule:: machine .. currentmodule:: machine
.. _machine.SPI: .. _machine.SPI:
class SPI -- a Serial Peripheral Interface bus protocol (master side) class SPI -- a Serial Peripheral Interface bus protocol (controller side)
===================================================================== =========================================================================
SPI is a synchronous serial protocol that is driven by a master. At the SPI is a synchronous serial protocol that is driven by a controller. At the
physical level, a bus consists of 3 lines: SCK, MOSI, MISO. Multiple devices physical level, a bus consists of 3 lines: SCK, MOSI, MISO. Multiple devices
can share the same bus. Each device should have a separate, 4th signal, can share the same bus. Each device should have a separate, 4th signal,
SS (Slave Select), to select a particular device on a bus with which CS (Chip Select), to select a particular device on a bus with which
communication takes place. Management of an SS signal should happen in communication takes place. Management of a CS signal should happen in
user code (via machine.Pin class). user code (via machine.Pin class).
Both hardware and software SPI implementations exist via the Both hardware and software SPI implementations exist via the
@ -102,9 +102,9 @@ Methods
Constants Constants
--------- ---------
.. data:: SPI.MASTER .. data:: SPI.CONTROLLER
for initialising the SPI bus to master; this is only used for the WiPy for initialising the SPI bus to controller; this is only used for the WiPy
.. data:: SPI.MSB .. data:: SPI.MSB

View File

@ -56,11 +56,22 @@ Methods
- *tx* specifies the TX pin to use. - *tx* specifies the TX pin to use.
- *rx* specifies the RX pin to use. - *rx* specifies the RX pin to use.
- *rts* specifies the RTS (output) pin to use for hardware receive flow control.
- *cts* specifies the CTS (input) pin to use for hardware transmit flow control.
- *txbuf* specifies the length in characters of the TX buffer. - *txbuf* specifies the length in characters of the TX buffer.
- *rxbuf* specifies the length in characters of the RX buffer. - *rxbuf* specifies the length in characters of the RX buffer.
- *timeout* specifies the time to wait for the first character (in ms). - *timeout* specifies the time to wait for the first character (in ms).
- *timeout_char* specifies the time to wait between characters (in ms). - *timeout_char* specifies the time to wait between characters (in ms).
- *invert* specifies which lines to invert. - *invert* specifies which lines to invert.
- *flow* specifies which hardware flow control signals to use. The value
is a bitmask.
- ``0`` will ignore hardware flow control signals.
- ``UART.RTS`` will enable receive flow control by using the RTS output pin to
signal if the receive FIFO has sufficient space to accept more data.
- ``UART.CTS`` will enable transmit flow control by pausing transmission when the
CTS input pin signals that the receiver is running low on buffer space.
- ``UART.RTS | UART.CTS`` will enable both, for full hardware flow control.
On the WiPy only the following keyword-only parameter is supported: On the WiPy only the following keyword-only parameter is supported:

View File

@ -137,6 +137,28 @@ Miscellaneous functions
above. The timeout is the same for both cases and given by *timeout_us* (which above. The timeout is the same for both cases and given by *timeout_us* (which
is in microseconds). is in microseconds).
.. function:: bitstream(pin, encoding, timing, data, /)
Transmits *data* by bit-banging the specified *pin*. The *encoding* argument
specifies how the bits are encoded, and *timing* is an encoding-specific timing
specification.
The supported encodings are:
- ``0`` for "high low" pulse duration modulation. This will transmit 0 and
1 bits as timed pulses, starting with the most significant bit.
The *timing* must be a four-tuple of nanoseconds in the format
``(high_time_0, low_time_0, high_time_1, low_time_1)``. For example,
``(400, 850, 800, 450)`` is the timing specification for WS2812 RGB LEDs
at 800kHz.
The accuracy of the timing varies between ports. On Cortex M0 at 48MHz, it is
at best +/- 120ns, however on faster MCUs (ESP8266, ESP32, STM32, Pyboard), it
will be closer to +/-30ns.
.. note:: For controlling WS2812 / NeoPixel strips, see the :mod:`neopixel`
module for a higher-level API.
.. function:: rng() .. function:: rng()
Return a 24-bit software generated random number. Return a 24-bit software generated random number.
@ -181,6 +203,7 @@ Classes
machine.UART.rst machine.UART.rst
machine.SPI.rst machine.SPI.rst
machine.I2C.rst machine.I2C.rst
machine.I2S.rst
machine.RTC.rst machine.RTC.rst
machine.Timer.rst machine.Timer.rst
machine.WDT.rst machine.WDT.rst

73
docs/library/neopixel.rst Normal file
View File

@ -0,0 +1,73 @@
:mod:`neopixel` --- control of WS2812 / NeoPixel LEDs
=====================================================
.. module:: neopixel
:synopsis: control of WS2812 / NeoPixel LEDs
This module provides a driver for WS2818 / NeoPixel LEDs.
.. note:: This module is only included by default on the ESP8266 and ESP32
ports. On STM32 / Pyboard, you can `download the module
<https://github.com/micropython/micropython/blob/master/drivers/neopixel/neopixel.py>`_
and copy it to the filesystem.
class NeoPixel
--------------
This class stores pixel data for a WS2812 LED strip connected to a pin. The
application should set pixel data and then call :meth:`NeoPixel.write`
when it is ready to update the strip.
For example::
import neopixel
# 32 LED strip connected to X8.
p = machine.Pin.board.X8
n = neopixel.NeoPixel(p, 32)
# Draw a red gradient.
for i in range(32):
n[i] = (i * 8, 0, 0)
# Update the strip.
n.write()
Constructors
------------
.. class:: NeoPixel(pin, n, *, bpp=3, timing=1)
Construct an NeoPixel object. The parameters are:
- *pin* is a machine.Pin instance.
- *n* is the number of LEDs in the strip.
- *bpp* is 3 for RGB LEDs, and 4 for RGBW LEDs.
- *timing* is 0 for 400KHz, and 1 for 800kHz LEDs (most are 800kHz).
Pixel access methods
--------------------
.. method:: NeoPixel.fill(pixel)
Sets the value of all pixels to the specified *pixel* value (i.e. an
RGB/RGBW tuple).
.. method:: NeoPixel.__len__()
Returns the number of LEDs in the strip.
.. method:: NeoPixel.__setitem__(index, val)
Set the pixel at *index* to the value, which is an RGB/RGBW tuple.
.. method:: NeoPixel.__getitem__(index)
Returns the pixel at *index* as an RGB/RGBW tuple.
Output methods
--------------
.. method:: NeoPixel.write()
Writes the current pixel data to the strip.

View File

@ -46,6 +46,8 @@ Methods
.. method:: WLAN.scan() .. method:: WLAN.scan()
Scan for the available wireless networks. Scan for the available wireless networks.
Hidden networks -- where the SSID is not broadcast -- will also be scanned
if the WLAN interface allows it.
Scanning is only possible on STA interface. Returns list of tuples with Scanning is only possible on STA interface. Returns list of tuples with
the information about WiFi access points: the information about WiFi access points:
@ -53,7 +55,7 @@ Methods
(ssid, bssid, channel, RSSI, authmode, hidden) (ssid, bssid, channel, RSSI, authmode, hidden)
*bssid* is hardware address of an access point, in binary form, returned as *bssid* is hardware address of an access point, in binary form, returned as
bytes object. You can use `ubinascii.hexlify()` to convert it to ASCII form. bytes object. You can use `binascii.hexlify()` to convert it to ASCII form.
There are five values for authmode: There are five values for authmode:

View File

@ -9,7 +9,7 @@ This module provides network drivers and routing configuration. To use this
module, a MicroPython variant/build with network capabilities must be installed. module, a MicroPython variant/build with network capabilities must be installed.
Network drivers for specific hardware are available within this module and are Network drivers for specific hardware are available within this module and are
used to configure hardware network interface(s). Network services provided used to configure hardware network interface(s). Network services provided
by configured interfaces are then available for use via the :mod:`usocket` by configured interfaces are then available for use via the :mod:`socket`
module. module.
For example:: For example::
@ -17,17 +17,17 @@ For example::
# connect/ show IP config a specific network interface # connect/ show IP config a specific network interface
# see below for examples of specific drivers # see below for examples of specific drivers
import network import network
import utime import time
nic = network.Driver(...) nic = network.Driver(...)
if not nic.isconnected(): if not nic.isconnected():
nic.connect() nic.connect()
print("Waiting for connection...") print("Waiting for connection...")
while not nic.isconnected(): while not nic.isconnected():
utime.sleep(1) time.sleep(1)
print(nic.ifconfig()) print(nic.ifconfig())
# now use usocket as usual # now use socket as usual
import usocket as socket import socket
addr = socket.getaddrinfo('micropython.org', 80)[0][-1] addr = socket.getaddrinfo('micropython.org', 80)[0][-1]
s = socket.socket() s = socket.socket()
s.connect(addr) s.connect(addr)

View File

@ -1,12 +1,12 @@
:mod:`uos` -- basic "operating system" services :mod:`os` -- basic "operating system" services
=============================================== ==============================================
.. module:: uos .. module:: os
:synopsis: basic "operating system" services :synopsis: basic "operating system" services
|see_cpython_module| :mod:`python:os`. |see_cpython_module| :mod:`python:os`.
The ``uos`` module contains functions for filesystem access and mounting, The ``os`` module contains functions for filesystem access and mounting,
terminal redirection and duplication, and the ``uname`` and ``urandom`` terminal redirection and duplication, and the ``uname`` and ``urandom``
functions. functions.
@ -116,7 +116,7 @@ Terminal redirection and duplication
Duplicate or switch the MicroPython terminal (the REPL) on the given `stream`-like Duplicate or switch the MicroPython terminal (the REPL) on the given `stream`-like
object. The *stream_object* argument must be a native stream object, or derive object. The *stream_object* argument must be a native stream object, or derive
from ``uio.IOBase`` and implement the ``readinto()`` and from ``io.IOBase`` and implement the ``readinto()`` and
``write()`` methods. The stream should be in non-blocking mode and ``write()`` methods. The stream should be in non-blocking mode and
``readinto()`` should return ``None`` if there is no data available for reading. ``readinto()`` should return ``None`` if there is no data available for reading.
@ -207,7 +207,7 @@ represented by VFS classes.
otherwise the timestamps will remain untouched. Littlefs v2 filesystems without otherwise the timestamps will remain untouched. Littlefs v2 filesystems without
timestamps will work without reformatting and timestamps will be added timestamps will work without reformatting and timestamps will be added
transparently to existing files once they are opened for writing. When *mtime* transparently to existing files once they are opened for writing. When *mtime*
is enabled `uos.stat` on files without timestamps will return 0 for the timestamp. is enabled `os.stat` on files without timestamps will return 0 for the timestamp.
See :ref:`filesystem` for more information. See :ref:`filesystem` for more information.
@ -234,7 +234,7 @@ but an actual block device class must implement the methods described below.
A concrete implementation of this class will usually allow access to the A concrete implementation of this class will usually allow access to the
memory-like functionality of a piece of hardware (like flash memory). A block memory-like functionality of a piece of hardware (like flash memory). A block
device can be formatted to any supported filesystem and mounted using ``uos`` device can be formatted to any supported filesystem and mounted using ``os``
methods. methods.
See :ref:`filesystem` for example implementations of block devices using the See :ref:`filesystem` for example implementations of block devices using the

View File

@ -43,7 +43,7 @@ Methods
These methods implement the simple and :ref:`extended These methods implement the simple and :ref:`extended
<block-device-interface>` block protocol defined by <block-device-interface>` block protocol defined by
:class:`uos.AbstractBlockDev`. :class:`os.AbstractBlockDev`.
Hardware Note Hardware Note
------------- -------------

View File

@ -15,10 +15,10 @@ Example::
from pyb import I2C from pyb import I2C
i2c = I2C(1) # create on bus 1 i2c = I2C(1) # create on bus 1
i2c = I2C(1, I2C.MASTER) # create and init as a master i2c = I2C(1, I2C.CONTROLLER) # create and init as a controller
i2c.init(I2C.MASTER, baudrate=20000) # init as a master i2c.init(I2C.CONTROLLER, baudrate=20000) # init as a controller
i2c.init(I2C.SLAVE, addr=0x42) # init as a slave with given address i2c.init(I2C.PERIPHERAL, addr=0x42) # init as a peripheral with given address
i2c.deinit() # turn off the peripheral i2c.deinit() # turn off the I2C unit
Printing the i2c object gives you information about its configuration. Printing the i2c object gives you information about its configuration.
@ -37,21 +37,21 @@ You can specify a timeout (in ms)::
i2c.send(b'123', timeout=2000) # timeout after 2 seconds i2c.send(b'123', timeout=2000) # timeout after 2 seconds
A master must specify the recipient's address:: A controller must specify the recipient's address::
i2c.init(I2C.MASTER) i2c.init(I2C.CONTROLLER)
i2c.send('123', 0x42) # send 3 bytes to slave with address 0x42 i2c.send('123', 0x42) # send 3 bytes to peripheral with address 0x42
i2c.send(b'456', addr=0x42) # keyword for address i2c.send(b'456', addr=0x42) # keyword for address
Master also has other methods:: Master also has other methods::
i2c.is_ready(0x42) # check if slave 0x42 is ready i2c.is_ready(0x42) # check if peripheral 0x42 is ready
i2c.scan() # scan for slaves on the bus, returning i2c.scan() # scan for peripherals on the bus, returning
# a list of valid addresses # a list of valid addresses
i2c.mem_read(3, 0x42, 2) # read 3 bytes from memory of slave 0x42, i2c.mem_read(3, 0x42, 2) # read 3 bytes from memory of peripheral 0x42,
# starting at address 2 in the slave # starting at address 2 in the peripheral
i2c.mem_write('abc', 0x42, 2, timeout=1000) # write 'abc' (3 bytes) to memory of slave 0x42 i2c.mem_write('abc', 0x42, 2, timeout=1000) # write 'abc' (3 bytes) to memory of peripheral 0x42
# starting at address 2 in the slave, timeout after 1 second # starting at address 2 in the peripheral, timeout after 1 second
Constructors Constructors
------------ ------------
@ -88,9 +88,9 @@ Methods
Initialise the I2C bus with the given parameters: Initialise the I2C bus with the given parameters:
- ``mode`` must be either ``I2C.MASTER`` or ``I2C.SLAVE`` - ``mode`` must be either ``I2C.CONTROLLER`` or ``I2C.PERIPHERAL``
- ``addr`` is the 7-bit address (only sensible for a slave) - ``addr`` is the 7-bit address (only sensible for a peripheral)
- ``baudrate`` is the SCL clock rate (only sensible for a master) - ``baudrate`` is the SCL clock rate (only sensible for a controller)
- ``gencall`` is whether to support general call mode - ``gencall`` is whether to support general call mode
- ``dma`` is whether to allow the use of DMA for the I2C transfers (note - ``dma`` is whether to allow the use of DMA for the I2C transfers (note
that DMA transfers have more precise timing but currently do not handle bus that DMA transfers have more precise timing but currently do not handle bus
@ -98,7 +98,7 @@ Methods
.. method:: I2C.is_ready(addr) .. method:: I2C.is_ready(addr)
Check if an I2C device responds to the given address. Only valid when in master mode. Check if an I2C device responds to the given address. Only valid when in controller mode.
.. method:: I2C.mem_read(data, addr, memaddr, *, timeout=5000, addr_size=8) .. method:: I2C.mem_read(data, addr, memaddr, *, timeout=5000, addr_size=8)
@ -111,7 +111,7 @@ Methods
- ``addr_size`` selects width of memaddr: 8 or 16 bits - ``addr_size`` selects width of memaddr: 8 or 16 bits
Returns the read data. Returns the read data.
This is only valid in master mode. This is only valid in controller mode.
.. method:: I2C.mem_write(data, addr, memaddr, *, timeout=5000, addr_size=8) .. method:: I2C.mem_write(data, addr, memaddr, *, timeout=5000, addr_size=8)
@ -124,7 +124,7 @@ Methods
- ``addr_size`` selects width of memaddr: 8 or 16 bits - ``addr_size`` selects width of memaddr: 8 or 16 bits
Returns ``None``. Returns ``None``.
This is only valid in master mode. This is only valid in controller mode.
.. method:: I2C.recv(recv, addr=0x00, *, timeout=5000) .. method:: I2C.recv(recv, addr=0x00, *, timeout=5000)
@ -132,7 +132,7 @@ Methods
- ``recv`` can be an integer, which is the number of bytes to receive, - ``recv`` can be an integer, which is the number of bytes to receive,
or a mutable buffer, which will be filled with received bytes or a mutable buffer, which will be filled with received bytes
- ``addr`` is the address to receive from (only required in master mode) - ``addr`` is the address to receive from (only required in controller mode)
- ``timeout`` is the timeout in milliseconds to wait for the receive - ``timeout`` is the timeout in milliseconds to wait for the receive
Return value: if ``recv`` is an integer then a new buffer of the bytes received, Return value: if ``recv`` is an integer then a new buffer of the bytes received,
@ -143,7 +143,7 @@ Methods
Send data on the bus: Send data on the bus:
- ``send`` is the data to send (an integer to send, or a buffer object) - ``send`` is the data to send (an integer to send, or a buffer object)
- ``addr`` is the address to send to (only required in master mode) - ``addr`` is the address to send to (only required in controller mode)
- ``timeout`` is the timeout in milliseconds to wait for the send - ``timeout`` is the timeout in milliseconds to wait for the send
Return value: ``None``. Return value: ``None``.
@ -151,15 +151,15 @@ Methods
.. method:: I2C.scan() .. method:: I2C.scan()
Scan all I2C addresses from 0x01 to 0x7f and return a list of those that respond. Scan all I2C addresses from 0x01 to 0x7f and return a list of those that respond.
Only valid when in master mode. Only valid when in controller mode.
Constants Constants
--------- ---------
.. data:: I2C.MASTER .. data:: I2C.CONTROLLER
for initialising the bus to master mode for initialising the bus to controller mode
.. data:: I2C.SLAVE .. data:: I2C.PERIPHERAL
for initialising the bus to slave mode for initialising the bus to peripheral mode

View File

@ -1,19 +1,19 @@
.. currentmodule:: pyb .. currentmodule:: pyb
.. _pyb.SPI: .. _pyb.SPI:
class SPI -- a master-driven serial protocol class SPI -- a controller-driven serial protocol
============================================ ================================================
SPI is a serial protocol that is driven by a master. At the physical level SPI is a serial protocol that is driven by a controller. At the physical level
there are 3 lines: SCK, MOSI, MISO. there are 3 lines: SCK, MOSI, MISO.
See usage model of I2C; SPI is very similar. Main difference is See usage model of I2C; SPI is very similar. Main difference is
parameters to init the SPI bus:: parameters to init the SPI bus::
from pyb import SPI from pyb import SPI
spi = SPI(1, SPI.MASTER, baudrate=600000, polarity=1, phase=0, crc=0x7) spi = SPI(1, SPI.CONTROLLER, baudrate=600000, polarity=1, phase=0, crc=0x7)
Only required parameter is mode, SPI.MASTER or SPI.SLAVE. Polarity can be Only required parameter is mode, SPI.CONTROLLER or SPI.PERIPHERAL. Polarity can be
0 or 1, and is the level the idle clock line sits at. Phase can be 0 or 1 0 or 1, and is the level the idle clock line sits at. Phase can be 0 or 1
to sample data on the first or second clock edge respectively. Crc can be to sample data on the first or second clock edge respectively. Crc can be
None for no CRC, or a polynomial specifier. None for no CRC, or a polynomial specifier.
@ -55,8 +55,8 @@ Methods
Initialise the SPI bus with the given parameters: Initialise the SPI bus with the given parameters:
- ``mode`` must be either ``SPI.MASTER`` or ``SPI.SLAVE``. - ``mode`` must be either ``SPI.CONTROLLER`` or ``SPI.PERIPHERAL``.
- ``baudrate`` is the SCK clock rate (only sensible for a master). - ``baudrate`` is the SCK clock rate (only sensible for a controller).
- ``prescaler`` is the prescaler to use to derive SCK from the APB bus frequency; - ``prescaler`` is the prescaler to use to derive SCK from the APB bus frequency;
use of ``prescaler`` overrides ``baudrate``. use of ``prescaler`` overrides ``baudrate``.
- ``polarity`` can be 0 or 1, and is the level the idle clock line sits at. - ``polarity`` can be 0 or 1, and is the level the idle clock line sits at.
@ -112,10 +112,10 @@ Methods
Constants Constants
--------- ---------
.. data:: SPI.MASTER .. data:: SPI.CONTROLLER
.. data:: SPI.SLAVE .. data:: SPI.PERIPHERAL
for initialising the SPI bus to master or slave mode for initialising the SPI bus to controller or peripheral mode
.. data:: SPI.LSB .. data:: SPI.LSB
.. data:: SPI.MSB .. data:: SPI.MSB

View File

@ -213,11 +213,11 @@ Miscellaneous functions
.. function:: mount(device, mountpoint, *, readonly=False, mkfs=False) .. function:: mount(device, mountpoint, *, readonly=False, mkfs=False)
.. note:: This function is deprecated. Mounting and unmounting devices should .. note:: This function is deprecated. Mounting and unmounting devices should
be performed by :meth:`uos.mount` and :meth:`uos.umount` instead. be performed by :meth:`os.mount` and :meth:`os.umount` instead.
Mount a block device and make it available as part of the filesystem. Mount a block device and make it available as part of the filesystem.
``device`` must be an object that provides the block protocol. (The ``device`` must be an object that provides the block protocol. (The
following is also deprecated. See :class:`uos.AbstractBlockDev` for the following is also deprecated. See :class:`os.AbstractBlockDev` for the
correct way to create a block device.) correct way to create a block device.)
- ``readblocks(self, blocknum, buf)`` - ``readblocks(self, blocknum, buf)``

View File

@ -1,7 +1,7 @@
:mod:`ure` -- simple regular expressions :mod:`re` -- simple regular expressions
======================================== =======================================
.. module:: ure .. module:: re
:synopsis: regular expressions :synopsis: regular expressions
|see_cpython_module| :mod:`python:re`. |see_cpython_module| :mod:`python:re`.
@ -95,11 +95,11 @@ Supported operators and special sequences are:
Example:: Example::
import ure import re
# As ure doesn't support escapes itself, use of r"" strings is not # As re doesn't support escapes itself, use of r"" strings is not
# recommended. # recommended.
regex = ure.compile("[\r\n]") regex = re.compile("[\r\n]")
regex.split("line1\rline2\nline3\r\n") regex.split("line1\rline2\nline3\r\n")
@ -152,7 +152,7 @@ Regex objects
------------- -------------
Compiled regular expression. Instances of this class are created using Compiled regular expression. Instances of this class are created using
`ure.compile()`. `re.compile()`.
.. method:: regex.match(string) .. method:: regex.match(string)
regex.search(string) regex.search(string)

View File

@ -32,5 +32,5 @@ Methods
These methods implement the simple and extended These methods implement the simple and extended
:ref:`block protocol <block-device-interface>` defined by :ref:`block protocol <block-device-interface>` defined by
:class:`uos.AbstractBlockDev`. :class:`os.AbstractBlockDev`.

View File

@ -1,7 +1,7 @@
:mod:`uselect` -- wait for events on a set of streams :mod:`select` -- wait for events on a set of streams
======================================================================== ====================================================
.. module:: uselect .. module:: select
:synopsis: wait for events on a set of streams :synopsis: wait for events on a set of streams
|see_cpython_module| :mod:`python:select`. |see_cpython_module| :mod:`python:select`.
@ -35,15 +35,15 @@ Methods
Register `stream` *obj* for polling. *eventmask* is logical OR of: Register `stream` *obj* for polling. *eventmask* is logical OR of:
* ``uselect.POLLIN`` - data available for reading * ``select.POLLIN`` - data available for reading
* ``uselect.POLLOUT`` - more data can be written * ``select.POLLOUT`` - more data can be written
Note that flags like ``uselect.POLLHUP`` and ``uselect.POLLERR`` are Note that flags like ``select.POLLHUP`` and ``select.POLLERR`` are
*not* valid as input eventmask (these are unsolicited events which *not* valid as input eventmask (these are unsolicited events which
will be returned from `poll()` regardless of whether they are asked will be returned from `poll()` regardless of whether they are asked
for). This semantics is per POSIX. for). This semantics is per POSIX.
*eventmask* defaults to ``uselect.POLLIN | uselect.POLLOUT``. *eventmask* defaults to ``select.POLLIN | select.POLLOUT``.
It is OK to call this function multiple times for the same *obj*. It is OK to call this function multiple times for the same *obj*.
Successive calls will update *obj*'s eventmask to the value of Successive calls will update *obj*'s eventmask to the value of
@ -67,8 +67,8 @@ Methods
Returns list of (``obj``, ``event``, ...) tuples. There may be other elements in Returns list of (``obj``, ``event``, ...) tuples. There may be other elements in
tuple, depending on a platform and version, so don't assume that its size is 2. tuple, depending on a platform and version, so don't assume that its size is 2.
The ``event`` element specifies which events happened with a stream and The ``event`` element specifies which events happened with a stream and
is a combination of ``uselect.POLL*`` constants described above. Note that is a combination of ``select.POLL*`` constants described above. Note that
flags ``uselect.POLLHUP`` and ``uselect.POLLERR`` can be returned at any time flags ``select.POLLHUP`` and ``select.POLLERR`` can be returned at any time
(even if were not asked for), and must be acted on accordingly (the (even if were not asked for), and must be acted on accordingly (the
corresponding stream unregistered from poll and likely closed), because corresponding stream unregistered from poll and likely closed), because
otherwise all further invocations of `poll()` may return immediately with otherwise all further invocations of `poll()` may return immediately with

View File

@ -1,8 +1,8 @@
******************************* ******************************
:mod:`usocket` -- socket module :mod:`socket` -- socket module
******************************* ******************************
.. module:: usocket .. module:: socket
:synopsis: socket module :synopsis: socket module
|see_cpython_module| :mod:`python:socket`. |see_cpython_module| :mod:`python:socket`.
@ -21,13 +21,13 @@ This module provides access to the BSD socket interface.
Socket address format(s) Socket address format(s)
------------------------ ------------------------
The native socket address format of the ``usocket`` module is an opaque data type The native socket address format of the ``socket`` module is an opaque data type
returned by `getaddrinfo` function, which must be used to resolve textual address returned by `getaddrinfo` function, which must be used to resolve textual address
(including numeric addresses):: (including numeric addresses)::
sockaddr = usocket.getaddrinfo('www.micropython.org', 80)[0][-1] sockaddr = socket.getaddrinfo('www.micropython.org', 80)[0][-1]
# You must use getaddrinfo() even for numeric addresses # You must use getaddrinfo() even for numeric addresses
sockaddr = usocket.getaddrinfo('127.0.0.1', 80)[0][-1] sockaddr = socket.getaddrinfo('127.0.0.1', 80)[0][-1]
# Now you can use that address # Now you can use that address
sock.connect(addr) sock.connect(addr)
@ -35,7 +35,7 @@ Using `getaddrinfo` is the most efficient (both in terms of memory and processin
power) and portable way to work with addresses. power) and portable way to work with addresses.
However, ``socket`` module (note the difference with native MicroPython However, ``socket`` module (note the difference with native MicroPython
``usocket`` module described here) provides CPython-compatible way to specify ``socket`` module described here) provides CPython-compatible way to specify
addresses using tuples, as described below. Note that depending on a addresses using tuples, as described below. Note that depending on a
:term:`MicroPython port`, ``socket`` module can be builtin or need to be :term:`MicroPython port`, ``socket`` module can be builtin or need to be
installed from `micropython-lib` (as in the case of :term:`MicroPython Unix port`), installed from `micropython-lib` (as in the case of :term:`MicroPython Unix port`),
@ -54,13 +54,13 @@ Tuple address format for ``socket`` module:
dot-notation numeric IPv4 address, e.g. ``"8.8.8.8"``, and *port* is and dot-notation numeric IPv4 address, e.g. ``"8.8.8.8"``, and *port* is and
integer port number in the range 1-65535. Note the domain names are not integer port number in the range 1-65535. Note the domain names are not
accepted as *ipv4_address*, they should be resolved first using accepted as *ipv4_address*, they should be resolved first using
`usocket.getaddrinfo()`. `socket.getaddrinfo()`.
* IPv6: *(ipv6_address, port, flowinfo, scopeid)*, where *ipv6_address* * IPv6: *(ipv6_address, port, flowinfo, scopeid)*, where *ipv6_address*
is a string with colon-notation numeric IPv6 address, e.g. ``"2001:db8::1"``, is a string with colon-notation numeric IPv6 address, e.g. ``"2001:db8::1"``,
and *port* is an integer port number in the range 1-65535. *flowinfo* and *port* is an integer port number in the range 1-65535. *flowinfo*
must be 0. *scopeid* is the interface scope identifier for link-local must be 0. *scopeid* is the interface scope identifier for link-local
addresses. Note the domain names are not accepted as *ipv6_address*, addresses. Note the domain names are not accepted as *ipv6_address*,
they should be resolved first using `usocket.getaddrinfo()`. Availability they should be resolved first using `socket.getaddrinfo()`. Availability
of IPv6 support depends on a :term:`MicroPython port`. of IPv6 support depends on a :term:`MicroPython port`.
Functions Functions
@ -94,17 +94,17 @@ Functions
The following example shows how to connect to a given url:: The following example shows how to connect to a given url::
s = usocket.socket() s = socket.socket()
# This assumes that if "type" is not specified, an address for # This assumes that if "type" is not specified, an address for
# SOCK_STREAM will be returned, which may be not true # SOCK_STREAM will be returned, which may be not true
s.connect(usocket.getaddrinfo('www.micropython.org', 80)[0][-1]) s.connect(socket.getaddrinfo('www.micropython.org', 80)[0][-1])
Recommended use of filtering params:: Recommended use of filtering params::
s = usocket.socket() s = socket.socket()
# Guaranteed to return an address which can be connect'ed to for # Guaranteed to return an address which can be connect'ed to for
# stream operation. # stream operation.
s.connect(usocket.getaddrinfo('www.micropython.org', 80, 0, SOCK_STREAM)[0][-1]) s.connect(socket.getaddrinfo('www.micropython.org', 80, 0, SOCK_STREAM)[0][-1])
.. admonition:: Difference to CPython .. admonition:: Difference to CPython
:class: attention :class: attention
@ -113,7 +113,7 @@ Functions
of error in this function. MicroPython doesn't have ``socket.gaierror`` of error in this function. MicroPython doesn't have ``socket.gaierror``
and raises OSError directly. Note that error numbers of `getaddrinfo()` and raises OSError directly. Note that error numbers of `getaddrinfo()`
form a separate namespace and may not match error numbers from form a separate namespace and may not match error numbers from
the :mod:`uerrno` module. To distinguish `getaddrinfo()` errors, they are the :mod:`errno` module. To distinguish `getaddrinfo()` errors, they are
represented by negative numbers, whereas standard system errors are represented by negative numbers, whereas standard system errors are
positive numbers (error numbers are accessible using ``e.args[0]`` property positive numbers (error numbers are accessible using ``e.args[0]`` property
from an exception object). The use of negative values is a provisional from an exception object). The use of negative values is a provisional
@ -124,7 +124,7 @@ Functions
Convert a binary network address *bin_addr* of the given address family *af* Convert a binary network address *bin_addr* of the given address family *af*
to a textual representation:: to a textual representation::
>>> usocket.inet_ntop(usocket.AF_INET, b"\x7f\0\0\1") >>> socket.inet_ntop(socket.AF_INET, b"\x7f\0\0\1")
'127.0.0.1' '127.0.0.1'
.. function:: inet_pton(af, txt_addr) .. function:: inet_pton(af, txt_addr)
@ -132,7 +132,7 @@ Functions
Convert a textual network address *txt_addr* of the given address family *af* Convert a textual network address *txt_addr* of the given address family *af*
to a binary representation:: to a binary representation::
>>> usocket.inet_pton(usocket.AF_INET, "1.2.3.4") >>> socket.inet_pton(socket.AF_INET, "1.2.3.4")
b'\x01\x02\x03\x04' b'\x01\x02\x03\x04'
Constants Constants
@ -152,17 +152,17 @@ Constants
IPPROTO_TCP IPPROTO_TCP
IP protocol numbers. Availability depends on a particular :term:`MicroPython port`. IP protocol numbers. Availability depends on a particular :term:`MicroPython port`.
Note that you don't need to specify these in a call to `usocket.socket()`, Note that you don't need to specify these in a call to `socket.socket()`,
because `SOCK_STREAM` socket type automatically selects `IPPROTO_TCP`, and because `SOCK_STREAM` socket type automatically selects `IPPROTO_TCP`, and
`SOCK_DGRAM` - `IPPROTO_UDP`. Thus, the only real use of these constants `SOCK_DGRAM` - `IPPROTO_UDP`. Thus, the only real use of these constants
is as an argument to `setsockopt()`. is as an argument to `setsockopt()`.
.. data:: usocket.SOL_* .. data:: socket.SOL_*
Socket option levels (an argument to `setsockopt()`). The exact Socket option levels (an argument to `setsockopt()`). The exact
inventory depends on a :term:`MicroPython port`. inventory depends on a :term:`MicroPython port`.
.. data:: usocket.SO_* .. data:: socket.SO_*
Socket options (an argument to `setsockopt()`). The exact Socket options (an argument to `setsockopt()`). The exact
inventory depends on a :term:`MicroPython port`. inventory depends on a :term:`MicroPython port`.
@ -260,7 +260,7 @@ Methods
is put in blocking mode. is put in blocking mode.
Not every :term:`MicroPython port` supports this method. A more portable and Not every :term:`MicroPython port` supports this method. A more portable and
generic solution is to use `uselect.poll` object. This allows to wait on generic solution is to use `select.poll` object. This allows to wait on
multiple objects at the same time (and not just on sockets, but on generic multiple objects at the same time (and not just on sockets, but on generic
`stream` objects which support polling). Example:: `stream` objects which support polling). Example::
@ -269,8 +269,8 @@ Methods
s.read(10) # may timeout s.read(10) # may timeout
# Use: # Use:
poller = uselect.poll() poller = select.poll()
poller.register(s, uselect.POLLIN) poller.register(s, select.POLLIN)
res = poller.poll(1000) # time in milliseconds res = poller.poll(1000) # time in milliseconds
if not res: if not res:
# s is still not ready for input, i.e. operation timed out # s is still not ready for input, i.e. operation timed out
@ -342,7 +342,7 @@ Methods
Return value: number of bytes written. Return value: number of bytes written.
.. exception:: usocket.error .. exception:: socket.error
MicroPython does NOT have this exception. MicroPython does NOT have this exception.

View File

@ -1,7 +1,7 @@
:mod:`ussl` -- SSL/TLS module :mod:`ssl` -- SSL/TLS module
============================= ============================
.. module:: ussl .. module:: ssl
:synopsis: TLS/SSL wrapper for socket objects :synopsis: TLS/SSL wrapper for socket objects
|see_cpython_module| :mod:`python:ssl`. |see_cpython_module| :mod:`python:ssl`.
@ -13,14 +13,14 @@ facilities for network sockets, both client-side and server-side.
Functions Functions
--------- ---------
.. function:: ussl.wrap_socket(sock, server_side=False, keyfile=None, certfile=None, cert_reqs=CERT_NONE, ca_certs=None, do_handshake=True) .. function:: ssl.wrap_socket(sock, server_side=False, keyfile=None, certfile=None, cert_reqs=CERT_NONE, ca_certs=None, do_handshake=True)
Takes a `stream` *sock* (usually usocket.socket instance of ``SOCK_STREAM`` type), Takes a `stream` *sock* (usually socket.socket instance of ``SOCK_STREAM`` type),
and returns an instance of ssl.SSLSocket, which wraps the underlying stream in and returns an instance of ssl.SSLSocket, which wraps the underlying stream in
an SSL context. Returned object has the usual `stream` interface methods like an SSL context. Returned object has the usual `stream` interface methods like
``read()``, ``write()``, etc. ``read()``, ``write()``, etc.
A server-side SSL socket should be created from a normal socket returned from A server-side SSL socket should be created from a normal socket returned from
:meth:`~usocket.socket.accept()` on a non-SSL listening server socket. :meth:`~socket.socket.accept()` on a non-SSL listening server socket.
- *do_handshake* determines whether the handshake is done as part of the ``wrap_socket`` - *do_handshake* determines whether the handshake is done as part of the ``wrap_socket``
or whether it is deferred to be done as part of the initial reads or writes or whether it is deferred to be done as part of the initial reads or writes
@ -36,7 +36,7 @@ Functions
.. warning:: .. warning::
Some implementations of ``ussl`` module do NOT validate server certificates, Some implementations of ``ssl`` module do NOT validate server certificates,
which makes an SSL connection established prone to man-in-the-middle attacks. which makes an SSL connection established prone to man-in-the-middle attacks.
CPython's ``wrap_socket`` returns an ``SSLSocket`` object which has methods typical CPython's ``wrap_socket`` returns an ``SSLSocket`` object which has methods typical
@ -54,8 +54,8 @@ Exceptions
Constants Constants
--------- ---------
.. data:: ussl.CERT_NONE .. data:: ssl.CERT_NONE
ussl.CERT_OPTIONAL ssl.CERT_OPTIONAL
ussl.CERT_REQUIRED ssl.CERT_REQUIRED
Supported values for *cert_reqs* parameter. Supported values for *cert_reqs* parameter.

View File

@ -1,7 +1,7 @@
:mod:`ustruct` -- pack and unpack primitive data types :mod:`struct` -- pack and unpack primitive data types
====================================================== =====================================================
.. module:: ustruct .. module:: struct
:synopsis: pack and unpack primitive data types :synopsis: pack and unpack primitive data types
|see_cpython_module| :mod:`python:struct`. |see_cpython_module| :mod:`python:struct`.
@ -12,6 +12,11 @@ Supported format codes: ``b``, ``B``, ``h``, ``H``, ``i``, ``I``, ``l``,
``L``, ``q``, ``Q``, ``s``, ``P``, ``f``, ``d`` (the latter 2 depending ``L``, ``q``, ``Q``, ``s``, ``P``, ``f``, ``d`` (the latter 2 depending
on the floating-point support). on the floating-point support).
.. admonition:: Difference to CPython
:class: attention
Whitespace is not supported in format strings.
Functions Functions
--------- ---------

View File

@ -1,7 +1,7 @@
:mod:`usys` -- system specific functions :mod:`sys` -- system specific functions
======================================== =======================================
.. module:: usys .. module:: sys
:synopsis: system specific functions :synopsis: system specific functions
|see_cpython_module| :mod:`python:sys`. |see_cpython_module| :mod:`python:sys`.
@ -28,10 +28,10 @@ Functions
This function is a MicroPython extension intended to provide similar This function is a MicroPython extension intended to provide similar
functionality to the :mod:`atexit` module in CPython. functionality to the :mod:`atexit` module in CPython.
.. function:: print_exception(exc, file=usys.stdout, /) .. function:: print_exception(exc, file=sys.stdout, /)
Print exception with a traceback to a file-like object *file* (or Print exception with a traceback to a file-like object *file* (or
`usys.stdout` by default). `sys.stdout` by default).
.. admonition:: Difference to CPython .. admonition:: Difference to CPython
:class: attention :class: attention
@ -84,7 +84,7 @@ Constants
value directly, but instead count number of bits in it:: value directly, but instead count number of bits in it::
bits = 0 bits = 0
v = usys.maxsize v = sys.maxsize
while v: while v:
bits += 1 bits += 1
v >>= 1 v >>= 1
@ -113,7 +113,7 @@ Constants
is an identifier of a board, e.g. ``"pyboard"`` for the original MicroPython is an identifier of a board, e.g. ``"pyboard"`` for the original MicroPython
reference board. It thus can be used to distinguish one board from another. reference board. It thus can be used to distinguish one board from another.
If you need to check whether your program runs on MicroPython (vs other If you need to check whether your program runs on MicroPython (vs other
Python implementation), use `usys.implementation` instead. Python implementation), use `sys.implementation` instead.
.. data:: stderr .. data:: stderr

View File

@ -1,12 +1,12 @@
:mod:`utime` -- time related functions :mod:`time` -- time related functions
====================================== =====================================
.. module:: utime .. module:: time
:synopsis: time related functions :synopsis: time related functions
|see_cpython_module| :mod:`python:time`. |see_cpython_module| :mod:`python:time`.
The ``utime`` module provides functions for getting the current time and date, The ``time`` module provides functions for getting the current time and date,
measuring time intervals, and for delays. measuring time intervals, and for delays.
**Time Epoch**: Unix port uses standard for POSIX systems epoch of **Time Epoch**: Unix port uses standard for POSIX systems epoch of
@ -74,10 +74,19 @@ Functions
Delay for given number of milliseconds, should be positive or 0. Delay for given number of milliseconds, should be positive or 0.
This function will delay for at least the given number of milliseconds, but
may take longer than that if other processing must take place, for example
interrupt handlers or other threads. Passing in 0 for *ms* will still allow
this other processing to occur. Use `sleep_us()` for more precise delays.
.. function:: sleep_us(us) .. function:: sleep_us(us)
Delay for given number of microseconds, should be positive or 0. Delay for given number of microseconds, should be positive or 0.
This function attempts to provide an accurate delay of at least *us*
microseconds, but it may take longer if the system has other higher priority
processing to perform.
.. function:: ticks_ms() .. function:: ticks_ms()
Returns an increasing millisecond counter with an arbitrary reference point, that Returns an increasing millisecond counter with an arbitrary reference point, that
@ -110,7 +119,7 @@ Functions
in the system. This is usually CPU clocks, and that's why the function is named that in the system. This is usually CPU clocks, and that's why the function is named that
way. But it doesn't have to be a CPU clock, some other timing source available in a way. But it doesn't have to be a CPU clock, some other timing source available in a
system (e.g. high-resolution timer) can be used instead. The exact timing unit system (e.g. high-resolution timer) can be used instead. The exact timing unit
(resolution) of this function is not specified on ``utime`` module level, but (resolution) of this function is not specified on ``time`` module level, but
documentation for a specific port may provide more specific information. This documentation for a specific port may provide more specific information. This
function is intended for very fine benchmarking or very tight real-time loops. function is intended for very fine benchmarking or very tight real-time loops.
Avoid using it in portable code. Avoid using it in portable code.

View File

@ -248,6 +248,14 @@ TCP stream connections
This is a coroutine, and a MicroPython extension. This is a coroutine, and a MicroPython extension.
.. method:: Stream.readexactly(n)
Read exactly *n* bytes and return them as a bytes object.
Raises an ``EOFError`` exception if the stream ends before reading *n* bytes.
This is a coroutine.
.. method:: Stream.readline() .. method:: Stream.readline()
Read a line and return it. Read a line and return it.

View File

@ -19,7 +19,7 @@ sub-fields.
.. seealso:: .. seealso::
Module :mod:`ustruct` Module :mod:`struct`
Standard Python way to access binary data structures (doesn't scale Standard Python way to access binary data structures (doesn't scale
well to large and complex structures). well to large and complex structures).

View File

@ -0,0 +1,38 @@
.. currentmodule:: zephyr
.. _zephyr.DiskAccess:
class DiskAccess -- access to disk storage
==========================================
Uses `Zephyr Disk Access API <https://docs.zephyrproject.org/latest/reference/storage/disk/access.html>`_.
This class allows access to storage devices on the board, such as support for SD card controllers and
interfacing with SD cards via SPI. Disk devices are automatically detected and initialized on boot using
Zephyr devicetree data.
The Zephyr disk access class enables the transfer of data between a disk device and an accessible memory buffer given a disk name,
buffer, starting disk block, and number of sectors to read. MicroPython reads as many blocks as necessary to fill the buffer, so
the number of sectors to read is found by dividing the buffer length by block size of the disk.
Constructors
------------
.. class:: DiskAccess(disk_name)
Gets an object for accessing disk memory of the specific disk.
For accessing an SD card on the mimxrt1050_evk, ``disk_name`` would be ``SDHC``. See board documentation and
devicetree for usable disk names for your board (ex. RT boards use style USDHC#).
Methods
-------
.. method:: DiskAccess.readblocks(block_num, buf)
DiskAccess.readblocks(block_num, buf, offset)
.. method:: DiskAccess.writeblocks(block_num, buf)
DiskAccess.writeblocks(block_num, buf, offset)
.. method:: DiskAccess.ioctl(cmd, arg)
These methods implement the simple and extended
:ref:`block protocol <block-device-interface>` defined by
:class:`uos.AbstractBlockDev`.

View File

@ -0,0 +1,40 @@
.. currentmodule:: zephyr
.. _zephyr.FlashArea:
class FlashArea -- access to built-in flash storage
===================================================
Uses `Zephyr flash map API <https://docs.zephyrproject.org/latest/reference/storage/flash_map/flash_map.html#flash-map>`_.
This class allows access to device flash partition data.
Flash area structs consist of a globally unique ID number, the name of the flash device the partition is in,
the start offset (expressed in relation to the flash memory beginning address per partition),
and the size of the partition that the device represents. For fixed flash partitions, data from the device
tree is used; however, fixed flash partitioning is not enforced in MicroPython because MCUBoot is not enabled.
Constructors
------------
.. class:: FlashArea(id, block_size)
Gets an object for accessing flash memory at partition specified by ``id`` and with block size of ``block_size``.
``id`` values are integers correlating to fixed flash partitions defined in the devicetree.
A commonly used partition is the designated flash storage area defined as ``FlashArea.STORAGE`` if
``FLASH_AREA_LABEL_EXISTS(storage)`` returns true at boot.
Zephyr devicetree fixed flash partitions are ``boot_partition``, ``slot0_partition``, ``slot1_partition``, and
``scratch_partition``. Because MCUBoot is not enabled by default for MicroPython, these fixed partitions can be accessed by
ID integer values 1, 2, 3, and 4, respectively.
Methods
-------
.. method:: FlashArea.readblocks(block_num, buf)
FlashArea.readblocks(block_num, buf, offset)
.. method:: FlashArea.writeblocks(block_num, buf)
FlashArea.writeblocks(block_num, buf, offset)
.. method:: FlashArea.ioctl(cmd, arg)
These methods implement the simple and extended
:ref:`block protocol <block-device-interface>` defined by
:class:`uos.AbstractBlockDev`.

60
docs/library/zephyr.rst Normal file
View File

@ -0,0 +1,60 @@
.. currentmodule:: zephyr
:mod:`zephyr` --- functionality specific to the Zephyr port
===========================================================
.. module:: zephyr
:synopsis: functionality specific to Zephyr
The ``zephyr`` module contains functions and classes specific to the Zephyr port.
Functions
---------
.. function:: is_preempt_thread()
Returns true if the current thread is a preemptible thread.
Zephyr preemptible threads are those with non-negative priority values (low priority levels), which therefore,
can be supplanted as soon as a higher or equal priority thread becomes ready.
.. function:: current_tid()
Returns the thread id of the current thread, which is used to reference the thread.
.. function:: thread_analyze()
Runs the Zephyr debug thread analyzer on the current thread and prints stack size statistics in the format:
"``thread_name``-20s: STACK: unused ``available_stack_space`` usage ``stack_space_used``
/ ``stack_size`` (``percent_stack_space_used`` %); CPU: ``cpu_utilization`` %"
* *CPU utilization is only printed if runtime statistics are configured via the ``CONFIG_THREAD_RUNTIME_STATS`` kconfig*
This function can only be accessed if ``CONFIG_THREAD_ANALYZER`` is configured for the port in ``zephyr/prj.conf``.
For more infomation, see documentation for Zephyr `thread analyzer
<https://docs.zephyrproject.org/latest/guides/debug_tools/thread-analyzer.html#thread-analyzer>`_.
.. function:: shell_exec(cmd_in)
Executes the given command on an UART backend. This function can only be accessed if ``CONFIG_SHELL_BACKEND_SERIAL``
is configured for the port in ``zephyr/prj.conf``.
A list of possible commands can be found in the documentation for Zephyr `shell commands <https://docs.zephyrproject.org/latest/reference/shell/index.html?highlight=shell_execute_cmd#commands>`_.
Classes
-------
.. toctree::
:maxdepth: 1
zephyr.DiskAccess.rst
zephyr.FlashArea.rst
Additional Modules
------------------
.. toctree::
:maxdepth: 1
zephyr.zsensor.rst

View File

@ -0,0 +1,123 @@
.. currentmodule:: zsensor
:mod:`zsensor` --- Zephyr sensor bindings
=========================================
.. module:: zsensor
:synopsis: zephyr sensor bindings
The ``zsensor`` module contains a class for using sensors with Zephyr.
.. _zsensor.Sensor:
class Sensor --- sensor control for the Zephyr port
---------------------------------------------------
Use this class to access data from sensors on your board.
See Zephyr documentation for sensor usage here: `Sensors
<https://docs.zephyrproject.org/latest/reference/peripherals/sensor.html?highlight=sensor#sensors>`_.
Sensors are defined in the Zephyr devicetree for each board. The quantities that a given sensor can
measure are called a sensor channels. Sensors can have multiple channels to represent different axes
of one property or different properties a sensor can measure. See `Channels`_ below for defined sensor
channels.
Constructor
~~~~~~~~~~~
.. class:: Sensor(device_name)
Device names are defined in the devicetree for your board.
For example, the device name for the accelerometer in the FRDM-k64f board is "FXOS8700".
Methods
~~~~~~~
.. method:: Sensor.measure()
Obtains a measurement sample from the sensor device using Zephyr sensor_sample_fetch and
stores it in an internal driver buffer as a useful value, a pair of (integer part of value,
fractional part of value in 1-millionths).
Returns none if successful or OSError value if failure.
.. method:: Sensor.get_float(sensor_channel)
Returns the value of the sensor measurement sample as a float.
.. method:: Sensor.get_micros(sensor_channel)
Returns the value of the sensor measurement sample in millionths.
(Ex. value of ``(1, 500000)`` returns as ``1500000``)
.. method:: Sensor.get_millis(sensor_channel)
Returns the value of sensor measurement sample in thousandths.
(Ex. value of ``(1, 500000)`` returns as ``1500``)
.. method:: Sensor.get_int(sensor_channel)
Returns only the integer value of the measurement sample.
(Ex. value of ``(1, 500000)`` returns as ``1``)
Channels
~~~~~~~~
.. data:: ACCEL_X
Acceleration on the X axis, in m/s^2.
.. data:: ACCEL_Y
Acceleration on the Y axis, in m/s^2.
.. data:: ACCEL_Z
Acceleration on the Z axis, in m/s^2.
.. data:: GYRO_X
Angular velocity around the X axis, in radians/s.
.. data:: GYRO_Y
Angular velocity around the Y axis, in radians/s.
.. data:: GYRO_Z
Angular velocity around the Z axis, in radians/s.
.. data:: MAGN_X
Magnetic field on the X axis, in Gauss.
.. data:: MAGN_Y
Magnetic field on the Y axis, in Gauss.
.. data:: MAGN_Z
Magnetic field on the Z axis, in Gauss.
.. data:: DIE_TEMP
Device die temperature in degrees Celsius.
.. data:: PRESS
Pressure in kilopascal.
.. data:: PROX
Proximity. Dimensionless. A value of 1 indicates that an object is close.
.. data:: HUMIDITY
Humidity, in percent.
.. data:: LIGHT
Illuminance in visible spectrum, in lux.
.. data:: ALTITUDE
Altitude, in meters.

View File

@ -1,7 +1,7 @@
:mod:`uzlib` -- zlib decompression :mod:`zlib` -- zlib decompression
================================== =================================
.. module:: uzlib .. module:: zlib
:synopsis: zlib decompression :synopsis: zlib decompression
|see_cpython_module| :mod:`python:zlib`. |see_cpython_module| :mod:`python:zlib`.

View File

@ -45,7 +45,7 @@ See :mod:`pyb`. ::
Delay and timing Delay and timing
---------------- ----------------
Use the :mod:`time <utime>` module:: Use the :mod:`time <time>` module::
import time import time
@ -191,7 +191,7 @@ See :ref:`pyb.SPI <pyb.SPI>`. ::
from pyb import SPI from pyb import SPI
spi = SPI(1, SPI.MASTER, baudrate=200000, polarity=1, phase=0) spi = SPI(1, SPI.CONTROLLER, baudrate=200000, polarity=1, phase=0)
spi.send('hello') spi.send('hello')
spi.recv(5) # receive 5 bytes on the bus spi.recv(5) # receive 5 bytes on the bus
spi.send_recv('hello') # send and receive 5 bytes spi.send_recv('hello') # send and receive 5 bytes
@ -210,15 +210,35 @@ eg ``I2C(1)``. Software I2C is also available by explicitly specifying the
i2c = I2C('X', freq=400000) # create hardware I2c object i2c = I2C('X', freq=400000) # create hardware I2c object
i2c = I2C(scl='X1', sda='X2', freq=100000) # create software I2C object i2c = I2C(scl='X1', sda='X2', freq=100000) # create software I2C object
i2c.scan() # returns list of slave addresses i2c.scan() # returns list of peripheral addresses
i2c.writeto(0x42, 'hello') # write 5 bytes to slave with address 0x42 i2c.writeto(0x42, 'hello') # write 5 bytes to peripheral with address 0x42
i2c.readfrom(0x42, 5) # read 5 bytes from slave i2c.readfrom(0x42, 5) # read 5 bytes from peripheral
i2c.readfrom_mem(0x42, 0x10, 2) # read 2 bytes from slave 0x42, slave memory 0x10 i2c.readfrom_mem(0x42, 0x10, 2) # read 2 bytes from peripheral 0x42, peripheral memory 0x10
i2c.writeto_mem(0x42, 0x10, 'xy') # write 2 bytes to slave 0x42, slave memory 0x10 i2c.writeto_mem(0x42, 0x10, 'xy') # write 2 bytes to peripheral 0x42, peripheral memory 0x10
Note: for legacy I2C support see :ref:`pyb.I2C <pyb.I2C>`. Note: for legacy I2C support see :ref:`pyb.I2C <pyb.I2C>`.
I2S bus
-------
See :ref:`machine.I2S <machine.I2S>`. ::
from machine import I2S, Pin
i2s = I2S(2, sck=Pin('Y6'), ws=Pin('Y5'), sd=Pin('Y8'), mode=I2S.TX, bits=16, format=I2S.STEREO, rate=44100, ibuf=40000) # create I2S object
i2s.write(buf) # write buffer of audio samples to I2S device
i2s = I2S(1, sck=Pin('X5'), ws=Pin('X6'), sd=Pin('Y4'), mode=I2S.RX, bits=16, format=I2S.MONO, rate=22050, ibuf=40000) # create I2S object
i2s.readinto(buf) # fill buffer with audio samples from I2S device
The I2S class is currently available as a Technical Preview. During the preview period, feedback from
users is encouraged. Based on this feedback, the I2S class API and implementation may be changed.
PYBv1.0/v1.1 has one I2S bus with id=2.
PYBD-SFxW has two I2S buses with id=1 and id=2.
I2S is shared with SPI.
CAN bus (controller area network) CAN bus (controller area network)
--------------------------------- ---------------------------------

View File

@ -30,7 +30,7 @@ To set the volume, define the following function::
import pyb import pyb
def volume(val): def volume(val):
pyb.I2C(1, pyb.I2C.MASTER).mem_write(val, 46, 0) pyb.I2C(1, pyb.I2C.CONTROLLER).mem_write(val, 46, 0)
Then you can do:: Then you can do::

View File

@ -51,7 +51,7 @@ MPR121 capacitive touch sensor has address 90.
To get started, try:: To get started, try::
>>> import pyb >>> import pyb
>>> i2c = pyb.I2C(1, pyb.I2C.MASTER) >>> i2c = pyb.I2C(1, pyb.I2C.CONTROLLER)
>>> i2c.mem_write(4, 90, 0x5e) >>> i2c.mem_write(4, 90, 0x5e)
>>> touch = i2c.mem_read(1, 90, 0)[0] >>> touch = i2c.mem_read(1, 90, 0)[0]
@ -68,7 +68,7 @@ directory or ``lib/`` directory) and then try::
>>> import pyb >>> import pyb
>>> import mpr121 >>> import mpr121
>>> m = mpr121.MPR121(pyb.I2C(1, pyb.I2C.MASTER)) >>> m = mpr121.MPR121(pyb.I2C(1, pyb.I2C.CONTROLLER))
>>> for i in range(100): >>> for i in range(100):
... print(m.touch_status()) ... print(m.touch_status())
... pyb.delay(100) ... pyb.delay(100)
@ -80,7 +80,7 @@ Try touching each one in turn.
Note that if you put the LCD skin in the Y-position, then you need to Note that if you put the LCD skin in the Y-position, then you need to
initialise the I2C bus using:: initialise the I2C bus using::
>>> m = mpr121.MPR121(pyb.I2C(2, pyb.I2C.MASTER)) >>> m = mpr121.MPR121(pyb.I2C(2, pyb.I2C.CONTROLLER))
There is also a demo which uses the LCD and the touch sensors together, There is also a demo which uses the LCD and the touch sensors together,
and can be found `here <http://micropython.org/resources/examples/lcddemo.py>`__. and can be found `here <http://micropython.org/resources/examples/lcddemo.py>`__.

View File

@ -122,7 +122,7 @@ execution from Flash, RAM may be saved as follows. The data should be located in
Python modules and frozen as bytecode. The data must be defined as `bytes` Python modules and frozen as bytecode. The data must be defined as `bytes`
objects. The compiler 'knows' that `bytes` objects are immutable and ensures objects. The compiler 'knows' that `bytes` objects are immutable and ensures
that the objects remain in flash memory rather than being copied to RAM. The that the objects remain in flash memory rather than being copied to RAM. The
`ustruct` module can assist in converting between `bytes` types and other `struct` module can assist in converting between `bytes` types and other
Python built-in types. Python built-in types.
When considering the implications of frozen bytecode, note that in Python When considering the implications of frozen bytecode, note that in Python
@ -261,7 +261,7 @@ were a string.
The Python funcitons `eval` and `exec` invoke the compiler at runtime, which The Python funcitons `eval` and `exec` invoke the compiler at runtime, which
requires significant amounts of RAM. Note that the ``pickle`` library from requires significant amounts of RAM. Note that the ``pickle`` library from
`micropython-lib` employs `exec`. It may be more RAM efficient to use the `micropython-lib` employs `exec`. It may be more RAM efficient to use the
`ujson` library for object serialisation. `json` library for object serialisation.
**Storing strings in flash** **Storing strings in flash**
@ -444,7 +444,7 @@ RAM usage and speed.
Where variables are required whose size is neither a byte nor a machine word Where variables are required whose size is neither a byte nor a machine word
there are standard libraries which can assist in storing these efficiently and there are standard libraries which can assist in storing these efficiently and
in performing conversions. See the `array`, `ustruct` and `uctypes` in performing conversions. See the `array`, `struct` and `uctypes`
modules. modules.
Footnote: gc.collect() return value Footnote: gc.collect() return value

View File

@ -40,7 +40,7 @@ Block devices
------------- -------------
A block device is an instance of a class that implements the A block device is an instance of a class that implements the
:class:`uos.AbstractBlockDev` protocol. :class:`os.AbstractBlockDev` protocol.
Built-in block devices Built-in block devices
~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~
@ -116,8 +116,8 @@ It can be used as follows::
An example of a block device that supports both the simple and extended An example of a block device that supports both the simple and extended
interface (i.e. both signatures and behaviours of the interface (i.e. both signatures and behaviours of the
:meth:`uos.AbstractBlockDev.readblocks` and :meth:`os.AbstractBlockDev.readblocks` and
:meth:`uos.AbstractBlockDev.writeblocks` methods) is:: :meth:`os.AbstractBlockDev.writeblocks` methods) is::
class RAMBlockDev: class RAMBlockDev:
def __init__(self, block_size, num_blocks): def __init__(self, block_size, num_blocks):
@ -148,7 +148,7 @@ interface (i.e. both signatures and behaviours of the
return 0 return 0
As it supports the extended interface, it can be used with :class:`littlefs As it supports the extended interface, it can be used with :class:`littlefs
<uos.VfsLfs2>`:: <os.VfsLfs2>`::
import os import os
@ -166,8 +166,8 @@ normally would be used from Python code, for example::
Filesystems Filesystems
----------- -----------
MicroPython ports can provide implementations of :class:`FAT <uos.VfsFat>`, MicroPython ports can provide implementations of :class:`FAT <os.VfsFat>`,
:class:`littlefs v1 <uos.VfsLfs1>` and :class:`littlefs v2 <uos.VfsLfs2>`. :class:`littlefs v1 <os.VfsLfs1>` and :class:`littlefs v2 <os.VfsLfs2>`.
The following table shows which filesystems are included in the firmware by The following table shows which filesystems are included in the firmware by
default for given port/board combinations, however they can be optionally default for given port/board combinations, however they can be optionally

View File

@ -184,7 +184,7 @@ Glossary
``close()``, etc. A stream is an important concept in MicroPython; ``close()``, etc. A stream is an important concept in MicroPython;
many I/O objects implement the stream interface, and thus can be used many I/O objects implement the stream interface, and thus can be used
consistently and interchangeably in different contexts. For more consistently and interchangeably in different contexts. For more
information on streams in MicroPython, see the `uio` module. information on streams in MicroPython, see the `io` module.
UART UART
Acronym for "Universal Asynchronous Receiver/Transmitter". This is a Acronym for "Universal Asynchronous Receiver/Transmitter". This is a

View File

@ -1,3 +1,5 @@
.. _packages:
Distribution packages, package management, and deploying applications Distribution packages, package management, and deploying applications
===================================================================== =====================================================================

View File

@ -91,9 +91,11 @@ code these should be pre-allocated and passed as arguments or as bound objects.
When passing slices of objects such as `bytearray` instances, Python creates When passing slices of objects such as `bytearray` instances, Python creates
a copy which involves allocation of the size proportional to the size of slice. a copy which involves allocation of the size proportional to the size of slice.
This can be alleviated using a `memoryview` object. `memoryview` itself This can be alleviated using a `memoryview` object. The `memoryview` itself
is allocated on heap, but is a small, fixed-size object, regardless of the size is allocated on the heap, but is a small, fixed-size object, regardless of the size
of slice it points too. of slice it points too. Slicing a `memoryview` creates a new `memoryview`, so this
cannot be done in an interrupt service routine. Further, the slice syntax ``a:b``
causes further allocation by instantiating a ``slice(a, b)`` object.
.. code:: python .. code:: python
@ -123,7 +125,7 @@ This is a process known as profiling and is covered in textbooks and
(for standard Python) supported by various software tools. For the type of (for standard Python) supported by various software tools. For the type of
smaller embedded application likely to be running on MicroPython platforms smaller embedded application likely to be running on MicroPython platforms
the slowest function or method can usually be established by judicious use the slowest function or method can usually be established by judicious use
of the timing ``ticks`` group of functions documented in `utime`. of the timing ``ticks`` group of functions documented in `time`.
Code execution time can be measured in ms, us, or CPU cycles. Code execution time can be measured in ms, us, or CPU cycles.
The following enables any function or method to be timed by adding an The following enables any function or method to be timed by adding an
@ -134,9 +136,9 @@ The following enables any function or method to be timed by adding an
def timed_function(f, *args, **kwargs): def timed_function(f, *args, **kwargs):
myname = str(f).split(' ')[1] myname = str(f).split(' ')[1]
def new_func(*args, **kwargs): def new_func(*args, **kwargs):
t = utime.ticks_us() t = time.ticks_us()
result = f(*args, **kwargs) result = f(*args, **kwargs)
delta = utime.ticks_diff(utime.ticks_us(), t) delta = time.ticks_diff(time.ticks_us(), t)
print('Function {} Time = {:6.3f}ms'.format(myname, delta/1000)) print('Function {} Time = {:6.3f}ms'.format(myname, delta/1000))
return result return result
return new_func return new_func

View File

@ -10,9 +10,27 @@ the RP2040.
Technical specifications and SoC datasheets Technical specifications and SoC datasheets
------------------------------------------- -------------------------------------------
Datasheets! For detailed technical specifications, please refer to the `datasheets
<https://datasheets.raspberrypi.org/rp2040/rp2040-datasheet.pdf>`_
Short summary of tech specs! The RP2040 microcontroller is manufactured on a 40 nm silicon process in a 7x7mm
QFN-56 SMD package. The key features include:
Description of general structure of the port (it's built on top of the APIs * 133 MHz dual ARM Cortex-M0+ cores (overclockable to over 400 MHz)
provided by the Raspberry Pi SDK). * 264KB SRAM in six independent banks
* No internal Flash or EEPROM memory (after reset, the bootloader loads
firmware from either the external flash memory or USB bus into internal SRAM)
* QSPI bus controller, which
supports up to 16 MB of external Flash memory
* On-chip programmable LDO togenerate core voltage
* 2 on-chip PLLs to generate USB and core clocks
* 30 GPIOpins, of which 4 can optionally be used as analog inputs
The peripherals include:
* 2 UARTs
* 2 SPI controllers
* 2 I2C contollers
* 16 PWM channels
* USB 1.1 controller
* 8 PIO state machines

Binary file not shown.

After

Width:  |  Height:  |  Size: 182 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 87 KiB

View File

@ -3,7 +3,7 @@
Quick reference for the RP2 Quick reference for the RP2
=========================== ===========================
.. image:: img/rpipico.jpg .. image:: img/pico_pinout.png
:alt: Raspberry Pi Pico :alt: Raspberry Pi Pico
:width: 640px :width: 640px
@ -27,10 +27,9 @@ a troubleshooting subsection.
General board control General board control
--------------------- ---------------------
The MicroPython REPL is on the USB serial port. The MicroPython REPL is accessed via the USB serial port. Tab-completion is useful to
Tab-completion is useful to find out what methods an object has. find out what methods an object has. Paste mode (ctrl-E) is useful to paste a
Paste mode (ctrl-E) is useful to paste a large slab of Python code into large slab of Python code into the REPL.
the REPL.
The :mod:`machine` module:: The :mod:`machine` module::
@ -46,7 +45,7 @@ The :mod:`rp2` module::
Delay and timing Delay and timing
---------------- ----------------
Use the :mod:`time <utime>` module:: Use the :mod:`time <time>` module::
import time import time
@ -59,7 +58,19 @@ Use the :mod:`time <utime>` module::
Timers Timers
------ ------
How do they work? RP2040's system timer peripheral provides a global microsecond timebase and
generates interrupts for it. The software timer is available currently,
and there are unlimited number of them (memory permitting). There is no need
to specify the timer id (id=-1 is supported at the moment) as it will default
to this.
Use the :mod:`machine.Timer` class::
from machine import Timer
tim = Timer(period=5000, mode=Timer.ONE_SHOT, callback=lambda t:print(1))
tim.init(period=2000, mode=Timer.PERIODIC, callback=lambda t:print(2))
.. _rp2_Pins_and_GPIO: .. _rp2_Pins_and_GPIO:
@ -84,19 +95,28 @@ Use the :ref:`machine.Pin <machine.Pin>` class::
UART (serial bus) UART (serial bus)
----------------- -----------------
There are two UARTs, UART0 and UART1. UART0 can be mapped to GPIO 0/1, 12/13
and 16/17, and UART1 to GPIO 4/5 and 8/9.
See :ref:`machine.UART <machine.UART>`. :: See :ref:`machine.UART <machine.UART>`. ::
from machine import UART from machine import UART, Pin
uart1 = UART(1, baudrate=9600, tx=Pin(4), rx=Pin(5))
uart1 = UART(1, baudrate=9600, tx=33, rx=32)
uart1.write('hello') # write 5 bytes uart1.write('hello') # write 5 bytes
uart1.read(5) # read up to 5 bytes uart1.read(5) # read up to 5 bytes
.. note::
REPL over UART is disabled by default. You can see the :ref:`rp2_intro` for
details on how to enable REPL over UART.
PWM (pulse width modulation) PWM (pulse width modulation)
---------------------------- ----------------------------
How does PWM work on the RPi RP2xxx? There are 8 independent channels each of which have 2 outputs making it 16
PWM channels in total which can be clocked from 7Hz to 125Mhz.
Use the ``machine.PWM`` class:: Use the ``machine.PWM`` class::
@ -112,13 +132,17 @@ Use the ``machine.PWM`` class::
ADC (analog to digital conversion) ADC (analog to digital conversion)
---------------------------------- ----------------------------------
How does the ADC module work? RP2040 has five ADC channels in total, four of which are 12-bit SAR based
ADCs: GP26, GP27, GP28 and GP29. The input signal for ADC0, ADC1, ADC2 and
ADC3 can be connected with GP26, GP27, GP28, GP29 respectively (On Pico board,
GP29 is connected to VSYS). The standard ADC range is 0-3.3V. The fifth
channel is connected to the in-built temperature sensor and can be used for
measuring the temperature.
Use the :ref:`machine.ADC <machine.ADC>` class:: Use the :ref:`machine.ADC <machine.ADC>` class::
from machine import ADC from machine import ADC, Pin
adc = ADC(Pin(26)) # create ADC object on ADC pin
adc = ADC(Pin(32)) # create ADC object on ADC pin
adc.read_u16() # read value, 0-65535 across voltage range 0.0v - 3.3v adc.read_u16() # read value, 0-65535 across voltage range 0.0v - 3.3v
Software SPI bus Software SPI bus
@ -132,7 +156,7 @@ Software SPI (using bit-banging) works on all pins, and is accessed via the
# construct a SoftSPI bus on the given pins # construct a SoftSPI bus on the given pins
# polarity is the idle state of SCK # polarity is the idle state of SCK
# phase=0 means sample on the first edge of SCK, phase=1 means the second # phase=0 means sample on the first edge of SCK, phase=1 means the second
spi = SoftSPI(baudrate=100000, polarity=1, phase=0, sck=Pin(0), mosi=Pin(2), miso=Pin(4)) spi = SoftSPI(baudrate=100_000, polarity=1, phase=0, sck=Pin(0), mosi=Pin(2), miso=Pin(4))
spi.init(baudrate=200000) # set the baudrate spi.init(baudrate=200000) # set the baudrate
@ -156,14 +180,15 @@ Software SPI (using bit-banging) works on all pins, and is accessed via the
Hardware SPI bus Hardware SPI bus
---------------- ----------------
Hardware SPI is accessed via the :ref:`machine.SPI <machine.SPI>` class and The RP2040 has 2 hardware SPI buses which is accessed via the
has the same methods as software SPI above:: :ref:`machine.SPI <machine.SPI>` class and has the same methods as software
SPI above::
from machine import Pin, SPI from machine import Pin, SPI
spi = SPI(1, 10000000) spi = SPI(1, 10_000_000) # Default assignment: sck=Pin(10), mosi=Pin(11), miso=Pin(8)
spi = SPI(1, 10000000, sck=Pin(14), mosi=Pin(13), miso=Pin(12)) spi = SPI(1, 10_000_000, sck=Pin(14), mosi=Pin(15), miso=Pin(12))
spi = SPI(2, baudrate=80000000, polarity=0, phase=0, bits=8, firstbit=0, sck=Pin(18), mosi=Pin(23), miso=Pin(19)) spi = SPI(0, baudrate=80_000_000, polarity=0, phase=0, bits=8, sck=Pin(6), mosi=Pin(7), miso=Pin(4))
Software I2C bus Software I2C bus
---------------- ----------------
@ -173,7 +198,7 @@ accessed via the :ref:`machine.SoftI2C <machine.SoftI2C>` class::
from machine import Pin, SoftI2C from machine import Pin, SoftI2C
i2c = SoftI2C(scl=Pin(5), sda=Pin(4), freq=100000) i2c = SoftI2C(scl=Pin(5), sda=Pin(4), freq=100_000)
i2c.scan() # scan for devices i2c.scan() # scan for devices
@ -181,7 +206,7 @@ accessed via the :ref:`machine.SoftI2C <machine.SoftI2C>` class::
i2c.writeto(0x3a, '12') # write '12' to device with address 0x3a i2c.writeto(0x3a, '12') # write '12' to device with address 0x3a
buf = bytearray(10) # create a buffer with 10 bytes buf = bytearray(10) # create a buffer with 10 bytes
i2c.writeto(0x3a, buf) # write the given buffer to the slave i2c.writeto(0x3a, buf) # write the given buffer to the peripheral
Hardware I2C bus Hardware I2C bus
---------------- ----------------
@ -191,8 +216,8 @@ has the same methods as software I2C above::
from machine import Pin, I2C from machine import Pin, I2C
i2c = I2C(0) i2c = I2C(0) # default assignment: scl=Pin(9), sda=Pin(8)
i2c = I2C(1, scl=Pin(5), sda=Pin(4), freq=400000) i2c = I2C(1, scl=Pin(3), sda=Pin(2), freq=400_000)
Real time clock (RTC) Real time clock (RTC)
--------------------- ---------------------
@ -202,13 +227,15 @@ See :ref:`machine.RTC <machine.RTC>` ::
from machine import RTC from machine import RTC
rtc = RTC() rtc = RTC()
rtc.datetime((2017, 8, 23, 2, 12, 48, 0, 0)) # set a specific date and time rtc.datetime((2017, 8, 23, 2, 12, 48, 0, 0)) # set a specific date and
# time, eg. 2017/8/23 1:12:48
rtc.datetime() # get date and time rtc.datetime() # get date and time
WDT (Watchdog timer) WDT (Watchdog timer)
-------------------- --------------------
Is there a watchdog timer? The RP2040 has a watchdog which is a countdown timer that can restart
parts of the chip if it reaches zero.
See :ref:`machine.WDT <machine.WDT>`. :: See :ref:`machine.WDT <machine.WDT>`. ::
@ -218,21 +245,6 @@ See :ref:`machine.WDT <machine.WDT>`. ::
wdt = WDT(timeout=5000) wdt = WDT(timeout=5000)
wdt.feed() wdt.feed()
Deep-sleep mode
---------------
Is there deep-sleep support for the rp2?
The following code can be used to sleep, wake and check the reset cause::
import machine
# check if the device woke from a deep sleep
if machine.reset_cause() == machine.DEEPSLEEP_RESET:
print('woke from a deep sleep')
# put the device to sleep for 10 seconds
machine.deepsleep(10000)
OneWire driver OneWire driver
-------------- --------------

View File

@ -66,6 +66,14 @@
<a class="biglink" href="{{ pathto("wipy/quickref") }}">Quick reference for the WiPy/CC3200</a><br/> <a class="biglink" href="{{ pathto("wipy/quickref") }}">Quick reference for the WiPy/CC3200</a><br/>
<span class="linkdescr">pinout for the WiPy/CC3200, snippets of useful code, and a tutorial</span> <span class="linkdescr">pinout for the WiPy/CC3200, snippets of useful code, and a tutorial</span>
</p> </p>
<p class="biglink">
<a class="biglink" href="{{ pathto("unix/quickref") }}">Quick reference for UNIX and Windows</a><br/>
<span class="linkdescr">command-line reference</span>
</p>
<p class="biglink">
<a class="biglink" href="{{ pathto("zephyr/quickref") }}">Quick reference for the Zephyr port</a><br/>
<span class="linkdescr">snippets of useful code and a tutorial</span>
</p>
</td> </td>
</tr></table> </tr></table>

View File

@ -296,8 +296,8 @@ and put it in '/flash/cert/'. Then do::
ss = ssl.wrap_socket(s, cert_reqs=ssl.CERT_REQUIRED, ca_certs='/flash/cert/ca.pem') ss = ssl.wrap_socket(s, cert_reqs=ssl.CERT_REQUIRED, ca_certs='/flash/cert/ca.pem')
ss.connect(socket.getaddrinfo('cloud.blynk.cc', 8441)[0][-1]) ss.connect(socket.getaddrinfo('cloud.blynk.cc', 8441)[0][-1])
Incompatibilities in uhashlib module Incompatibilities in hashlib module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Due to hardware implementation details of the WiPy, data must be buffered before being Due to hardware implementation details of the WiPy, data must be buffered before being
digested, which would make it impossible to calculate the hash of big blocks of data that digested, which would make it impossible to calculate the hash of big blocks of data that
@ -310,7 +310,7 @@ initial one) is a multiple of 4 bytes.** The last chunk may be of any length.
Example:: Example::
hash = uhashlib.sha1('abcd1234', 1001) # length of the initial piece is multiple of 4 bytes hash = hashlib.sha1('abcd1234', 1001) # length of the initial piece is multiple of 4 bytes
hash.update('1234') # also multiple of 4 bytes hash.update('1234') # also multiple of 4 bytes
... ...
hash.update('12345') # last chunk may be of any length hash.update('12345') # last chunk may be of any length
@ -366,7 +366,7 @@ Adhoc VFS-like support
~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~
WiPy doesn't implement full MicroPython VFS support, instead following WiPy doesn't implement full MicroPython VFS support, instead following
functions are defined in ``uos`` module: functions are defined in ``os`` module:
.. function:: mount(block_device, mount_point, \*, readonly=False) .. function:: mount(block_device, mount_point, \*, readonly=False)

View File

@ -107,8 +107,8 @@ See :ref:`machine.SPI <machine.SPI>`. ::
from machine import SPI from machine import SPI
# configure the SPI master @ 2MHz # configure the SPI controller @ 2MHz
spi = SPI(0, SPI.MASTER, baudrate=200000, polarity=0, phase=0) spi = SPI(0, SPI.CONTROLLER, baudrate=2_000_000, polarity=0, phase=0)
spi.write('hello') spi.write('hello')
spi.read(5) # receive 5 bytes on the bus spi.read(5) # receive 5 bytes on the bus
rbuf = bytearray(5) rbuf = bytearray(5)
@ -122,11 +122,11 @@ See :ref:`machine.I2C <machine.I2C>`. ::
from machine import I2C from machine import I2C
# configure the I2C bus # configure the I2C bus
i2c = I2C(baudrate=100000) i2c = I2C(baudrate=100000)
i2c.scan() # returns list of slave addresses i2c.scan() # returns list of peripheral addresses
i2c.writeto(0x42, 'hello') # send 5 bytes to slave with address 0x42 i2c.writeto(0x42, 'hello') # send 5 bytes to peripheral with address 0x42
i2c.readfrom(0x42, 5) # receive 5 bytes from slave i2c.readfrom(0x42, 5) # receive 5 bytes from peripheral
i2c.readfrom_mem(0x42, 0x10, 2) # read 2 bytes from slave 0x42, slave memory 0x10 i2c.readfrom_mem(0x42, 0x10, 2) # read 2 bytes from peripheral 0x42, peripheral memory 0x10
i2c.writeto_mem(0x42, 0x10, 'xy') # write 2 bytes to slave 0x42, slave memory 0x10 i2c.writeto_mem(0x42, 0x10, 'xy') # write 2 bytes to peripheral 0x42, peripheral memory 0x10
Watchdog timer (WDT) Watchdog timer (WDT)
-------------------- --------------------

22
docs/zephyr/general.rst Normal file
View File

@ -0,0 +1,22 @@
.. _zephyr_general:
General information about the Zephyr port
=========================================
The Zephyr Project is a Linux Foundation hosted Collaboration Project. Its an open
source collaborative effort uniting developers and users in building a
small, scalable, real-time operating system (RTOS) optimized for resource-constrained
devices, across multiple architectures.
Multitude of boards
-------------------
There is a multitude of modules and boards from different sources that are supported
by the Zephyr OS. All boards supported by Zephyr (with standard level of features
support, like UART console) should work with MicroPython (but not all were tested).
The FRDM-K64f board is taken as a reference board for the port for this documentation.
If you have another board, please make sure you have a datasheet, schematics and other
reference materials for your board handy to look up various aspects of your board
functioning.
For a full list of Zephyr supported boards click `here (external link) <https://docs.zephyrproject.org/latest/boards/index.html#boards>`_

157
docs/zephyr/quickref.rst Normal file
View File

@ -0,0 +1,157 @@
.. _zephyr_quickref:
Quick reference for the Zephyr port
===================================
Below is a quick reference for the Zephyr port. If it is your first time working with this port please consider reading the following sections first:
.. toctree::
:maxdepth: 1
general.rst
tutorial/index.rst
Running MicroPython
-------------------
See the corresponding section of the tutorial: :ref:`intro`.
Delay and timing
----------------
Use the :mod:`time <utime>` module::
import time
time.sleep(1) # sleep for 1 second
time.sleep_ms(500) # sleep for 500 milliseconds
time.sleep_us(10) # sleep for 10 microseconds
start = time.ticks_ms() # get millisecond counter
delta = time.ticks_diff(time.ticks_ms(), start) # compute time difference
Pins and GPIO
-------------
Use the :ref:`machine.Pin <machine.Pin>` class::
from machine import Pin
pin = Pin(("GPIO_1", 21), Pin.IN) # create input pin on GPIO1
print(pin) # print pin port and number
pin.init(Pin.OUT, Pin.PULL_UP, value=1) # reinitialize pin
pin.value(1) # set pin to high
pin.value(0) # set pin to low
pin.on() # set pin to high
pin.off() # set pin to low
pin = Pin(("GPIO_1", 21), Pin.IN) # create input pin on GPIO1
pin = Pin(("GPIO_1", 21), Pin.OUT, value=1) # set pin high on creation
pin = Pin(("GPIO_1", 21), Pin.IN, Pin.PULL_UP) # enable internal pull-up resistor
switch = Pin(("GPIO_2", 6), Pin.IN) # create input pin for a switch
switch.irq(lambda t: print("SW2 changed")) # enable an interrupt when switch state is changed
Hardware I2C bus
----------------
Hardware I2C is accessed via the :ref:`machine.I2C <machine.I2C>` class::
from machine import I2C
i2c = I2C("I2C_0") # construct an i2c bus
print(i2c) # print device name
i2c.scan() # scan the device for available I2C slaves
i2c.readfrom(0x1D, 4) # read 4 bytes from slave 0x1D
i2c.readfrom_mem(0x1D, 0x0D, 1) # read 1 byte from slave 0x1D at slave memory 0x0D
i2c.writeto(0x1D, b'abcd') # write to slave with address 0x1D
i2c.writeto_mem(0x1D, 0x0D, b'ab') # write to slave 0x1D at slave memory 0x0D
buf = bytearray(8) # create buffer of size 8
i2c.writeto(0x1D, b'abcd') # write buf to slave 0x1D
Hardware SPI bus
----------------
Hardware SPI is accessed via the :ref:`machine.SPI <machine.SPI>` class::
from machine import SPI
spi = SPI("SPI_0") # construct a spi bus with default configuration
spi.init(baudrate=100000, polarity=0, phase=0, bits=8, firstbit=SPI.MSB) # set configuration
# equivalently, construct spi bus and set configuration at the same time
spi = SPI("SPI_0", baudrate=100000, polarity=0, phase=0, bits=8, firstbit=SPI.MSB)
print(spi) # print device name and bus configuration
spi.read(4) # read 4 bytes on MISO
spi.read(4, write=0xF) # read 4 bytes while writing 0xF on MOSI
buf = bytearray(8) # create a buffer of size 8
spi.readinto(buf) # read into the buffer (reads number of bytes equal to the buffer size)
spi.readinto(buf, 0xF) # read into the buffer while writing 0xF on MOSI
spi.write(b'abcd') # write 4 bytes on MOSI
buf = bytearray(4) # create buffer of size 8
spi.write_readinto(b'abcd', buf) # write to MOSI and read from MISO into the buffer
spi.write_readinto(buf, buf) # write buf to MOSI and read back into the buf
Disk Access
-----------
Use the :ref:`zephyr.DiskAccess <zephyr.DiskAccess>` class to support filesystem::
import os
from zephyr import DiskAccess
block_dev = DiskAccess('SDHC') # create a block device object for an SD card
os.VfsFat.mkfs(block_dev) # create FAT filesystem object using the disk storage block
os.mount(block_dev, '/sd') # mount the filesystem at the SD card subdirectory
# with the filesystem mounted, files can be manipulated as normal
with open('/sd/hello.txt','w') as f: # open a new file in the directory
f.write('Hello world') # write to the file
print(open('/sd/hello.txt').read()) # print contents of the file
Flash Area
----------
Use the :ref:`zephyr.FlashArea <zephyr.FlashArea>` class to support filesystem::
import os
from zephyr import FlashArea
block_dev = FlashArea(4, 4096) # creates a block device object in the frdm-k64f flash scratch partition
os.VfsLfs2.mkfs(block_dev) # create filesystem in lfs2 format using the flash block device
os.mount(block_dev, '/flash') # mount the filesystem at the flash subdirectory
# with the filesystem mounted, files can be manipulated as normal
with open('/flash/hello.txt','w') as f: # open a new file in the directory
f.write('Hello world') # write to the file
print(open('/flash/hello.txt').read()) # print contents of the file
Sensor
------
Use the :ref:`zsensor.Sensor <zsensor.Sensor>` class to access sensor data::
import zsensor
from zsensor import Sensor
accel = Sensor("FXOX8700") # create sensor object for the accelerometer
accel.measure() # obtain a measurement reading from the accelerometer
# each of these prints the value taken by measure()
accel.float(zsensor.ACCEL_X) # print measurement value for accelerometer X-axis sensor channel as float
accel.millis(zsensor.ACCEL_Y) # print measurement value for accelerometer Y-axis sensor channel in millionths
accel.micro(zsensor.ACCEL_Z) # print measurement value for accelerometer Z-axis sensor channel in thousandths
accel.int(zsensor.ACCEL_X) # print measurement integer value only for accelerometer X-axis sensor channel

View File

@ -0,0 +1,16 @@
.. _zephyr_tutorial:
MicroPython tutorial for the Zephyr port
========================================
This tutorial is intended to get you started with the Zephyr port.
.. toctree::
:maxdepth: 1
:numbered:
intro.rst
repl.rst
storage.rst
pins.rst

View File

@ -0,0 +1,30 @@
.. _intro_zephyr:
Getting started with MicroPython on the Zephyr port
===================================================
Lets get started!
Requirements
------------
To use the MicroPython Zephyr port, you will need a Zephyr supported board (for a list of acceptable
boards see :ref:`zephyr_general`).
Powering up
-----------
If your board has a USB connector on it then most likely it is powered
through this when connected to your PC. Otherwise you will need to power
it directly. Please refer to the documentation for your board for
further details.
Getting and deploying the firmware
----------------------------------
The first step you will need to do is either clone the `MicroPython repository <https://github.com/micropython/micropython.git>`_
or download it from the `MicroPython downloads page <http://micropython.org/download>`_. If you are an end user of MicroPython,
it is recommended to start with the stable firmware builds. If you would like to work on development, you may follow the daily
builds on git.
Next, follow the Zephyr port readme document (``ports/zephyr/README.md``) to build and run the application on your board.

View File

@ -0,0 +1,46 @@
.. _pins_zephyr:
GPIO Pins
=========
Use :ref:`machine.Pin <machine.Pin>` to control I/O pins.
For Zephyr, pins are initialized using a tuple of port and pin number ``(\"GPIO_x\", pin#)``
for the ``id`` value. For example to initialize a pin for the red LED on a FRDM-k64 board::
LED = Pin(("GPIO_1", 22), Pin.OUT)
Reference your board's datasheet or Zephyr documentation for pin numbers, see below for more examples.
.. list-table:: Pin Formatting
:header-rows: 1
* - Board
- Pin
- Format
* - frdm_k64f
- Red LED = PTB22
- ("GPIO_1", 22)
* - 96b_carbon
- LED1 = PD2
- ("GPIOD", 2)
* - mimxrt685_evk_cm33
- Green LED = PIO0_14
- ("GPIO0", 14)
Interrupts
----------
The Zephyr port also supports interrupt handling for Pins using `machine.Pin.irq() <machine.Pin.irq>`.
To respond to Pin change IRQs run::
from machine import Pin
SW2 = Pin(("GPIO_2", 6), Pin.IN) # create Pin object for switch 2
SW3 = Pin(("GPIO_0", 4), Pin.IN) # create Pin object for switch 3
SW2.irq(lambda t: print("SW2 changed")) # print message when SW2 state is changed (triggers change IRQ)
SW3.irq(lambda t: print("SW3 changed")) # print message when SW3 state is changed (triggers change IRQ)
while True: # wait
pass

View File

@ -0,0 +1,75 @@
Getting a MicroPython REPL prompt
=================================
REPL stands for Read Evaluate Print Loop, and is the name given to the
interactive MicroPython prompt that you can access on your board through
Zephyr. It is recommended to use REPL to test out your code and run commands.
REPL over the serial port
-------------------------
The REPL is available on a UART serial peripheral specified for the board by
the ``zephyr,console`` devicetree node. The baudrate of the REPL is 115200.
If your board has a USB-serial convertor on it then you should be able to access
the REPL directly from your PC.
To access the prompt over USB-serial you will need to use a terminal emulator
program. For a Linux or Mac machine, open a terminal and run::
screen /dev/ttyACM0 115200
You can also try ``picocom`` or ``minicom`` instead of screen. You may have to use
``/dev/ttyACM1`` or a higher number for ``ttyACM``. Additional permissions
may be necessary to access this device (eg group ``uucp`` or ``dialout``, or use sudo).
For Windows, get a terminal software, such as puTTY and connect via a serial session
using the proper COM port.
Using the REPL
--------------
With your serial program open (PuTTY, screen, picocom, etc) you may see a
blank screen with a flashing cursor. Press Enter (or reset the board) and
you should be presented with the following text::
*** Booting Zephyr OS build v2.6.0-rc1-416-g3056c5ec30ad ***
MicroPython v2.6.0-rc1-416-g3056c5ec30 on 2021-06-24; zephyr-frdm_k64f with mk64f12
Type "help()" for more information.
>>>
Now you can try running MicroPython code directly on your board.
Anything you type at the prompt, indicated by ``>>>``, will be executed after you press
the Enter key. If there is an error with the text that you enter then an error
message is printed.
Start by typing the following at the prompt to make sure it is working::
>>> print("hello world!")
hello world!
If you already know some python you can now try some basic commands here. For
example::
>>> 1 + 2
3
>>> 1 / 2
0.5
>>> 3 * 'Zephyr'
ZephyrZephyrZephyr
If your board has an LED, you can blink it using the following code::
>>>import time
>>>from machine import Pin
>>>LED = Pin(("GPIO_1", 21), Pin.OUT)
>>>while True:
... LED.value(1)
... time.sleep(0.5)
... LED.value(0)
... time.sleep(0.5)
The above code uses an LED location for a FRDM-K64F board (port B, pin 21;
following Zephyr conventions ports are identified by "GPIO_x", where *x*
starts from 0). You will need to adjust it for another board using the board's
reference materials.

View File

@ -0,0 +1,56 @@
.. _storage_zephyr:
Filesystems and Storage
=======================
Storage modules support virtual filesystem with FAT and littlefs formats, backed by either
Zephyr DiskAccess or FlashArea (flash map) APIs depending on which the board supports.
See `os Filesystem Mounting <https://docs.micropython.org/en/latest/library/os.html?highlight=os#filesystem-mounting>`_.
Disk Access
-----------
The :ref:`zephyr.DiskAccess <zephyr.DiskAccess>` class can be used to access storage devices, such as SD cards.
This class uses `Zephyr Disk Access API <https://docs.zephyrproject.org/latest/reference/storage/disk/access.html>`_ and
implements the `os.AbstractBlockDev` protocol.
For use with SD card controllers, SD cards must be present at boot & not removed; they will
be auto detected and initialized by filesystem at boot. Use the disk driver interface and a
file system to access SD cards via disk access (see below).
Example usage of FatFS with an SD card on the mimxrt1050_evk board::
import os
from zephyr import DiskAccess
bdev = zephyr.DiskAccess('SDHC') # create block device object using DiskAccess
os.VfsFat.mkfs(bdev) # create FAT filesystem object using the disk storage block
os.mount(bdev, '/sd') # mount the filesystem at the SD card subdirectory
with open('/sd/hello.txt','w') as f: # open a new file in the directory
f.write('Hello world') # write to the file
print(open('/sd/hello.txt').read()) # print contents of the file
Flash Area
----------
The :ref:`zephyr.FlashArea <zephyr.FlashArea>` class can be used to implement a low-level storage system or
customize filesystem configurations. To store persistent data on the device, using a higher-level filesystem
API is recommended (see below).
This class uses `Zephyr Flash map API <https://docs.zephyrproject.org/latest/reference/storage/flash_map/flash_map.html#>`_ and
implements the `os.AbstractBlockDev` protocol.
Example usage with the internal flash on the reel_board or the rv32m1_vega_ri5cy board::
import os
from zephyr import FlashArea
bdev = FlashArea(FlashArea.STORAGE, 4096) # create block device object using FlashArea
os.VfsLfs2.mkfs(bdev) # create Little filesystem object using the flash area block
os.mount(bdev, '/flash') # mount the filesystem at the flash storage subdirectory
with open('/flash/hello.txt','w') as f: # open a new file in the directory
f.write('Hello world') # write to the file
print(open('/flash/hello.txt').read()) # print contents of the file
For boards such as the frdm_k64f in which the MicroPython application spills into the default flash storage
partition, use the scratch partition by replacing ``FlashArea.STORAGE`` with the integer value 4.

View File

@ -28,7 +28,7 @@
#include "lwip/netif.h" #include "lwip/netif.h"
#include "lwip/dhcp.h" #include "lwip/dhcp.h"
#include "lib/netutils/dhcpserver.h" #include "shared/netutils/dhcpserver.h"
#include "drivers/cyw43/cyw43_ll.h" #include "drivers/cyw43/cyw43_ll.h"
// For trace_flags // For trace_flags

View File

@ -27,6 +27,7 @@
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include "py/mperrno.h"
#include "py/mphal.h" #include "py/mphal.h"
#include "drivers/cyw43/cyw43.h" #include "drivers/cyw43/cyw43.h"
#include "pendsv.h" #include "pendsv.h"
@ -52,6 +53,9 @@
#define WIFI_JOIN_STATE_KEYED (0x0800) #define WIFI_JOIN_STATE_KEYED (0x0800)
#define WIFI_JOIN_STATE_ALL (0x0e01) #define WIFI_JOIN_STATE_ALL (0x0e01)
#define CYW43_STA_IS_ACTIVE(self) (((self)->itf_state >> CYW43_ITF_STA) & 1)
#define CYW43_AP_IS_ACTIVE(self) (((self)->itf_state >> CYW43_ITF_AP) & 1)
cyw43_t cyw43_state; cyw43_t cyw43_state;
void (*cyw43_poll)(void); void (*cyw43_poll)(void);
uint32_t cyw43_sleep; uint32_t cyw43_sleep;
@ -102,28 +106,25 @@ void cyw43_init(cyw43_t *self) {
} }
void cyw43_deinit(cyw43_t *self) { void cyw43_deinit(cyw43_t *self) {
if (cyw43_poll == NULL) {
return;
}
CYW_ENTER CYW_ENTER
cyw43_ll_bus_sleep(&self->cyw43_ll, true); // Stop the TCP/IP network interfaces.
cyw43_delay_ms(2);
cyw43_tcpip_deinit(self, 0); cyw43_tcpip_deinit(self, 0);
cyw43_tcpip_deinit(self, 1); cyw43_tcpip_deinit(self, 1);
self->itf_state = 0; // Turn off the SDIO bus.
#if USE_SDIOIT
// Disable async polling
sdio_enable_irq(false); sdio_enable_irq(false);
cyw43_poll = NULL;
#ifdef pyb_pin_WL_RFSW_VDD
// Turn the RF-switch off
mp_hal_pin_low(pyb_pin_WL_RFSW_VDD);
#endif #endif
// Power down the WL chip and the SDIO bus
mp_hal_pin_low(pyb_pin_WL_REG_ON);
sdio_deinit(); sdio_deinit();
// Power off the WLAN chip and make sure all state is reset.
cyw43_init(self);
CYW_EXIT CYW_EXIT
} }
@ -478,7 +479,7 @@ void cyw43_wifi_set_up(cyw43_t *self, int itf, bool up) {
int cyw43_wifi_scan(cyw43_t *self, cyw43_wifi_scan_options_t *opts, void *env, int (*result_cb)(void*, const cyw43_ev_scan_result_t*)) { int cyw43_wifi_scan(cyw43_t *self, cyw43_wifi_scan_options_t *opts, void *env, int (*result_cb)(void*, const cyw43_ev_scan_result_t*)) {
if (self->itf_state == 0) { if (self->itf_state == 0) {
return -1; return -MP_EPERM;
} }
cyw43_ensure_up(self); cyw43_ensure_up(self);
@ -521,6 +522,10 @@ int cyw43_wifi_link_status(cyw43_t *self, int itf) {
// WiFi STA // WiFi STA
int cyw43_wifi_join(cyw43_t *self, size_t ssid_len, const uint8_t *ssid, size_t key_len, const uint8_t *key, uint32_t auth_type, const uint8_t *bssid, uint32_t channel) { int cyw43_wifi_join(cyw43_t *self, size_t ssid_len, const uint8_t *ssid, size_t key_len, const uint8_t *key, uint32_t auth_type, const uint8_t *bssid, uint32_t channel) {
if (!CYW43_STA_IS_ACTIVE(self)) {
return -MP_EPERM;
}
int ret = cyw43_ensure_up(self); int ret = cyw43_ensure_up(self);
if (ret) { if (ret) {
return ret; return ret;

View File

@ -28,7 +28,7 @@
#include <string.h> #include <string.h>
#include "py/mphal.h" #include "py/mphal.h"
#include "lib/netutils/netutils.h" #include "shared/netutils/netutils.h"
#include "lwip/etharp.h" #include "lwip/etharp.h"
#include "lwip/dns.h" #include "lwip/dns.h"
#include "lwip/apps/mdns.h" #include "lwip/apps/mdns.h"

View File

@ -0,0 +1,5 @@
freeze(
".",
"neopixel.py",
opt=3,
)

View File

@ -0,0 +1,46 @@
# NeoPixel driver for MicroPython
# MIT license; Copyright (c) 2016 Damien P. George, 2021 Jim Mussared
from machine import bitstream
class NeoPixel:
# G R B W
ORDER = (1, 0, 2, 3)
def __init__(self, pin, n, bpp=3, timing=1):
self.pin = pin
self.n = n
self.bpp = bpp
self.buf = bytearray(n * bpp)
self.pin.init(pin.OUT)
# Timing arg can either be 1 for 800kHz or 0 for 400kHz,
# or a user-specified timing ns tuple (high_0, low_0, high_1, low_1).
self.timing = (
((400, 850, 800, 450) if timing else (800, 1700, 1600, 900))
if isinstance(timing, int)
else timing
)
def __len__(self):
return self.n
def __setitem__(self, i, v):
offset = i * self.bpp
for i in range(self.bpp):
self.buf[offset + self.ORDER[i]] = v[i]
def __getitem__(self, i):
offset = i * self.bpp
return tuple(self.buf[offset + self.ORDER[i]] for i in range(self.bpp))
def fill(self, v):
b = self.buf
for i in range(self.bpp):
c = v[i]
for j in range(self.ORDER[i], len(self.buf), self.bpp):
b[j] = c
def write(self):
# BITSTREAM_TYPE_HIGH_LOW = 0
bitstream(self.pin, 0, self.timing, self.buf)

View File

@ -82,9 +82,9 @@ endif
endif endif
ifeq ($(MICROPY_USE_READLINE),1) ifeq ($(MICROPY_USE_READLINE),1)
INC += -I$(MPTOP)/lib/mp-readline INC += -I$(MPTOP)/shared/readline
CFLAGS_MOD += -DMICROPY_USE_READLINE=1 CFLAGS_MOD += -DMICROPY_USE_READLINE=1
LIB_SRC_C_EXTRA += mp-readline/readline.c SHARED_SRC_C_EXTRA += readline/readline.c
endif endif
ifeq ($(MICROPY_USE_READLINE),2) ifeq ($(MICROPY_USE_READLINE),2)
CFLAGS_MOD += -DMICROPY_USE_READLINE=2 CFLAGS_MOD += -DMICROPY_USE_READLINE=2
@ -145,19 +145,19 @@ SRC_C = $(addprefix ports/unix/,\
$(SRC_MOD) \ $(SRC_MOD) \
) )
LIB_SRC_C = $(addprefix lib/,\ SHARED_SRC_C = $(addprefix shared/,\
$(LIB_SRC_C_EXTRA) \ libc/printf.c \
utils/printf.c \ runtime/gchelper_generic.c \
utils/gchelper_generic.c \
timeutils/timeutils.c \ timeutils/timeutils.c \
$(SHARED_SRC_C_EXTRA) \
) )
OBJ = $(PY_O) OBJ = $(PY_O)
OBJ += $(addprefix $(BUILD)/, $(SRC_C:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(SRC_C:.c=.o))
OBJ += $(addprefix $(BUILD)/, $(LIB_SRC_C:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(SHARED_SRC_C:.c=.o))
# List of sources for qstr extraction # List of sources for qstr extraction
SRC_QSTR += $(SRC_C) $(LIB_SRC_C) SRC_QSTR += $(SRC_C) $(SHARED_SRC_C)
# Append any auto-generated sources that are needed by sources listed in # Append any auto-generated sources that are needed by sources listed in
# SRC_QSTR # SRC_QSTR
SRC_QSTR_AUTO_DEPS += SRC_QSTR_AUTO_DEPS +=

View File

@ -0,0 +1,55 @@
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2021 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef AXTLS_OS_PORT_H
#define AXTLS_OS_PORT_H
#include <errno.h>
#include "py/stream.h"
#include "lib/crypto-algorithms/sha256.h"
#define SSL_CTX_MUTEX_INIT(mutex)
#define SSL_CTX_MUTEX_DESTROY(mutex)
#define SSL_CTX_LOCK(mutex)
#define SSL_CTX_UNLOCK(mutex)
#define SOCKET_READ(s, buf, size) mp_stream_posix_read((void *)s, buf, size)
#define SOCKET_WRITE(s, buf, size) mp_stream_posix_write((void *)s, buf, size)
#define SOCKET_CLOSE(A) UNUSED
#define SOCKET_ERRNO() errno
#define SHA256_CTX CRYAL_SHA256_CTX
#define SHA256_Init(ctx) sha256_init(ctx)
#define SHA256_Update(ctx, buf, size) sha256_update(ctx, buf, size)
#define SHA256_Final(hash, ctx) sha256_final(ctx, hash)
#define TTY_FLUSH()
#ifdef WDEV_HWRNG
// For esp8266 port: use the hardware RNG.
#define PLATFORM_RNG_U8() (*WDEV_HWRNG)
#endif
#endif // AXTLS_OS_PORT_H

View File

@ -67,7 +67,7 @@ endif
LIB_SRC_C += $(SRC_BTSTACK) LIB_SRC_C += $(SRC_BTSTACK)
# Suppress some warnings. # Suppress some warnings.
BTSTACK_WARNING_CFLAGS = -Wno-old-style-definition -Wno-unused-variable -Wno-unused-parameter # -Wimplicit-fallthrough=0 BTSTACK_WARNING_CFLAGS = -Wno-old-style-definition -Wno-unused-variable -Wno-unused-parameter -Wno-implicit-fallthrough
ifneq ($(CC),clang) ifneq ($(CC),clang)
BTSTACK_WARNING_CFLAGS += -Wno-format BTSTACK_WARNING_CFLAGS += -Wno-format
endif endif

View File

@ -1085,11 +1085,14 @@ int mp_bluetooth_gatts_read(uint16_t value_handle, uint8_t **value, size_t *valu
return mp_bluetooth_gatts_db_read(MP_STATE_PORT(bluetooth_btstack_root_pointers)->gatts_db, value_handle, value, value_len); return mp_bluetooth_gatts_db_read(MP_STATE_PORT(bluetooth_btstack_root_pointers)->gatts_db, value_handle, value, value_len);
} }
int mp_bluetooth_gatts_write(uint16_t value_handle, const uint8_t *value, size_t value_len) { int mp_bluetooth_gatts_write(uint16_t value_handle, const uint8_t *value, size_t value_len, bool send_update) {
DEBUG_printf("mp_bluetooth_gatts_write\n"); DEBUG_printf("mp_bluetooth_gatts_write\n");
if (!mp_bluetooth_is_active()) { if (!mp_bluetooth_is_active()) {
return ERRNO_BLUETOOTH_NOT_ACTIVE; return ERRNO_BLUETOOTH_NOT_ACTIVE;
} }
if (send_update) {
return MP_EOPNOTSUPP;
}
return mp_bluetooth_gatts_db_write(MP_STATE_PORT(bluetooth_btstack_root_pointers)->gatts_db, value_handle, value, value_len); return mp_bluetooth_gatts_db_write(MP_STATE_PORT(bluetooth_btstack_root_pointers)->gatts_db, value_handle, value, value_len);
} }

View File

@ -4,8 +4,9 @@ set(MICROPY_EXTMOD_DIR "${MICROPY_DIR}/extmod")
set(MICROPY_OOFATFS_DIR "${MICROPY_DIR}/lib/oofatfs") set(MICROPY_OOFATFS_DIR "${MICROPY_DIR}/lib/oofatfs")
set(MICROPY_SOURCE_EXTMOD set(MICROPY_SOURCE_EXTMOD
${MICROPY_DIR}/lib/embed/abort_.c ${MICROPY_DIR}/shared/libc/abort_.c
${MICROPY_DIR}/lib/utils/printf.c ${MICROPY_DIR}/shared/libc/printf.c
${MICROPY_EXTMOD_DIR}/machine_bitstream.c
${MICROPY_EXTMOD_DIR}/machine_i2c.c ${MICROPY_EXTMOD_DIR}/machine_i2c.c
${MICROPY_EXTMOD_DIR}/machine_mem.c ${MICROPY_EXTMOD_DIR}/machine_mem.c
${MICROPY_EXTMOD_DIR}/machine_pulse.c ${MICROPY_EXTMOD_DIR}/machine_pulse.c

View File

@ -153,7 +153,7 @@ LWIP_DIR = lib/lwip/src
INC += -I$(TOP)/$(LWIP_DIR)/include INC += -I$(TOP)/$(LWIP_DIR)/include
CFLAGS_MOD += -DMICROPY_PY_LWIP=1 CFLAGS_MOD += -DMICROPY_PY_LWIP=1
$(BUILD)/$(LWIP_DIR)/core/ipv4/dhcp.o: CFLAGS_MOD += -Wno-address $(BUILD)/$(LWIP_DIR)/core/ipv4/dhcp.o: CFLAGS_MOD += -Wno-address
SRC_MOD += extmod/modlwip.c lib/netutils/netutils.c SRC_MOD += extmod/modlwip.c shared/netutils/netutils.c
SRC_MOD += $(addprefix $(LWIP_DIR)/,\ SRC_MOD += $(addprefix $(LWIP_DIR)/,\
apps/mdns/mdns.c \ apps/mdns/mdns.c \
core/def.c \ core/def.c \

View File

@ -0,0 +1,65 @@
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2021 Jim Mussared
* Copyright (c) 2021 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "py/runtime.h"
#include "py/mphal.h"
#include "extmod/machine_bitstream.h"
#if MICROPY_PY_MACHINE_BITSTREAM
// Timing is a 4-tuple of (high_time_0, low_time_0, high_time_1, low_time_1)
// suitable for driving WS2812.
#define MICROPY_MACHINE_BITSTREAM_TYPE_HIGH_LOW (0)
// machine.bitstream(pin, encoding, (timing), bytes)
STATIC mp_obj_t machine_bitstream_(size_t n_args, const mp_obj_t *args) {
mp_hal_pin_obj_t pin = mp_hal_get_pin_obj(args[0]);
int encoding = mp_obj_get_int(args[1]);
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(args[3], &bufinfo, MP_BUFFER_READ);
switch (encoding) {
case MICROPY_MACHINE_BITSTREAM_TYPE_HIGH_LOW: {
uint32_t timing_ns[4];
mp_obj_t *timing;
mp_obj_get_array_fixed_n(args[2], 4, &timing);
for (size_t i = 0; i < 4; ++i) {
timing_ns[i] = mp_obj_get_int(timing[i]);
}
machine_bitstream_high_low(pin, timing_ns, bufinfo.buf, bufinfo.len);
break;
}
default:
mp_raise_ValueError(MP_ERROR_TEXT("encoding"));
}
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_bitstream_obj, 4, 4, machine_bitstream_);
#endif // MICROPY_PY_MACHINE_BITSTREAM

View File

@ -0,0 +1,37 @@
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2021 Jim Mussared
* Copyright (c) 2021 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_EXTMOD_MACHINE_BITSTREAM_H
#define MICROPY_INCLUDED_EXTMOD_MACHINE_BITSTREAM_H
#include "py/obj.h"
#include "py/mphal.h"
void machine_bitstream_high_low(mp_hal_pin_obj_t pin, uint32_t *timing_ns, const uint8_t *buf, size_t len);
MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(machine_bitstream_obj);
#endif // MICROPY_INCLUDED_EXTMOD_MACHINE_BITSTREAM_H

View File

@ -717,15 +717,17 @@ STATIC mp_obj_t bluetooth_ble_gatts_read(mp_obj_t self_in, mp_obj_t value_handle
} }
STATIC MP_DEFINE_CONST_FUN_OBJ_2(bluetooth_ble_gatts_read_obj, bluetooth_ble_gatts_read); STATIC MP_DEFINE_CONST_FUN_OBJ_2(bluetooth_ble_gatts_read_obj, bluetooth_ble_gatts_read);
STATIC mp_obj_t bluetooth_ble_gatts_write(mp_obj_t self_in, mp_obj_t value_handle_in, mp_obj_t data) { STATIC mp_obj_t bluetooth_ble_gatts_write(size_t n_args, const mp_obj_t *args) {
(void)self_in;
mp_buffer_info_t bufinfo = {0}; mp_buffer_info_t bufinfo = {0};
mp_get_buffer_raise(data, &bufinfo, MP_BUFFER_READ); mp_get_buffer_raise(args[2], &bufinfo, MP_BUFFER_READ);
int err = mp_bluetooth_gatts_write(mp_obj_get_int(value_handle_in), bufinfo.buf, bufinfo.len); bool send_update = false;
bluetooth_handle_errno(err); if (n_args > 3) {
send_update = mp_obj_is_true(args[3]);
}
bluetooth_handle_errno(mp_bluetooth_gatts_write(mp_obj_get_int(args[1]), bufinfo.buf, bufinfo.len, send_update));
return MP_OBJ_NEW_SMALL_INT(bufinfo.len); return MP_OBJ_NEW_SMALL_INT(bufinfo.len);
} }
STATIC MP_DEFINE_CONST_FUN_OBJ_3(bluetooth_ble_gatts_write_obj, bluetooth_ble_gatts_write); STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bluetooth_ble_gatts_write_obj, 3, 4, bluetooth_ble_gatts_write);
STATIC mp_obj_t bluetooth_ble_gatts_notify(size_t n_args, const mp_obj_t *args) { STATIC mp_obj_t bluetooth_ble_gatts_notify(size_t n_args, const mp_obj_t *args) {
mp_int_t conn_handle = mp_obj_get_int(args[1]); mp_int_t conn_handle = mp_obj_get_int(args[1]);
@ -842,7 +844,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(bluetooth_ble_gattc_exchange_mtu_obj, bluetooth
STATIC mp_obj_t bluetooth_ble_l2cap_listen(mp_obj_t self_in, mp_obj_t psm_in, mp_obj_t mtu_in) { STATIC mp_obj_t bluetooth_ble_l2cap_listen(mp_obj_t self_in, mp_obj_t psm_in, mp_obj_t mtu_in) {
(void)self_in; (void)self_in;
mp_int_t psm = mp_obj_get_int(psm_in); mp_int_t psm = mp_obj_get_int(psm_in);
mp_int_t mtu = mp_obj_get_int(mtu_in); mp_int_t mtu = MAX(32, MIN(UINT16_MAX, mp_obj_get_int(mtu_in)));
return bluetooth_handle_errno(mp_bluetooth_l2cap_listen(psm, mtu)); return bluetooth_handle_errno(mp_bluetooth_l2cap_listen(psm, mtu));
} }
STATIC MP_DEFINE_CONST_FUN_OBJ_3(bluetooth_ble_l2cap_listen_obj, bluetooth_ble_l2cap_listen); STATIC MP_DEFINE_CONST_FUN_OBJ_3(bluetooth_ble_l2cap_listen_obj, bluetooth_ble_l2cap_listen);
@ -850,7 +852,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_3(bluetooth_ble_l2cap_listen_obj, bluetooth_ble_l
STATIC mp_obj_t bluetooth_ble_l2cap_connect(size_t n_args, const mp_obj_t *args) { STATIC mp_obj_t bluetooth_ble_l2cap_connect(size_t n_args, const mp_obj_t *args) {
mp_int_t conn_handle = mp_obj_get_int(args[1]); mp_int_t conn_handle = mp_obj_get_int(args[1]);
mp_int_t psm = mp_obj_get_int(args[2]); mp_int_t psm = mp_obj_get_int(args[2]);
mp_int_t mtu = mp_obj_get_int(args[3]); mp_int_t mtu = MAX(32, MIN(UINT16_MAX, mp_obj_get_int(args[3])));
return bluetooth_handle_errno(mp_bluetooth_l2cap_connect(conn_handle, psm, mtu)); return bluetooth_handle_errno(mp_bluetooth_l2cap_connect(conn_handle, psm, mtu));
} }
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bluetooth_ble_l2cap_connect_obj, 4, 4, bluetooth_ble_l2cap_connect); STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bluetooth_ble_l2cap_connect_obj, 4, 4, bluetooth_ble_l2cap_connect);

View File

@ -334,8 +334,8 @@ int mp_bluetooth_gatts_register_service_end(void);
// Read the value from the local gatts db (likely this has been written by a central). // Read the value from the local gatts db (likely this has been written by a central).
int mp_bluetooth_gatts_read(uint16_t value_handle, uint8_t **value, size_t *value_len); int mp_bluetooth_gatts_read(uint16_t value_handle, uint8_t **value, size_t *value_len);
// Write a value to the local gatts db (ready to be queried by a central). // Write a value to the local gatts db (ready to be queried by a central). Optionally send notifications/indications.
int mp_bluetooth_gatts_write(uint16_t value_handle, const uint8_t *value, size_t value_len); int mp_bluetooth_gatts_write(uint16_t value_handle, const uint8_t *value, size_t value_len, bool send_update);
// Notify the central that it should do a read. // Notify the central that it should do a read.
int mp_bluetooth_gatts_notify(uint16_t conn_handle, uint16_t value_handle); int mp_bluetooth_gatts_notify(uint16_t conn_handle, uint16_t value_handle);
// Notify the central, including a data payload. (Note: does not set the gatts db value). // Notify the central, including a data payload. (Note: does not set the gatts db value).

View File

@ -491,6 +491,10 @@ STATIC mp_obj_t framebuf_blit(size_t n_args, const mp_obj_t *args) {
if (n_args > 4) { if (n_args > 4) {
key = mp_obj_get_int(args[4]); key = mp_obj_get_int(args[4]);
} }
mp_obj_framebuf_t *palette = NULL;
if (n_args > 5 && args[5] != mp_const_none) {
palette = MP_OBJ_TO_PTR(mp_obj_cast_to_native_base(args[5], MP_OBJ_FROM_PTR(&mp_type_framebuf)));
}
if ( if (
(x >= self->width) || (x >= self->width) ||
@ -514,6 +518,9 @@ STATIC mp_obj_t framebuf_blit(size_t n_args, const mp_obj_t *args) {
int cx1 = x1; int cx1 = x1;
for (int cx0 = x0; cx0 < x0end; ++cx0) { for (int cx0 = x0; cx0 < x0end; ++cx0) {
uint32_t col = getpixel(source, cx1, y1); uint32_t col = getpixel(source, cx1, y1);
if (palette) {
col = getpixel(palette, col, 0);
}
if (col != (uint32_t)key) { if (col != (uint32_t)key) {
setpixel(self, cx0, y0, col); setpixel(self, cx0, y0, col);
} }
@ -523,7 +530,7 @@ STATIC mp_obj_t framebuf_blit(size_t n_args, const mp_obj_t *args) {
} }
return mp_const_none; return mp_const_none;
} }
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(framebuf_blit_obj, 4, 5, framebuf_blit); STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(framebuf_blit_obj, 4, 6, framebuf_blit);
STATIC mp_obj_t framebuf_scroll(mp_obj_t self_in, mp_obj_t xstep_in, mp_obj_t ystep_in) { STATIC mp_obj_t framebuf_scroll(mp_obj_t self_in, mp_obj_t xstep_in, mp_obj_t ystep_in) {
mp_obj_framebuf_t *self = MP_OBJ_TO_PTR(self_in); mp_obj_framebuf_t *self = MP_OBJ_TO_PTR(self_in);

View File

@ -35,7 +35,7 @@
#include "py/mperrno.h" #include "py/mperrno.h"
#include "py/mphal.h" #include "py/mphal.h"
#include "lib/netutils/netutils.h" #include "shared/netutils/netutils.h"
#include "lwip/init.h" #include "lwip/init.h"
#include "lwip/tcp.h" #include "lwip/tcp.h"
@ -1502,16 +1502,16 @@ STATIC mp_uint_t lwip_socket_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_
return 0; return 0;
} }
// Deregister callback (pcb.tcp is set to NULL below so must deregister now)
tcp_arg(socket->pcb.tcp, NULL);
tcp_err(socket->pcb.tcp, NULL);
tcp_recv(socket->pcb.tcp, NULL);
// Free any incoming buffers or connections that are stored // Free any incoming buffers or connections that are stored
lwip_socket_free_incoming(socket); lwip_socket_free_incoming(socket);
switch (socket->type) { switch (socket->type) {
case MOD_NETWORK_SOCK_STREAM: { case MOD_NETWORK_SOCK_STREAM: {
// Deregister callback (pcb.tcp is set to NULL below so must deregister now)
tcp_arg(socket->pcb.tcp, NULL);
tcp_err(socket->pcb.tcp, NULL);
tcp_recv(socket->pcb.tcp, NULL);
if (socket->pcb.tcp->state != LISTEN) { if (socket->pcb.tcp->state != LISTEN) {
// Schedule a callback to abort the connection if it's not cleanly closed after // Schedule a callback to abort the connection if it's not cleanly closed after
// the given timeout. The callback must be set before calling tcp_close since // the given timeout. The callback must be set before calling tcp_close since
@ -1525,10 +1525,12 @@ STATIC mp_uint_t lwip_socket_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_
break; break;
} }
case MOD_NETWORK_SOCK_DGRAM: case MOD_NETWORK_SOCK_DGRAM:
udp_recv(socket->pcb.udp, NULL, NULL);
udp_remove(socket->pcb.udp); udp_remove(socket->pcb.udp);
break; break;
#if MICROPY_PY_LWIP_SOCK_RAW #if MICROPY_PY_LWIP_SOCK_RAW
case MOD_NETWORK_SOCK_RAW: case MOD_NETWORK_SOCK_RAW:
raw_recv(socket->pcb.raw, NULL, NULL);
raw_remove(socket->pcb.raw); raw_remove(socket->pcb.raw);
break; break;
#endif #endif

View File

@ -218,7 +218,7 @@ STATIC mp_obj_t mod_binascii_b2a_base64(mp_obj_t data) {
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_binascii_b2a_base64_obj, mod_binascii_b2a_base64); STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_binascii_b2a_base64_obj, mod_binascii_b2a_base64);
#if MICROPY_PY_UBINASCII_CRC32 #if MICROPY_PY_UBINASCII_CRC32
#include "uzlib/tinf.h" #include "lib/uzlib/tinf.h"
STATIC mp_obj_t mod_binascii_crc32(size_t n_args, const mp_obj_t *args) { STATIC mp_obj_t mod_binascii_crc32(size_t n_args, const mp_obj_t *args) {
mp_buffer_info_t bufinfo; mp_buffer_info_t bufinfo;

View File

@ -40,7 +40,7 @@
#if MICROPY_SSL_MBEDTLS #if MICROPY_SSL_MBEDTLS
#include "mbedtls/sha256.h" #include "mbedtls/sha256.h"
#else #else
#include "crypto-algorithms/sha256.h" #include "lib/crypto-algorithms/sha256.h"
#endif #endif
#endif #endif
@ -115,7 +115,7 @@ STATIC mp_obj_t uhashlib_sha256_digest(mp_obj_t self_in) {
#else #else
#include "crypto-algorithms/sha256.c" #include "lib/crypto-algorithms/sha256.c"
STATIC mp_obj_t uhashlib_sha256_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { STATIC mp_obj_t uhashlib_sha256_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
mp_arg_check_num(n_args, n_kw, 0, 1, false); mp_arg_check_num(n_args, n_kw, 0, 1, false);

View File

@ -34,6 +34,62 @@
#if MICROPY_PY_UJSON #if MICROPY_PY_UJSON
#if MICROPY_PY_UJSON_SEPARATORS
enum {
DUMP_MODE_TO_STRING = 1,
DUMP_MODE_TO_STREAM = 2,
};
STATIC mp_obj_t mod_ujson_dump_helper(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args, unsigned int mode) {
enum { ARG_separators };
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_separators, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
};
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
mp_arg_parse_all(n_args - mode, pos_args + mode, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
mp_print_ext_t print_ext;
if (args[ARG_separators].u_obj == mp_const_none) {
print_ext.item_separator = ", ";
print_ext.key_separator = ": ";
} else {
mp_obj_t *items;
mp_obj_get_array_fixed_n(args[ARG_separators].u_obj, 2, &items);
print_ext.item_separator = mp_obj_str_get_str(items[0]);
print_ext.key_separator = mp_obj_str_get_str(items[1]);
}
if (mode == DUMP_MODE_TO_STRING) {
// dumps(obj)
vstr_t vstr;
vstr_init_print(&vstr, 8, &print_ext.base);
mp_obj_print_helper(&print_ext.base, pos_args[0], PRINT_JSON);
return mp_obj_new_str_from_vstr(&mp_type_str, &vstr);
} else {
// dump(obj, stream)
print_ext.base.data = MP_OBJ_TO_PTR(pos_args[1]);
print_ext.base.print_strn = mp_stream_write_adaptor;
mp_get_stream_raise(pos_args[1], MP_STREAM_OP_WRITE);
mp_obj_print_helper(&print_ext.base, pos_args[0], PRINT_JSON);
return mp_const_none;
}
}
STATIC mp_obj_t mod_ujson_dump(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
return mod_ujson_dump_helper(n_args, pos_args, kw_args, DUMP_MODE_TO_STREAM);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(mod_ujson_dump_obj, 2, mod_ujson_dump);
STATIC mp_obj_t mod_ujson_dumps(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
return mod_ujson_dump_helper(n_args, pos_args, kw_args, DUMP_MODE_TO_STRING);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(mod_ujson_dumps_obj, 1, mod_ujson_dumps);
#else
STATIC mp_obj_t mod_ujson_dump(mp_obj_t obj, mp_obj_t stream) { STATIC mp_obj_t mod_ujson_dump(mp_obj_t obj, mp_obj_t stream) {
mp_get_stream_raise(stream, MP_STREAM_OP_WRITE); mp_get_stream_raise(stream, MP_STREAM_OP_WRITE);
mp_print_t print = {MP_OBJ_TO_PTR(stream), mp_stream_write_adaptor}; mp_print_t print = {MP_OBJ_TO_PTR(stream), mp_stream_write_adaptor};
@ -51,6 +107,8 @@ STATIC mp_obj_t mod_ujson_dumps(mp_obj_t obj) {
} }
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_ujson_dumps_obj, mod_ujson_dumps); STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_ujson_dumps_obj, mod_ujson_dumps);
#endif
// The function below implements a simple non-recursive JSON parser. // The function below implements a simple non-recursive JSON parser.
// //
// The JSON specification is at http://www.ietf.org/rfc/rfc4627.txt // The JSON specification is at http://www.ietf.org/rfc/rfc4627.txt

View File

@ -37,7 +37,7 @@
#define re1_5_stack_chk() MP_STACK_CHECK() #define re1_5_stack_chk() MP_STACK_CHECK()
#include "re1.5/re1.5.h" #include "lib/re1.5/re1.5.h"
#define FLAG_DEBUG 0x1000 #define FLAG_DEBUG 0x1000
@ -68,7 +68,7 @@ STATIC mp_obj_t match_group(mp_obj_t self_in, mp_obj_t no_in) {
mp_obj_match_t *self = MP_OBJ_TO_PTR(self_in); mp_obj_match_t *self = MP_OBJ_TO_PTR(self_in);
mp_int_t no = mp_obj_get_int(no_in); mp_int_t no = mp_obj_get_int(no_in);
if (no < 0 || no >= self->num_matches) { if (no < 0 || no >= self->num_matches) {
nlr_raise(mp_obj_new_exception_arg1(&mp_type_IndexError, no_in)); mp_raise_type_arg(&mp_type_IndexError, no_in);
} }
const char *start = self->caps[no * 2]; const char *start = self->caps[no * 2];
@ -107,7 +107,7 @@ STATIC void match_span_helper(size_t n_args, const mp_obj_t *args, mp_obj_t span
if (n_args == 2) { if (n_args == 2) {
no = mp_obj_get_int(args[1]); no = mp_obj_get_int(args[1]);
if (no < 0 || no >= self->num_matches) { if (no < 0 || no >= self->num_matches) {
nlr_raise(mp_obj_new_exception_arg1(&mp_type_IndexError, args[1])); mp_raise_type_arg(&mp_type_IndexError, args[1]);
} }
} }
@ -334,7 +334,7 @@ STATIC mp_obj_t re_sub_helper(size_t n_args, const mp_obj_t *args) {
} }
if (match_no >= (unsigned int)match->num_matches) { if (match_no >= (unsigned int)match->num_matches) {
nlr_raise(mp_obj_new_exception_arg1(&mp_type_IndexError, MP_OBJ_NEW_SMALL_INT(match_no))); mp_raise_type_arg(&mp_type_IndexError, MP_OBJ_NEW_SMALL_INT(match_no));
} }
const char *start_match = match->caps[match_no * 2]; const char *start_match = match->caps[match_no * 2];
@ -454,11 +454,11 @@ const mp_obj_module_t mp_module_ure = {
// only if module is enabled by config setting. // only if module is enabled by config setting.
#define re1_5_fatal(x) assert(!x) #define re1_5_fatal(x) assert(!x)
#include "re1.5/compilecode.c" #include "lib/re1.5/compilecode.c"
#if MICROPY_PY_URE_DEBUG #if MICROPY_PY_URE_DEBUG
#include "re1.5/dumpcode.c" #include "lib/re1.5/dumpcode.c"
#endif #endif
#include "re1.5/recursiveloop.c" #include "lib/re1.5/recursiveloop.c"
#include "re1.5/charclass.c" #include "lib/re1.5/charclass.c"
#endif // MICROPY_PY_URE #endif // MICROPY_PY_URE

View File

@ -107,6 +107,7 @@ STATIC mp_uint_t poll_map_poll(mp_map_t *poll_map, size_t *rwx_num) {
return n_ready; return n_ready;
} }
#if MICROPY_PY_USELECT_SELECT
// select(rlist, wlist, xlist[, timeout]) // select(rlist, wlist, xlist[, timeout])
STATIC mp_obj_t select_select(size_t n_args, const mp_obj_t *args) { STATIC mp_obj_t select_select(size_t n_args, const mp_obj_t *args) {
// get array data from tuple/list arguments // get array data from tuple/list arguments
@ -173,6 +174,7 @@ STATIC mp_obj_t select_select(size_t n_args, const mp_obj_t *args) {
} }
} }
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_select_select_obj, 3, 4, select_select); MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_select_select_obj, 3, 4, select_select);
#endif // MICROPY_PY_USELECT_SELECT
typedef struct _mp_obj_poll_t { typedef struct _mp_obj_poll_t {
mp_obj_base_t base; mp_obj_base_t base;
@ -355,7 +357,9 @@ MP_DEFINE_CONST_FUN_OBJ_0(mp_select_poll_obj, select_poll);
STATIC const mp_rom_map_elem_t mp_module_select_globals_table[] = { STATIC const mp_rom_map_elem_t mp_module_select_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_uselect) }, { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_uselect) },
#if MICROPY_PY_USELECT_SELECT
{ MP_ROM_QSTR(MP_QSTR_select), MP_ROM_PTR(&mp_select_select_obj) }, { MP_ROM_QSTR(MP_QSTR_select), MP_ROM_PTR(&mp_select_select_obj) },
#endif
{ MP_ROM_QSTR(MP_QSTR_poll), MP_ROM_PTR(&mp_select_poll_obj) }, { MP_ROM_QSTR(MP_QSTR_poll), MP_ROM_PTR(&mp_select_poll_obj) },
{ MP_ROM_QSTR(MP_QSTR_POLLIN), MP_ROM_INT(MP_STREAM_POLL_RD) }, { MP_ROM_QSTR(MP_QSTR_POLLIN), MP_ROM_INT(MP_STREAM_POLL_RD) },
{ MP_ROM_QSTR(MP_QSTR_POLLOUT), MP_ROM_INT(MP_STREAM_POLL_WR) }, { MP_ROM_QSTR(MP_QSTR_POLLOUT), MP_ROM_INT(MP_STREAM_POLL_WR) },

View File

@ -33,7 +33,7 @@
#if MICROPY_PY_UZLIB #if MICROPY_PY_UZLIB
#include "uzlib/tinf.h" #include "lib/uzlib/tinf.h"
#if 0 // print debugging info #if 0 // print debugging info
#define DEBUG_printf DEBUG_printf #define DEBUG_printf DEBUG_printf
@ -201,7 +201,7 @@ STATIC mp_obj_t mod_uzlib_decompress(size_t n_args, const mp_obj_t *args) {
return res; return res;
error: error:
nlr_raise(mp_obj_new_exception_arg1(&mp_type_ValueError, MP_OBJ_NEW_SMALL_INT(st))); mp_raise_type_arg(&mp_type_ValueError, MP_OBJ_NEW_SMALL_INT(st));
} }
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_uzlib_decompress_obj, 1, 3, mod_uzlib_decompress); STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_uzlib_decompress_obj, 1, 3, mod_uzlib_decompress);
@ -223,10 +223,10 @@ const mp_obj_module_t mp_module_uzlib = {
// Source files #include'd here to make sure they're compiled in // Source files #include'd here to make sure they're compiled in
// only if module is enabled by config setting. // only if module is enabled by config setting.
#include "uzlib/tinflate.c" #include "lib/uzlib/tinflate.c"
#include "uzlib/tinfzlib.c" #include "lib/uzlib/tinfzlib.c"
#include "uzlib/tinfgzip.c" #include "lib/uzlib/tinfgzip.c"
#include "uzlib/adler32.c" #include "lib/uzlib/adler32.c"
#include "uzlib/crc32.c" #include "lib/uzlib/crc32.c"
#endif // MICROPY_PY_UZLIB #endif // MICROPY_PY_UZLIB

Some files were not shown because too many files have changed in this diff Show More