Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
  • 9Rmain
  • anon/gpndemo
  • anon/update-sim
  • anon/webflasher
  • audio_input
  • audio_io
  • bl00mbox
  • bl00mbox_old
  • captouch-threshold
  • ch3/bl00mbox_docs
  • ci-1690580595
  • compressor
  • dev_p4
  • dev_p4-iggy
  • dev_p4-iggy-rebased
  • dos
  • dos-main-patch-50543
  • events
  • fm_fix
  • fm_fix2
  • fpletz/flake
  • history-rewrite
  • icon-flower
  • iggy/stemming
  • iggy/stemming_merge
  • json-error
  • main
  • main+schneider
  • media-buf
  • micropython_api
  • moon2_applications
  • moon2_demo_temp
  • moon2_gay_drums
  • passthrough
  • phhw
  • pippin/display-python-errors-on-display
  • pippin/make_empty_drawlists_skip_render_and_blit
  • pippin/media_framework
  • pippin/uhm_flash_access_bust
  • pressable_bugfix
  • q3k/doom-poc
  • rahix/big-flow3r
  • rahix/flow3rseeds
  • raw_captouch_new
  • raw_captouch_old
  • release/1.0.0
  • release/1.1.0
  • release/1.1.1
  • rev4_micropython
  • schneider/application-remove-name
  • schneider/bhi581
  • schneider/factory_test
  • schneider/recovery
  • scope
  • scope_hack
  • sdkconfig-spiram-tinyusb
  • sec/auto-nick
  • sec/blinky
  • simtest
  • slewtest
  • t
  • test
  • test2
  • uctx-wip
  • view-think
  • vm-pending
  • vsync
  • wave
  • wip-docs
  • wip-tinyusb
  • v1.0.0
  • v1.0.0+rc1
  • v1.0.0+rc2
  • v1.0.0+rc3
  • v1.0.0+rc4
  • v1.0.0+rc5
  • v1.0.0+rc6
  • v1.1.0
  • v1.1.0+rc1
  • v1.1.1
  • v1.2.0
  • v1.2.0+rc1
  • v1.3.0
83 results

Target

Select target project
  • flow3r/flow3r-firmware
  • Vespasian/flow3r-firmware
  • alxndr42/flow3r-firmware
  • pl/flow3r-firmware
  • Kari/flow3r-firmware
  • raimue/flow3r-firmware
  • grandchild/flow3r-firmware
  • mu5tach3/flow3r-firmware
  • Nervengift/flow3r-firmware
  • arachnist/flow3r-firmware
  • TheNewCivilian/flow3r-firmware
  • alibi/flow3r-firmware
  • manuel_v/flow3r-firmware
  • xeniter/flow3r-firmware
  • maxbachmann/flow3r-firmware
  • yGifoom/flow3r-firmware
  • istobic/flow3r-firmware
  • EiNSTeiN_/flow3r-firmware
  • gnudalf/flow3r-firmware
  • 999eagle/flow3r-firmware
  • toerb/flow3r-firmware
  • pandark/flow3r-firmware
  • teal/flow3r-firmware
  • x42/flow3r-firmware
  • alufers/flow3r-firmware
  • dos/flow3r-firmware
  • yrlf/flow3r-firmware
  • LuKaRo/flow3r-firmware
  • ThomasElRubio/flow3r-firmware
  • ai/flow3r-firmware
  • T_X/flow3r-firmware
  • highTower/flow3r-firmware
  • beanieboi/flow3r-firmware
  • Woazboat/flow3r-firmware
  • gooniesbro/flow3r-firmware
  • marvino/flow3r-firmware
  • kressnerd/flow3r-firmware
  • quazgar/flow3r-firmware
  • aoid/flow3r-firmware
  • jkj/flow3r-firmware
  • naomi/flow3r-firmware
41 results
Select Git revision
  • 89-apps-should-be-able-to-specify-if-they-want-wifi-to-be-disabled-when-entering-them
  • 9Rmain
  • allow-reloading-sunmenu
  • always-have-a-wifi-instance
  • anon/gpndemo
  • anon/update-sim
  • anon/webflasher
  • app_text_viewer
  • audio_input
  • audio_io
  • blm_dev_chan
  • ch3/bl00mbox_docs
  • ci-1690580595
  • dev_p4
  • dev_p4-iggy
  • dev_p4-iggy-rebased
  • dx/dldldld
  • dx/fb-save-restore
  • dx/hint-hint
  • dx/jacksense-headset-mic-only
  • events
  • fil3s-limit-filesize
  • fil3s-media
  • fpletz/flake
  • gr33nhouse-improvements
  • history-rewrite
  • icon-flower
  • iggy/stemming
  • iggy/stemming_merge
  • led_fix_fix
  • main
  • main+schneider
  • media_has_video_has_audio
  • micropython_api
  • mixer2
  • moon2_demo_temp
  • moon2_migrate_apps
  • more-accurate-battery
  • pippin/ctx_sprite_sheet_support
  • pippin/display-python-errors-on-display
  • pippin/make_empty_drawlists_skip_render_and_blit
  • pippin/more-accurate-battery
  • pippin/tcp_redirect_hack
  • pippin/tune_ctx_config_update_from_upstream
  • pippin/uhm_flash_access_bust
  • pressable_bugfix
  • py_only_update_fps_overlay_when_changing
  • q3k/doom-poc
  • q3k/render-to-texture
  • rahix/flow3rseeds
  • raw_captouch_new
  • raw_captouch_old
  • release/1.0.0
  • release/1.1.0
  • release/1.1.1
  • release/1.2.0
  • release/1.3.0
  • release/1.4.0
  • restore_blit
  • return_of_melodic_demo
  • rev4_micropython
  • schneider/application-remove-name
  • schneider/bhi581
  • schneider/factory_test
  • schneider/recovery
  • scope_hack
  • sdkconfig-spiram-tinyusb
  • sec/auto-nick
  • sec/blinky
  • sector_size_512
  • shoegaze-fps
  • smaller_gradient_lut
  • store_delta_ms_and_ins_as_class_members
  • task_cleanup
  • uctx-wip
  • w1f1-in-sim
  • widgets_draw
  • wifi-json-error-handling
  • wip-docs
  • wip-tinyusb
  • v1.0.0
  • v1.0.0+rc1
  • v1.0.0+rc2
  • v1.0.0+rc3
  • v1.0.0+rc4
  • v1.0.0+rc5
  • v1.0.0+rc6
  • v1.1.0
  • v1.1.0+rc1
  • v1.1.1
  • v1.2.0
  • v1.2.0+rc1
  • v1.3.0
  • v1.4.0
94 results
Show changes
Showing
with 2657 additions and 0 deletions
:mod:`hashlib` -- hashing algorithms
====================================
.. module:: hashlib
:synopsis: hashing algorithms
|see_cpython_module| :mod:`python:hashlib`.
This module implements binary data hashing algorithms. The exact inventory
of available algorithms depends on a board. Among the algorithms which may
be implemented:
* SHA256 - The current generation, modern hashing algorithm (of SHA2 series).
It is suitable for cryptographically-secure purposes. Included in the
MicroPython core and any board is recommended to provide this, unless
it has particular code size constraints.
* SHA1 - A previous generation algorithm. Not recommended for new usages,
but SHA1 is a part of number of Internet standards and existing
applications, so boards targeting network connectivity and
interoperability will try to provide this.
* MD5 - A legacy algorithm, not considered cryptographically secure. Only
selected boards, targeting interoperability with legacy applications,
will offer this.
Constructors
------------
.. class:: hashlib.sha256([data])
Create an SHA256 hasher object and optionally feed ``data`` into it.
.. class:: hashlib.sha1([data])
Create an SHA1 hasher object and optionally feed ``data`` into it.
.. class:: hashlib.md5([data])
Create an MD5 hasher object and optionally feed ``data`` into it.
Methods
-------
.. method:: hash.update(data)
Feed more binary data into hash.
.. method:: hash.digest()
Return hash for all data passed through hash, as a bytes object. After this
method is called, more data cannot be fed into the hash any longer.
.. method:: hash.hexdigest()
This method is NOT implemented. Use ``binascii.hexlify(hash.digest())``
to achieve a similar effect.
:mod:`heapq` -- heap queue algorithm
====================================
.. module:: heapq
:synopsis: heap queue algorithm
|see_cpython_module| :mod:`python:heapq`.
This module implements the
`min heap queue algorithm <https://en.wikipedia.org/wiki/Heap_%28data_structure%29>`_.
A heap queue is essentially a list that has its elements stored in such a way
that the first item of the list is always the smallest.
Functions
---------
.. function:: heappush(heap, item)
Push the ``item`` onto the ``heap``.
.. function:: heappop(heap)
Pop the first item from the ``heap``, and return it. Raise ``IndexError`` if
``heap`` is empty.
The returned item will be the smallest item in the ``heap``.
.. function:: heapify(x)
Convert the list ``x`` into a heap. This is an in-place operation.
.. _micropython_lib:
MicroPython libraries
=====================
.. warning::
Important summary of this section
* MicroPython provides built-in modules that mirror the functionality of the
Python standard library (e.g. :mod:`os`, :mod:`time`), as well as
MicroPython-specific modules (e.g. :mod:`bluetooth`, :mod:`machine`).
* Most standard library modules implement a subset of the functionality of
the equivalent Python module, and in a few cases provide some
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
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.
With that in mind, please 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
can be imported by entering the following at the :term:`REPL`::
help('modules')
Beyond the built-in libraries described in this documentation, many more
modules from the Python standard library, as well as further MicroPython
extensions to it, can be found in :term:`micropython-lib`.
Python standard libraries and micro-libraries
---------------------------------------------
The following standard Python libraries have been "micro-ified" to fit in with
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
library.
.. toctree::
:maxdepth: 1
array.rst
binascii.rst
builtins.rst
cmath.rst
collections.rst
errno.rst
gc.rst
hashlib.rst
heapq.rst
io.rst
json.rst
math.rst
os.rst
random.rst
re.rst
select.rst
socket.rst
ssl.rst
struct.rst
sys.rst
time.rst
uasyncio.rst
zlib.rst
_thread.rst
MicroPython-specific libraries
------------------------------
Functionality specific to the MicroPython implementation is available in
the following libraries.
.. toctree::
:maxdepth: 1
bluetooth.rst
btree.rst
cryptolib.rst
framebuf.rst
machine.rst
micropython.rst
neopixel.rst
network.rst
uctypes.rst
The following libraries provide drivers for hardware components.
.. toctree::
:maxdepth: 1
wm8960.rst
Port-specific libraries
-----------------------
In some cases the following port/board-specific libraries have functions or
classes similar to those in the :mod:`machine` library. Where this occurs, the
entry in the port specific library exposes hardware functionality unique to
that platform.
To write portable code use functions and classes from the :mod:`machine` module.
To access platform-specific hardware use the appropriate library, e.g.
:mod:`pyb` in the case of the Pyboard.
Libraries specific to the pyboard
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following libraries are specific to the pyboard.
.. toctree::
:maxdepth: 2
pyb.rst
stm.rst
lcd160cr.rst
Libraries specific to the WiPy
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following libraries and classes are specific to the WiPy.
.. toctree::
:maxdepth: 2
wipy.rst
machine.ADCWiPy.rst
machine.TimerWiPy.rst
Libraries specific to the ESP8266 and ESP32
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following libraries are specific to the ESP8266 and ESP32.
.. toctree::
:maxdepth: 2
esp.rst
esp32.rst
Libraries specific to the RP2040
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following libraries are specific to the RP2040, as used in the Raspberry Pi Pico.
.. toctree::
:maxdepth: 2
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``.
:mod:`io` -- input/output streams
=================================
.. module:: io
:synopsis: input/output streams
|see_cpython_module| :mod:`python:io`.
This module contains additional types of `stream` (file-like) objects
and helper functions.
Conceptual hierarchy
--------------------
.. admonition:: Difference to CPython
:class: attention
Conceptual hierarchy of stream base classes is simplified in MicroPython,
as described in this section.
(Abstract) base stream classes, which serve as a foundation for behaviour
of all the concrete classes, adhere to few dichotomies (pair-wise
classifications) in CPython. In MicroPython, they are somewhat simplified
and made implicit to achieve higher efficiencies and save resources.
An important dichotomy in CPython is unbuffered vs buffered streams. In
MicroPython, all streams are currently unbuffered. This is because all
modern OSes, and even many RTOSes and filesystem drivers already perform
buffering on their side. Adding another layer of buffering is counter-
productive (an issue known as "bufferbloat") and takes precious memory.
Note that there still cases where buffering may be useful, so we may
introduce optional buffering support at a later time.
But in CPython, another important dichotomy is tied with "bufferedness" -
it's whether a stream may incur short read/writes or not. A short read
is when a user asks e.g. 10 bytes from a stream, but gets less, similarly
for writes. In CPython, unbuffered streams are automatically short
operation susceptible, while buffered are guarantee against them. The
no short read/writes is an important trait, as it allows to develop
more concise and efficient programs - something which is highly desirable
for MicroPython. So, while MicroPython doesn't support buffered streams,
it still provides for no-short-operations streams. Whether there will
be short operations or not depends on each particular class' needs, but
developers are strongly advised to favour no-short-operations behaviour
for the reasons stated above. For example, MicroPython sockets are
guaranteed to avoid short read/writes. Actually, at this time, there is
no example of a short-operations stream class in the core, and one would
be a port-specific class, where such a need is governed by hardware
peculiarities.
The no-short-operations behaviour gets tricky in case of non-blocking
streams, blocking vs non-blocking behaviour being another CPython dichotomy,
fully supported by MicroPython. Non-blocking streams never wait for
data either to arrive or be written - they read/write whatever possible,
or signal lack of data (or ability to write data). Clearly, this conflicts
with "no-short-operations" policy, and indeed, a case of non-blocking
buffered (and this no-short-ops) streams is convoluted in CPython - in
some places, such combination is prohibited, in some it's undefined or
just not documented, in some cases it raises verbose exceptions. The
matter is much simpler in MicroPython: non-blocking stream are important
for efficient asynchronous operations, so this property prevails on
the "no-short-ops" one. So, while blocking streams will avoid short
reads/writes whenever possible (the only case to get a short read is
if end of file is reached, or in case of error (but errors don't
return short data, but raise exceptions)), non-blocking streams may
produce short data to avoid blocking the operation.
The final dichotomy is binary vs text streams. MicroPython of course
supports these, but while in CPython text streams are inherently
buffered, they aren't in MicroPython. (Indeed, that's one of the cases
for which we may introduce buffering support.)
Note that for efficiency, MicroPython doesn't provide abstract base
classes corresponding to the hierarchy above, and it's not possible
to implement, or subclass, a stream class in pure Python.
Functions
---------
.. function:: open(name, mode='r', **kwargs)
Open a file. Builtin ``open()`` function is aliased to this function.
All ports (which provide access to file system) are required to support
*mode* parameter, but support for other arguments vary by port.
Classes
-------
.. class:: FileIO(...)
This is type of a file open in binary mode, e.g. using ``open(name, "rb")``.
You should not instantiate this class directly.
.. class:: TextIOWrapper(...)
This is type of a file open in text mode, e.g. using ``open(name, "rt")``.
You should not instantiate this class directly.
.. class:: StringIO([string])
.. class:: BytesIO([string])
In-memory file-like objects for input/output. `StringIO` is used for
text-mode I/O (similar to a normal file opened with "t" modifier).
`BytesIO` is used for binary-mode I/O (similar to a normal file
opened with "b" modifier). Initial contents of file-like objects
can be specified with *string* parameter (should be normal string
for `StringIO` or bytes object for `BytesIO`). All the usual file
methods like ``read()``, ``write()``, ``seek()``, ``flush()``,
``close()`` are available on these objects, and additionally, a
following method:
.. method:: getvalue()
Get the current contents of the underlying buffer which holds data.
.. class:: StringIO(alloc_size)
:noindex:
.. class:: BytesIO(alloc_size)
:noindex:
Create an empty `StringIO`/`BytesIO` object, preallocated to hold up
to *alloc_size* number of bytes. That means that writing that amount
of bytes won't lead to reallocation of the buffer, and thus won't hit
out-of-memory situation or lead to memory fragmentation. These constructors
are a MicroPython extension and are recommended for usage only in special
cases and in system-level libraries, not for end-user applications.
.. admonition:: Difference to CPython
:class: attention
These constructors are a MicroPython extension.
:mod:`json` -- JSON encoding and decoding
=========================================
.. module:: json
:synopsis: JSON encoding and decoding
|see_cpython_module| :mod:`python:json`.
This modules allows to convert between Python objects and the JSON
data format.
Functions
---------
.. function:: dump(obj, stream, separators=None)
Serialise *obj* to a JSON string, writing it to the given *stream*.
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.
The arguments have the same meaning as in `dump`.
.. function:: load(stream)
Parse the given *stream*, interpreting it as a JSON string and
deserialising the data to a Python object. The resulting object is
returned.
Parsing continues until end-of-file is encountered.
A :exc:`ValueError` is raised if the data in *stream* is not correctly formed.
.. function:: loads(str)
Parse the JSON *str* and return an object. Raises :exc:`ValueError` if the
string is not correctly formed.
:mod:`lcd160cr` --- control of LCD160CR display
===============================================
.. module:: lcd160cr
:synopsis: control of LCD160CR display
This module provides control of the MicroPython LCD160CR display.
.. image:: http://micropython.org/resources/LCD160CRv10-persp.jpg
:alt: LCD160CRv1.0 picture
:width: 640px
Further resources are available via the following links:
* `LCD160CRv1.0 reference manual <http://micropython.org/resources/LCD160CRv10-refmanual.pdf>`_ (100KiB PDF)
* `LCD160CRv1.0 schematics <http://micropython.org/resources/LCD160CRv10-schematics.pdf>`_ (1.6MiB PDF)
class LCD160CR
--------------
The LCD160CR class provides an interface to the display. Create an
instance of this class and use its methods to draw to the LCD and get
the status of the touch panel.
For example::
import lcd160cr
lcd = lcd160cr.LCD160CR('X')
lcd.set_orient(lcd160cr.PORTRAIT)
lcd.set_pos(0, 0)
lcd.set_text_color(lcd.rgb(255, 0, 0), lcd.rgb(0, 0, 0))
lcd.set_font(1)
lcd.write('Hello MicroPython!')
print('touch:', lcd.get_touch())
Constructors
------------
.. class:: LCD160CR(connect=None, *, pwr=None, i2c=None, spi=None, i2c_addr=98)
Construct an LCD160CR object. The parameters are:
- *connect* is a string specifying the physical connection of the LCD
display to the board; valid values are "X", "Y", "XY", "YX".
Use "X" when the display is connected to a pyboard in the X-skin
position, and "Y" when connected in the Y-skin position. "XY"
and "YX" are used when the display is connected to the right or
left side of the pyboard, respectively.
- *pwr* is a Pin object connected to the LCD's power/enabled pin.
- *i2c* is an I2C object connected to the LCD's I2C interface.
- *spi* is an SPI object connected to the LCD's SPI interface.
- *i2c_addr* is the I2C address of the display.
One must specify either a valid *connect* or all of *pwr*, *i2c* and *spi*.
If a valid *connect* is given then any of *pwr*, *i2c* or *spi* which are
not passed as parameters (i.e. they are ``None``) will be created based on the
value of *connect*. This allows to override the default interface to the
display if needed.
The default values are:
- "X" is for the X-skin and uses:
``pwr=Pin("X4")``, ``i2c=I2C("X")``, ``spi=SPI("X")``
- "Y" is for the Y-skin and uses:
``pwr=Pin("Y4")``, ``i2c=I2C("Y")``, ``spi=SPI("Y")``
- "XY" is for the right-side and uses:
``pwr=Pin("X4")``, ``i2c=I2C("Y")``, ``spi=SPI("X")``
- "YX" is for the left-side and uses:
``pwr=Pin("Y4")``, ``i2c=I2C("X")``, ``spi=SPI("Y")``
See `this image <http://micropython.org/resources/LCD160CRv10-positions.jpg>`_
for how the display can be connected to the pyboard.
Static methods
--------------
.. staticmethod:: LCD160CR.rgb(r, g, b)
Return a 16-bit integer representing the given rgb color values. The
16-bit value can be used to set the font color (see
:meth:`LCD160CR.set_text_color`) pen color (see :meth:`LCD160CR.set_pen`)
and draw individual pixels.
.. staticmethod:: LCD160CR.clip_line(data, w, h):
Clip the given line data. This is for internal use.
Instance members
----------------
The following instance members are publicly accessible.
.. data:: LCD160CR.w
.. data:: LCD160CR.h
The width and height of the display, respectively, in pixels. These
members are updated when calling :meth:`LCD160CR.set_orient` and should
be considered read-only.
Setup commands
--------------
.. method:: LCD160CR.set_power(on)
Turn the display on or off, depending on the given value of *on*: 0 or ``False``
will turn the display off, and 1 or ``True`` will turn it on.
.. method:: LCD160CR.set_orient(orient)
Set the orientation of the display. The *orient* parameter can be one
of `PORTRAIT`, `LANDSCAPE`, `PORTRAIT_UPSIDEDOWN`, `LANDSCAPE_UPSIDEDOWN`.
.. method:: LCD160CR.set_brightness(value)
Set the brightness of the display, between 0 and 31.
.. method:: LCD160CR.set_i2c_addr(addr)
Set the I2C address of the display. The *addr* value must have the
lower 2 bits cleared.
.. method:: LCD160CR.set_uart_baudrate(baudrate)
Set the baudrate of the UART interface.
.. method:: LCD160CR.set_startup_deco(value)
Set the start-up decoration of the display. The *value* parameter can be a
logical or of `STARTUP_DECO_NONE`, `STARTUP_DECO_MLOGO`, `STARTUP_DECO_INFO`.
.. method:: LCD160CR.save_to_flash()
Save the following parameters to flash so they persist on restart and power up:
initial decoration, orientation, brightness, UART baud rate, I2C address.
Pixel access methods
--------------------
The following methods manipulate individual pixels on the display.
.. method:: LCD160CR.set_pixel(x, y, c)
Set the specified pixel to the given color. The color should be a 16-bit
integer and can be created by :meth:`LCD160CR.rgb`.
.. method:: LCD160CR.get_pixel(x, y)
Get the 16-bit value of the specified pixel.
.. method:: LCD160CR.get_line(x, y, buf)
Low-level method to get a line of pixels into the given buffer.
To read *n* pixels *buf* should be *2*n+1* bytes in length. The first byte
is a dummy byte and should be ignored, and subsequent bytes represent the
pixels in the line starting at coordinate *(x, y)*.
.. method:: LCD160CR.screen_dump(buf, x=0, y=0, w=None, h=None)
Dump the contents of the screen to the given buffer. The parameters *x* and *y*
specify the starting coordinate, and *w* and *h* the size of the region. If *w*
or *h* are ``None`` then they will take on their maximum values, set by the size
of the screen minus the given *x* and *y* values. *buf* should be large enough
to hold ``2*w*h`` bytes. If it's smaller then only the initial horizontal lines
will be stored.
.. method:: LCD160CR.screen_load(buf)
Load the entire screen from the given buffer.
Drawing text
------------
To draw text one sets the position, color and font, and then uses
`LCD160CR.write` to draw the text.
.. method:: LCD160CR.set_pos(x, y)
Set the position for text output using :meth:`LCD160CR.write`. The position
is the upper-left corner of the text.
.. method:: LCD160CR.set_text_color(fg, bg)
Set the foreground and background color of the text.
.. method:: LCD160CR.set_font(font, scale=0, bold=0, trans=0, scroll=0)
Set the font for the text. Subsequent calls to `write` will use the newly
configured font. The parameters are:
- *font* is the font family to use, valid values are 0, 1, 2, 3.
- *scale* is a scaling value for each character pixel, where the pixels
are drawn as a square with side length equal to *scale + 1*. The value
can be between 0 and 63.
- *bold* controls the number of pixels to overdraw each character pixel,
making a bold effect. The lower 2 bits of *bold* are the number of
pixels to overdraw in the horizontal direction, and the next 2 bits are
for the vertical direction. For example, a *bold* value of 5 will
overdraw 1 pixel in both the horizontal and vertical directions.
- *trans* can be either 0 or 1 and if set to 1 the characters will be
drawn with a transparent background.
- *scroll* can be either 0 or 1 and if set to 1 the display will do a
soft scroll if the text moves to the next line.
.. method:: LCD160CR.write(s)
Write text to the display, using the current position, color and font.
As text is written the position is automatically incremented. The
display supports basic VT100 control codes such as newline and backspace.
Drawing primitive shapes
------------------------
Primitive drawing commands use a foreground and background color set by the
`set_pen` method.
.. method:: LCD160CR.set_pen(line, fill)
Set the line and fill color for primitive shapes.
.. method:: LCD160CR.erase()
Erase the entire display to the pen fill color.
.. method:: LCD160CR.dot(x, y)
Draw a single pixel at the given location using the pen line color.
.. method:: LCD160CR.rect(x, y, w, h)
.. method:: LCD160CR.rect_outline(x, y, w, h)
.. method:: LCD160CR.rect_interior(x, y, w, h)
Draw a rectangle at the given location and size using the pen line
color for the outline, and the pen fill color for the interior.
The `rect` method draws the outline and interior, while the other methods
just draw one or the other.
.. method:: LCD160CR.line(x1, y1, x2, y2)
Draw a line between the given coordinates using the pen line color.
.. method:: LCD160CR.dot_no_clip(x, y)
.. method:: LCD160CR.rect_no_clip(x, y, w, h)
.. method:: LCD160CR.rect_outline_no_clip(x, y, w, h)
.. method:: LCD160CR.rect_interior_no_clip(x, y, w, h)
.. method:: LCD160CR.line_no_clip(x1, y1, x2, y2)
These methods are as above but don't do any clipping on the input
coordinates. They are faster than the clipping versions and can be
used when you know that the coordinates are within the display.
.. method:: LCD160CR.poly_dot(data)
Draw a sequence of dots using the pen line color.
The *data* should be a buffer of bytes, with each successive pair of
bytes corresponding to coordinate pairs (x, y).
.. method:: LCD160CR.poly_line(data)
Similar to :meth:`LCD160CR.poly_dot` but draws lines between the dots.
Touch screen methods
--------------------
.. method:: LCD160CR.touch_config(calib=False, save=False, irq=None)
Configure the touch panel:
- If *calib* is ``True`` then the call will trigger a touch calibration of
the resistive touch sensor. This requires the user to touch various
parts of the screen.
- If *save* is ``True`` then the touch parameters will be saved to NVRAM
to persist across reset/power up.
- If *irq* is ``True`` then the display will be configured to pull the IRQ
line low when a touch force is detected. If *irq* is ``False`` then this
feature is disabled. If *irq* is ``None`` (the default value) then no
change is made to this setting.
.. method:: LCD160CR.is_touched()
Returns a boolean: ``True`` if there is currently a touch force on the screen,
``False`` otherwise.
.. method:: LCD160CR.get_touch()
Returns a 3-tuple of: *(active, x, y)*. If there is currently a touch force
on the screen then *active* is 1, otherwise it is 0. The *x* and *y* values
indicate the position of the current or most recent touch.
Advanced commands
-----------------
.. method:: LCD160CR.set_spi_win(x, y, w, h)
Set the window that SPI data is written to.
.. method:: LCD160CR.fast_spi(flush=True)
Ready the display to accept RGB pixel data on the SPI bus, resetting the location
of the first byte to go to the top-left corner of the window set by
:meth:`LCD160CR.set_spi_win`.
The method returns an SPI object which can be used to write the pixel data.
Pixels should be sent as 16-bit RGB values in the 5-6-5 format. The destination
counter will increase as data is sent, and data can be sent in arbitrary sized
chunks. Once the destination counter reaches the end of the window specified by
:meth:`LCD160CR.set_spi_win` it will wrap around to the top-left corner of that window.
.. method:: LCD160CR.show_framebuf(buf)
Show the given buffer on the display. *buf* should be an array of bytes containing
the 16-bit RGB values for the pixels, and they will be written to the area
specified by :meth:`LCD160CR.set_spi_win`, starting from the top-left corner.
The `framebuf <framebuf.html>`_ module can be used to construct frame buffers
and provides drawing primitives. Using a frame buffer will improve
performance of animations when compared to drawing directly to the screen.
.. method:: LCD160CR.set_scroll(on)
Turn scrolling on or off. This controls globally whether any window regions will
scroll.
.. method:: LCD160CR.set_scroll_win(win, x=-1, y=0, w=0, h=0, vec=0, pat=0, fill=0x07e0, color=0)
Configure a window region for scrolling:
- *win* is the window id to configure. There are 0..7 standard windows for
general purpose use. Window 8 is the text scroll window (the ticker).
- *x*, *y*, *w*, *h* specify the location of the window in the display.
- *vec* specifies the direction and speed of scroll: it is a 16-bit value
of the form ``0bF.ddSSSSSSSSSSSS``. *dd* is 0, 1, 2, 3 for +x, +y, -x,
-y scrolling. *F* sets the speed format, with 0 meaning that the window
is shifted *S % 256* pixel every frame, and 1 meaning that the window
is shifted 1 pixel every *S* frames.
- *pat* is a 16-bit pattern mask for the background.
- *fill* is the fill color.
- *color* is the extra color, either of the text or pattern foreground.
.. method:: LCD160CR.set_scroll_win_param(win, param, value)
Set a single parameter of a scrolling window region:
- *win* is the window id, 0..8.
- *param* is the parameter number to configure, 0..7, and corresponds
to the parameters in the `set_scroll_win` method.
- *value* is the value to set.
.. method:: LCD160CR.set_scroll_buf(s)
Set the string for scrolling in window 8. The parameter *s* must be a string
with length 32 or less.
.. method:: LCD160CR.jpeg(buf)
Display a JPEG. *buf* should contain the entire JPEG data. JPEG data should
not include EXIF information. The following encodings are supported: Baseline
DCT, Huffman coding, 8 bits per sample, 3 color components, YCbCr4:2:2.
The origin of the JPEG is set by :meth:`LCD160CR.set_pos`.
.. method:: LCD160CR.jpeg_start(total_len)
.. method:: LCD160CR.jpeg_data(buf)
Display a JPEG with the data split across multiple buffers. There must be
a single call to `jpeg_start` to begin with, specifying the total number of
bytes in the JPEG. Then this number of bytes must be transferred to the
display using one or more calls to the `jpeg_data` command.
.. method:: LCD160CR.feed_wdt()
The first call to this method will start the display's internal watchdog
timer. Subsequent calls will feed the watchdog. The timeout is roughly 30
seconds.
.. method:: LCD160CR.reset()
Reset the display.
Constants
---------
.. data:: lcd160cr.PORTRAIT
lcd160cr.LANDSCAPE
lcd160cr.PORTRAIT_UPSIDEDOWN
lcd160cr.LANDSCAPE_UPSIDEDOWN
Orientations of the display, used by :meth:`LCD160CR.set_orient`.
.. data:: lcd160cr.STARTUP_DECO_NONE
lcd160cr.STARTUP_DECO_MLOGO
lcd160cr.STARTUP_DECO_INFO
Types of start-up decoration, can be OR'ed together, used by
:meth:`LCD160CR.set_startup_deco`.
.. currentmodule:: machine
.. _machine.ADC:
class ADC -- analog to digital conversion
=========================================
The ADC class provides an interface to analog-to-digital convertors, and
represents a single endpoint that can sample a continuous voltage and
convert it to a discretised value.
For extra control over ADC sampling see :ref:`machine.ADCBlock <machine.ADCBlock>`.
Example usage::
from machine import ADC
adc = ADC(pin) # create an ADC object acting on a pin
val = adc.read_u16() # read a raw analog value in the range 0-65535
val = adc.read_uv() # read an analog value in microvolts
Constructors
------------
.. class:: ADC(id, *, sample_ns, atten)
Access the ADC associated with a source identified by *id*. This
*id* may be an integer (usually specifying a channel number), a
:ref:`Pin <machine.Pin>` object, or other value supported by the
underlying machine.
If additional keyword-arguments are given then they will configure
various aspects of the ADC. If not given, these settings will take
previous or default values. The settings are:
- *sample_ns* is the sampling time in nanoseconds.
- *atten* specifies the input attenuation.
Methods
-------
.. method:: ADC.init(*, sample_ns, atten)
Apply the given settings to the ADC. Only those arguments that are
specified will be changed. See the ADC constructor above for what the
arguments are.
.. method:: ADC.block()
Return the :ref:`ADCBlock <machine.ADCBlock>` instance associated with
this ADC object.
This method only exists if the port supports the
:ref:`ADCBlock <machine.ADCBlock>` class.
.. method:: ADC.read_u16()
Take an analog reading and return an integer in the range 0-65535.
The return value represents the raw reading taken by the ADC, scaled
such that the minimum value is 0 and the maximum value is 65535.
.. method:: ADC.read_uv()
Take an analog reading and return an integer value with units of
microvolts. It is up to the particular port whether or not this value
is calibrated, and how calibration is done.
.. currentmodule:: machine
.. _machine.ADCBlock:
class ADCBlock -- control ADC peripherals
=========================================
The ADCBlock class provides access to an ADC peripheral which has a
number of channels that can be used to sample analog values. It allows
finer control over configuration of :ref:`machine.ADC <machine.ADC>`
objects, which do the actual sampling.
This class is not always available.
Example usage::
from machine import ADCBlock
block = ADCBlock(id, bits=12) # create an ADCBlock with 12-bit resolution
adc = block.connect(4, pin) # connect channel 4 to the given pin
val = adc.read_uv() # read an analog value
Constructors
------------
.. class:: ADCBlock(id, *, bits)
Access the ADC peripheral identified by *id*, which may be an integer
or string.
The *bits* argument, if given, sets the resolution in bits of the
conversion process. If not specified then the previous or default
resolution is used.
Methods
-------
.. method:: ADCBlock.init(*, bits)
Configure the ADC peripheral. *bits* will set the resolution of the
conversion process.
.. method:: ADCBlock.connect(channel)
ADCBlock.connect(source)
ADCBlock.connect(channel, source)
Connect up a channel on the ADC peripheral so it is ready for sampling,
and return an :ref:`ADC <machine.ADC>` object that represents that connection.
The *channel* argument must be an integer, and *source* must be an object
(for example a :ref:`Pin <machine.Pin>`) which can be connected up for sampling.
If only *channel* is given then it is configured for sampling.
If only *source* is given then that object is connected to a default
channel ready for sampling.
If both *channel* and *source* are given then they are connected together
and made ready for sampling.
.. currentmodule:: machine
.. _machine.ADCWiPy:
class ADCWiPy -- analog to digital conversion
=============================================
.. note::
This class is a non-standard ADC implementation for the WiPy.
It is available simply as ``machine.ADC`` on the WiPy but is named in the
documentation below as ``machine.ADCWiPy`` to distinguish it from the
more general :ref:`machine.ADC <machine.ADC>` class.
Usage::
import machine
adc = machine.ADC() # create an ADC object
apin = adc.channel(pin='GP3') # create an analog pin on GP3
val = apin() # read an analog value
Constructors
------------
.. class:: ADCWiPy(id=0, *, bits=12)
Create an ADC object associated with the given pin.
This allows you to then read analog values on that pin.
For more info check the `pinout and alternate functions
table. <https://raw.githubusercontent.com/wipy/wipy/master/docs/PinOUT.png>`_
.. warning::
ADC pin input range is 0-1.4V (being 1.8V the absolute maximum that it
can withstand). When GP2, GP3, GP4 or GP5 are remapped to the
ADC block, 1.8 V is the maximum. If these pins are used in digital mode,
then the maximum allowed input is 3.6V.
Methods
-------
.. method:: ADCWiPy.channel(id, *, pin)
Create an analog pin. If only channel ID is given, the correct pin will
be selected. Alternatively, only the pin can be passed and the correct
channel will be selected. Examples::
# all of these are equivalent and enable ADC channel 1 on GP3
apin = adc.channel(1)
apin = adc.channel(pin='GP3')
apin = adc.channel(id=1, pin='GP3')
.. method:: ADCWiPy.init()
Enable the ADC block.
.. method:: ADCWiPy.deinit()
Disable the ADC block.
class ADCChannel --- read analog values from internal or external sources
=========================================================================
ADC channels can be connected to internal points of the MCU or to GPIO pins.
ADC channels are created using the ADC.channel method.
.. method:: adcchannel()
Fast method to read the channel value.
.. method:: adcchannel.value()
Read the channel value.
.. method:: adcchannel.init()
Re-init (and effectively enable) the ADC channel.
.. method:: adcchannel.deinit()
Disable the ADC channel.
.. currentmodule:: machine
.. _machine.I2C:
class I2C -- a two-wire serial protocol
=======================================
I2C is a two-wire protocol for communicating between devices. At the physical
level it consists of 2 wires: SCL and SDA, the clock and data lines respectively.
I2C objects are created attached to a specific bus. They can be initialised
when created, or initialised later on.
Printing the I2C object gives you information about its configuration.
Both hardware and software I2C implementations exist via the
:ref:`machine.I2C <machine.I2C>` and `machine.SoftI2C` classes. Hardware I2C uses
underlying hardware support of the system to perform the reads/writes and is
usually efficient and fast but may have restrictions on which pins can be used.
Software I2C is implemented by bit-banging and can be used on any pin but is not
as efficient. These classes have the same methods available and differ primarily
in the way they are constructed.
.. Note::
The I2C bus requires pull-up circuitry on both SDA and SCL for it's operation.
Usually these are resistors in the range of 1 - 10 kOhm, connected from each SDA/SCL
to Vcc. Without these, the behaviour is undefined and may range from blocking,
unexpected watchdog reset to just wrong values. Often, this pull-up circuitry
is built-in already to the MCU board or sensor breakout boards, but there is
no rule for that. So please check in case of trouble. See also this excellent
`learning guide <https://learn.adafruit.com/working-with-i2c-devices/pull-up-resistors>`_
by Adafruit about I2C wiring.
Example usage::
from machine import I2C
i2c = I2C(freq=400000) # create I2C peripheral at frequency of 400kHz
# depending on the port, extra parameters may be required
# to select the peripheral and/or pins to use
i2c.scan() # scan for peripherals, returning a list of 7-bit addresses
i2c.writeto(42, b'123') # write 3 bytes to peripheral 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 peripheral 42,
# starting at memory-address 8 in the peripheral
i2c.writeto_mem(42, 2, b'\x10') # write 1 byte to memory of peripheral 42
# starting at address 2 in the peripheral
Constructors
------------
.. class:: I2C(id, *, scl, sda, freq=400000)
Construct and return a new I2C object using the following parameters:
- *id* identifies a particular I2C peripheral. Allowed values for
depend on the particular port/board
- *scl* should be a pin object specifying the pin to use for SCL.
- *sda* should be a pin object specifying the pin to use for SDA.
- *freq* should be an integer which sets the maximum frequency
for SCL.
Note that some ports/boards will have default values of *scl* and *sda*
that can be changed in this constructor. Others will have fixed values
of *scl* and *sda* that cannot be changed.
.. _machine.SoftI2C:
.. class:: SoftI2C(scl, sda, *, freq=400000, timeout=50000)
Construct a new software I2C object. The parameters are:
- *scl* should be a pin object specifying the pin to use for SCL.
- *sda* should be a pin object specifying the pin to use for SDA.
- *freq* should be an integer which sets the maximum frequency
for SCL.
- *timeout* is the maximum time in microseconds to wait for clock
stretching (SCL held low by another device on the bus), after
which an ``OSError(ETIMEDOUT)`` exception is raised.
General Methods
---------------
.. method:: I2C.init(scl, sda, *, freq=400000)
Initialise the I2C bus with the given arguments:
- *scl* is a pin object for the SCL line
- *sda* is a pin object for the SDA line
- *freq* is the SCL clock rate
In the case of hardware I2C the actual clock frequency may be lower than the
requested frequency. This is dependant on the platform hardware. The actual
rate may be determined by printing the I2C object.
.. method:: I2C.deinit()
Turn off the I2C bus.
Availability: WiPy.
.. method:: I2C.scan()
Scan all I2C addresses between 0x08 and 0x77 inclusive and return a list of
those that respond. A device responds if it pulls the SDA line low after
its address (including a write bit) is sent on the bus.
Primitive I2C operations
------------------------
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
control over the bus, otherwise the standard methods (see below) can be used.
These methods are only available on the `machine.SoftI2C` class.
.. method:: I2C.start()
Generate a START condition on the bus (SDA transitions to low while SCL is high).
.. method:: I2C.stop()
Generate a STOP condition on the bus (SDA transitions to high while SCL is high).
.. method:: I2C.readinto(buf, nack=True, /)
Reads bytes from the bus and stores them into *buf*. The number of bytes
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*
is true then a NACK will be sent, otherwise an ACK will be sent (and in this
case the peripheral assumes more bytes are going to be read in a later call).
.. method:: I2C.write(buf)
Write the bytes from *buf* to the bus. Checks that an ACK is received
after each byte and stops transmitting the remaining bytes if a NACK is
received. The function returns the number of ACKs that were received.
Standard bus operations
-----------------------
The following methods implement the standard I2C controller read and write
operations that target a given peripheral device.
.. method:: I2C.readfrom(addr, nbytes, stop=True, /)
Read *nbytes* from the peripheral specified by *addr*.
If *stop* is true then a STOP condition is generated at the end of the transfer.
Returns a `bytes` object with the data read.
.. method:: I2C.readfrom_into(addr, buf, stop=True, /)
Read into *buf* from the peripheral specified by *addr*.
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.
The method returns ``None``.
.. method:: I2C.writeto(addr, buf, stop=True, /)
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
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.
The function returns the number of ACKs that were received.
.. method:: I2C.writevto(addr, vector, stop=True, /)
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.
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
in length in which case they don't contribute to the output.
If a NACK is received following the write of a byte from one of the
objects in *vector* then the remaining bytes, and any remaining objects,
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. The function
returns the number of ACKs that were received.
Memory operations
-----------------
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
I2C transaction: the peripheral address and the memory address. The following
methods are convenience functions to communicate with such devices.
.. method:: I2C.readfrom_mem(addr, memaddr, nbytes, *, addrsize=8)
Read *nbytes* from the peripheral specified by *addr* starting from the memory
address specified by *memaddr*.
The argument *addrsize* specifies the address size in bits.
Returns a `bytes` object with the data read.
.. method:: I2C.readfrom_mem_into(addr, memaddr, buf, *, addrsize=8)
Read into *buf* from the peripheral specified by *addr* starting from the
memory address specified by *memaddr*. The number of bytes read is the
length of *buf*.
The argument *addrsize* specifies the address size in bits (on ESP8266
this argument is not recognised and the address size is always 8 bits).
The method returns ``None``.
.. method:: I2C.writeto_mem(addr, memaddr, buf, *, addrsize=8)
Write *buf* to the peripheral specified by *addr* starting from the
memory address specified by *memaddr*.
The argument *addrsize* specifies the address size in bits (on ESP8266
this argument is not recognised and the address size is always 8 bits).
The method returns ``None``.
.. 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)
Some codec devices like the WM8960 or SGTL5000 require separate initialization
before they can operate with the I2S class. For these, separate drivers are
supplied, which also offer methods for controlling volume, audio processing and
other things. For these drivers see:
- :ref:`wm8960`
Constructor
-----------
.. class:: I2S(id, *, sck, ws, sd, mck=None, mode, bits, format, rate, ibuf)
Construct an I2S object of the given id:
- ``id`` identifies a particular I2S bus; it is board and port specific
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
- ``mck`` is a pin object for the master clock line;
master clock frequency is sampling rate * 256
- ``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 (Hz);
this is the frequency of the ``ws`` signal
- ``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
.. currentmodule:: machine
.. _machine.PWM:
class PWM -- pulse width modulation
===================================
This class provides pulse width modulation output.
Example usage::
from machine import PWM
pwm = PWM(pin) # create a PWM object on a pin
pwm.duty_u16(32768) # set duty to 50%
# reinitialise with a period of 200us, duty of 5us
pwm.init(freq=5000, duty_ns=5000)
pwm.duty_ns(3000) # set pulse width to 3us
pwm.deinit()
Constructors
------------
.. class:: PWM(dest, *, freq, duty_u16, duty_ns)
Construct and return a new PWM object using the following parameters:
- *dest* is the entity on which the PWM is output, which is usually a
:ref:`machine.Pin <machine.Pin>` object, but a port may allow other values,
like integers.
- *freq* should be an integer which sets the frequency in Hz for the
PWM cycle.
- *duty_u16* sets the duty cycle as a ratio ``duty_u16 / 65535``.
- *duty_ns* sets the pulse width in nanoseconds.
Setting *freq* may affect other PWM objects if the objects share the same
underlying PWM generator (this is hardware specific).
Only one of *duty_u16* and *duty_ns* should be specified at a time.
Methods
-------
.. method:: PWM.init(*, freq, duty_u16, duty_ns)
Modify settings for the PWM object. See the above constructor for details
about the parameters.
.. method:: PWM.deinit()
Disable the PWM output.
.. method:: PWM.freq([value])
Get or set the current frequency of the PWM output.
With no arguments the frequency in Hz is returned.
With a single *value* argument the frequency is set to that value in Hz. The
method may raise a ``ValueError`` if the frequency is outside the valid range.
.. method:: PWM.duty_u16([value])
Get or set the current duty cycle of the PWM output, as an unsigned 16-bit
value in the range 0 to 65535 inclusive.
With no arguments the duty cycle is returned.
With a single *value* argument the duty cycle is set to that value, measured
as the ratio ``value / 65535``.
.. method:: PWM.duty_ns([value])
Get or set the current pulse width of the PWM output, as a value in nanoseconds.
With no arguments the pulse width in nanoseconds is returned.
With a single *value* argument the pulse width is set to that value.
Specific PWM class implementations
----------------------------------
The following concrete class(es) implement enhancements to the PWM class.
| :ref:`pyb.Timer for PyBoard <pyb.Timer>`
Limitations of PWM
------------------
* Not all frequencies can be generated with absolute accuracy due to
the discrete nature of the computing hardware. Typically the PWM frequency
is obtained by dividing some integer base frequency by an integer divider.
For example, if the base frequency is 80MHz and the required PWM frequency is
300kHz the divider must be a non-integer number 80000000 / 300000 = 266.67.
After rounding the divider is set to 267 and the PWM frequency will be
80000000 / 267 = 299625.5 Hz, not 300kHz. If the divider is set to 266 then
the PWM frequency will be 80000000 / 266 = 300751.9 Hz, but again not 300kHz.
Some ports like the RP2040 one use a fractional divider, which allow a finer
granularity of the frequency at higher frequencies by switching the PWM
pulse duration between two adjacent values, such that the resulting average
frequency is more close to the intended one, at the cost of spectral purity.
* The duty cycle has the same discrete nature and its absolute accuracy is not
achievable. On most hardware platforms the duty will be applied at the next
frequency period. Therefore, you should wait more than "1/frequency" before
measuring the duty.
* The frequency and the duty cycle resolution are usually interdependent.
The higher the PWM frequency the lower the duty resolution which is available,
and vice versa. For example, a 300kHz PWM frequency can have a duty cycle
resolution of 8 bit, not 16-bit as may be expected. In this case, the lowest
8 bits of *duty_u16* are insignificant. So::
pwm=PWM(Pin(13), freq=300_000, duty_u16=2**16//2)
and::
pwm=PWM(Pin(13), freq=300_000, duty_u16=2**16//2 + 255)
will generate PWM with the same 50% duty cycle.
.. currentmodule:: machine
.. _machine.Pin:
class Pin -- control I/O pins
=============================
A pin object is used to control I/O pins (also known as GPIO - general-purpose
input/output). Pin objects are commonly associated with a physical pin that can
drive an output voltage and read input voltages. The pin class has methods to set the mode of
the pin (IN, OUT, etc) and methods to get and set the digital logic level.
For analog control of a pin, see the :class:`ADC` class.
A pin object is constructed by using an identifier which unambiguously
specifies a certain I/O pin. The allowed forms of the identifier and the
physical pin that the identifier maps to are port-specific. Possibilities
for the identifier are an integer, a string or a tuple with port and pin
number.
Usage Model::
from machine import Pin
# create an output pin on pin #0
p0 = Pin(0, Pin.OUT)
# set the value low then high
p0.value(0)
p0.value(1)
# create an input pin on pin #2, with a pull up resistor
p2 = Pin(2, Pin.IN, Pin.PULL_UP)
# read and print the pin value
print(p2.value())
# reconfigure pin #0 in input mode with a pull down resistor
p0.init(p0.IN, p0.PULL_DOWN)
# configure an irq callback
p0.irq(lambda p:print(p))
Constructors
------------
.. class:: Pin(id, mode=-1, pull=-1, *, value=None, drive=0, alt=-1)
Access the pin peripheral (GPIO pin) associated with the given ``id``. If
additional arguments are given in the constructor then they are used to initialise
the pin. Any settings that are not specified will remain in their previous state.
The arguments are:
- ``id`` is mandatory and can be an arbitrary object. Among possible value
types are: int (an internal Pin identifier), str (a Pin name), and tuple
(pair of [port, pin]).
- ``mode`` specifies the pin mode, which can be one of:
- ``Pin.IN`` - Pin is configured for input. If viewed as an output the pin
is in high-impedance state.
- ``Pin.OUT`` - Pin is configured for (normal) output.
- ``Pin.OPEN_DRAIN`` - Pin is configured for open-drain output. Open-drain
output works in the following way: if the output value is set to 0 the pin
is active at a low level; if the output value is 1 the pin is in a high-impedance
state. Not all ports implement this mode, or some might only on certain pins.
- ``Pin.ALT`` - Pin is configured to perform an alternative function, which is
port specific. For a pin configured in such a way any other Pin methods
(except :meth:`Pin.init`) are not applicable (calling them will lead to undefined,
or a hardware-specific, result). Not all ports implement this mode.
- ``Pin.ALT_OPEN_DRAIN`` - The Same as ``Pin.ALT``, but the pin is configured as
open-drain. Not all ports implement this mode.
- ``Pin.ANALOG`` - Pin is configured for analog input, see the :class:`ADC` class.
- ``pull`` specifies if the pin has a (weak) pull resistor attached, and can be
one of:
- ``None`` - No pull up or down resistor.
- ``Pin.PULL_UP`` - Pull up resistor enabled.
- ``Pin.PULL_DOWN`` - Pull down resistor enabled.
- ``value`` is valid only for Pin.OUT and Pin.OPEN_DRAIN modes and specifies initial
output pin value if given, otherwise the state of the pin peripheral remains
unchanged.
- ``drive`` specifies the output power of the pin and can be one of: ``Pin.DRIVE_0``,
``Pin.DRIVE_1``, etc., increasing in drive strength. The actual current driving
capabilities are port dependent. Not all ports implement this argument.
- ``alt`` specifies an alternate function for the pin and the values it can take are
port dependent. This argument is valid only for ``Pin.ALT`` and ``Pin.ALT_OPEN_DRAIN``
modes. It may be used when a pin supports more than one alternate function. If only
one pin alternate function is supported the this argument is not required. Not all
ports implement this argument.
As specified above, the Pin class allows to set an alternate function for a particular
pin, but it does not specify any further operations on such a pin. Pins configured in
alternate-function mode are usually not used as GPIO but are instead driven by other
hardware peripherals. The only operation supported on such a pin is re-initialising,
by calling the constructor or :meth:`Pin.init` method. If a pin that is configured in
alternate-function mode is re-initialised with ``Pin.IN``, ``Pin.OUT``, or
``Pin.OPEN_DRAIN``, the alternate function will be removed from the pin.
Methods
-------
.. method:: Pin.init(mode=-1, pull=-1, *, value=None, drive=0, alt=-1)
Re-initialise the pin using the given parameters. Only those arguments that
are specified will be set. The rest of the pin peripheral state will remain
unchanged. See the constructor documentation for details of the arguments.
Returns ``None``.
.. method:: Pin.value([x])
This method allows to set and get the value of the pin, depending on whether
the argument ``x`` is supplied or not.
If the argument is omitted then this method gets the digital logic level of
the pin, returning 0 or 1 corresponding to low and high voltage signals
respectively. The behaviour of this method depends on the mode of the pin:
- ``Pin.IN`` - The method returns the actual input value currently present
on the pin.
- ``Pin.OUT`` - The behaviour and return value of the method is undefined.
- ``Pin.OPEN_DRAIN`` - If the pin is in state '0' then the behaviour and
return value of the method is undefined. Otherwise, if the pin is in
state '1', the method returns the actual input value currently present
on the pin.
If the argument is supplied then this method sets the digital logic level of
the pin. The argument ``x`` can be anything that converts to a boolean.
If it converts to ``True``, the pin is set to state '1', otherwise it is set
to state '0'. The behaviour of this method depends on the mode of the pin:
- ``Pin.IN`` - The value is stored in the output buffer for the pin. The
pin state does not change, it remains in the high-impedance state. The
stored value will become active on the pin as soon as it is changed to
``Pin.OUT`` or ``Pin.OPEN_DRAIN`` mode.
- ``Pin.OUT`` - The output buffer is set to the given value immediately.
- ``Pin.OPEN_DRAIN`` - If the value is '0' the pin is set to a low voltage
state. Otherwise the pin is set to high-impedance state.
When setting the value this method returns ``None``.
.. method:: Pin.__call__([x])
Pin objects are callable. The call method provides a (fast) shortcut to set
and get the value of the pin. It is equivalent to Pin.value([x]).
See :meth:`Pin.value` for more details.
.. method:: Pin.on()
Set pin to "1" output level.
.. method:: Pin.off()
Set pin to "0" output level.
.. method:: Pin.irq(handler=None, trigger=(Pin.IRQ_FALLING | Pin.IRQ_RISING), *, priority=1, wake=None, hard=False)
Configure an interrupt handler to be called when the trigger source of the
pin is active. If the pin mode is ``Pin.IN`` then the trigger source is
the external value on the pin. If the pin mode is ``Pin.OUT`` then the
trigger source is the output buffer of the pin. Otherwise, if the pin mode
is ``Pin.OPEN_DRAIN`` then the trigger source is the output buffer for
state '0' and the external pin value for state '1'.
The arguments are:
- ``handler`` is an optional function to be called when the interrupt
triggers. The handler must take exactly one argument which is the
``Pin`` instance.
- ``trigger`` configures the event which can generate an interrupt.
Possible values are:
- ``Pin.IRQ_FALLING`` interrupt on falling edge.
- ``Pin.IRQ_RISING`` interrupt on rising edge.
- ``Pin.IRQ_LOW_LEVEL`` interrupt on low level.
- ``Pin.IRQ_HIGH_LEVEL`` interrupt on high level.
These values can be OR'ed together to trigger on multiple events.
- ``priority`` sets the priority level of the interrupt. The values it
can take are port-specific, but higher values always represent higher
priorities.
- ``wake`` selects the power mode in which this interrupt can wake up the
system. It can be ``machine.IDLE``, ``machine.SLEEP`` or ``machine.DEEPSLEEP``.
These values can also be OR'ed together to make a pin generate interrupts in
more than one power mode.
- ``hard`` if true a hardware interrupt is used. This reduces the delay
between the pin change and the handler being called. Hard interrupt
handlers may not allocate memory; see :ref:`isr_rules`.
Not all ports support this argument.
This method returns a callback object.
The following methods are not part of the core Pin API and only implemented on certain ports.
.. method:: Pin.low()
Set pin to "0" output level.
Availability: nrf, rp2, stm32 ports.
.. method:: Pin.high()
Set pin to "1" output level.
Availability: nrf, rp2, stm32 ports.
.. method:: Pin.mode([mode])
Get or set the pin mode.
See the constructor documentation for details of the ``mode`` argument.
Availability: cc3200, stm32 ports.
.. method:: Pin.pull([pull])
Get or set the pin pull state.
See the constructor documentation for details of the ``pull`` argument.
Availability: cc3200, stm32 ports.
.. method:: Pin.drive([drive])
Get or set the pin drive strength.
See the constructor documentation for details of the ``drive`` argument.
Availability: cc3200 port.
Constants
---------
The following constants are used to configure the pin objects. Note that
not all constants are available on all ports.
.. data:: Pin.IN
Pin.OUT
Pin.OPEN_DRAIN
Pin.ALT
Pin.ALT_OPEN_DRAIN
Pin.ANALOG
Selects the pin mode.
.. data:: Pin.PULL_UP
Pin.PULL_DOWN
Pin.PULL_HOLD
Selects whether there is a pull up/down resistor. Use the value
``None`` for no pull.
.. data:: Pin.DRIVE_0
Pin.DRIVE_1
Pin.DRIVE_2
Selects the pin drive strength. A port may define additional drive
constants with increasing number corresponding to increasing drive
strength.
.. data:: Pin.IRQ_FALLING
Pin.IRQ_RISING
Pin.IRQ_LOW_LEVEL
Pin.IRQ_HIGH_LEVEL
Selects the IRQ trigger type.
.. currentmodule:: machine
.. _machine.RTC:
class RTC -- real time clock
============================
The RTC is an independent clock that keeps track of the date
and time.
Example usage::
rtc = machine.RTC()
rtc.datetime((2020, 1, 21, 2, 10, 32, 36, 0))
print(rtc.datetime())
Constructors
------------
.. class:: RTC(id=0, ...)
Create an RTC object. See init for parameters of initialization.
Methods
-------
.. method:: RTC.datetime([datetimetuple])
Get or set the date and time of the RTC.
With no arguments, this method returns an 8-tuple with the current
date and time. With 1 argument (being an 8-tuple) it sets the date
and time.
The 8-tuple has the following format:
(year, month, day, weekday, hours, minutes, seconds, subseconds)
The meaning of the ``subseconds`` field is hardware dependent.
.. method:: RTC.init(datetime)
Initialise the RTC. Datetime is a tuple of the form:
``(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])``
.. method:: RTC.now()
Get get the current datetime tuple.
.. method:: RTC.deinit()
Resets the RTC to the time of January 1, 2015 and starts running it again.
.. method:: RTC.alarm(id, time, *, repeat=False)
Set the RTC alarm. Time might be either a millisecond value to program the alarm to
current time + time_in_ms in the future, or a datetimetuple. If the time passed is in
milliseconds, repeat can be set to ``True`` to make the alarm periodic.
.. method:: RTC.alarm_left(alarm_id=0)
Get the number of milliseconds left before the alarm expires.
.. method:: RTC.cancel(alarm_id=0)
Cancel a running alarm.
.. method:: RTC.irq(*, trigger, handler=None, wake=machine.IDLE)
Create an irq object triggered by a real time clock alarm.
- ``trigger`` must be ``RTC.ALARM0``
- ``handler`` is the function to be called when the callback is triggered.
- ``wake`` specifies the sleep mode from where this interrupt can wake
up the system.
Constants
---------
.. data:: RTC.ALARM0
irq trigger source
.. currentmodule:: machine
.. _machine.SD:
class SD -- secure digital memory card (cc3200 port only)
=========================================================
.. warning::
This is a non-standard class and is only available on the cc3200 port.
The SD card class allows to configure and enable the memory card
module of the WiPy and automatically mount it as ``/sd`` as part
of the file system. There are several pin combinations that can be
used to wire the SD card socket to the WiPy and the pins used can
be specified in the constructor. Please check the `pinout and alternate functions
table. <https://raw.githubusercontent.com/wipy/wipy/master/docs/PinOUT.png>`_ for
more info regarding the pins which can be remapped to be used with a SD card.
Example usage::
from machine import SD
import os
# clk cmd and dat0 pins must be passed along with
# their respective alternate functions
sd = machine.SD(pins=('GP10', 'GP11', 'GP15'))
os.mount(sd, '/sd')
# do normal file operations
Constructors
------------
.. class:: SD(id,... )
Create a SD card object. See ``init()`` for parameters if initialization.
Methods
-------
.. method:: SD.init(id=0, pins=('GP10', 'GP11', 'GP15'))
Enable the SD card. In order to initialize the card, give it a 3-tuple:
``(clk_pin, cmd_pin, dat0_pin)``.
.. method:: SD.deinit()
Disable the SD card.
.. currentmodule:: machine
.. _machine.SDCard:
class SDCard -- secure digital memory card
==========================================
SD cards are one of the most common small form factor removable storage media.
SD cards come in a variety of sizes and physical form factors. MMC cards are
similar removable storage devices while eMMC devices are electrically similar
storage devices designed to be embedded into other systems. All three form
share a common protocol for communication with their host system and high-level
support looks the same for them all. As such in MicroPython they are implemented
in a single class called :class:`machine.SDCard` .
Both SD and MMC interfaces support being accessed with a variety of bus widths.
When being accessed with a 1-bit wide interface they can be accessed using the
SPI protocol. Different MicroPython hardware platforms support different widths
and pin configurations but for most platforms there is a standard configuration
for any given hardware. In general constructing an ``SDCard`` object with without
passing any parameters will initialise the interface to the default card slot
for the current hardware. The arguments listed below represent the common
arguments that might need to be set in order to use either a non-standard slot
or a non-standard pin assignment. The exact subset of arguments supported will
vary from platform to platform.
.. class:: SDCard(slot=1, width=1, cd=None, wp=None, sck=None, miso=None, mosi=None, cs=None, freq=20000000)
This class provides access to SD or MMC storage cards using either
a dedicated SD/MMC interface hardware or through an SPI channel.
The class implements the block protocol defined by :class:`os.AbstractBlockDev`.
This allows the mounting of an SD card to be as simple as::
os.mount(machine.SDCard(), "/sd")
The constructor takes the following parameters:
- *slot* selects which of the available interfaces to use. Leaving this
unset will select the default interface.
- *width* selects the bus width for the SD/MMC interface.
- *cd* can be used to specify a card-detect pin.
- *wp* can be used to specify a write-protect pin.
- *sck* can be used to specify an SPI clock pin.
- *miso* can be used to specify an SPI miso pin.
- *mosi* can be used to specify an SPI mosi pin.
- *cs* can be used to specify an SPI chip select pin.
- *freq* selects the SD/MMC interface frequency in Hz (only supported on the ESP32).
Implementation-specific details
-------------------------------
Different implementations of the ``SDCard`` class on different hardware support
varying subsets of the options above.
PyBoard
```````
The standard PyBoard has just one slot. No arguments are necessary or supported.
ESP32
`````
The ESP32 provides two channels of SD/MMC hardware and also supports
access to SD Cards through either of the two SPI ports that are
generally available to the user. As a result the *slot* argument can
take a value between 0 and 3, inclusive. Slots 0 and 1 use the
built-in SD/MMC hardware while slots 2 and 3 use the SPI ports. Slot 0
supports 1, 4 or 8-bit wide access while slot 1 supports 1 or 4-bit
access; the SPI slots only support 1-bit access.
.. note:: Slot 0 is used to communicate with on-board flash memory
on most ESP32 modules and so will be unavailable to the
user.
.. note:: Most ESP32 modules that provide an SD card slot using the
dedicated hardware only wire up 1 data pin, so the default
value for *width* is 1.
The pins used by the dedicated SD/MMC hardware are fixed. The pins
used by the SPI hardware can be reassigned.
.. note:: If any of the SPI signals are remapped then all of the SPI
signals will pass through a GPIO multiplexer unit which
can limit the performance of high frequency signals. Since
the normal operating speed for SD cards is 40MHz this can
cause problems on some cards.
The default (and preferred) pin assignment are as follows:
====== ====== ====== ====== ======
Slot 0 1 2 3
------ ------ ------ ------ ------
Signal Pin Pin Pin Pin
====== ====== ====== ====== ======
sck 6 14 18 14
cmd 11 15
cs 5 15
miso 19 12
mosi 23 13
D0 7 2
D1 8 4
D2 9 12
D3 10 13
D4 16
D5 17
D6 5
D7 18
====== ====== ====== ====== ======
cc3200
``````
You can set the pins used for SPI access by passing a tuple as the
*pins* argument.
*Note:* The current cc3200 SD card implementation names the this class
:class:`machine.SD` rather than :class:`machine.SDCard` .
mimxrt
``````
The SDCard module for the mimxrt port only supports access via dedicated SD/MMC
peripheral (USDHC) in 4-bit mode with 50MHz clock frequency exclusively.
Unfortunately the MIMXRT1011 controller does not support the USDHC peripheral.
Hence this controller does not feature the ``machine.SDCard`` module.
Due to the decision to only support 4-bit mode with 50MHz clock frequency the
interface has been simplified, and the constructor signature is:
.. class:: SDCard(slot=1)
:noindex:
The pins used for the USDHC peripheral have to be configured in ``mpconfigboard.h``.
Most of the controllers supported by the mimxrt port provide up to two USDHC
peripherals. Therefore the pin configuration is performed using the macro
``MICROPY_USDHCx`` with x being 1 or 2 respectively.
The following shows an example configuration for USDHC1::
#define MICROPY_USDHC1 \
{ \
.cmd = { GPIO_SD_B0_02_USDHC1_CMD}, \
.clk = { GPIO_SD_B0_03_USDHC1_CLK }, \
.cd_b = { GPIO_SD_B0_06_USDHC1_CD_B },\
.data0 = { GPIO_SD_B0_04_USDHC1_DATA0 },\
.data1 = { GPIO_SD_B0_05_USDHC1_DATA1 },\
.data2 = { GPIO_SD_B0_00_USDHC1_DATA2 },\
.data3 = { GPIO_SD_B0_01_USDHC1_DATA3 },\
}
If the card detect pin is not used (cb_b pin) then the respective entry has to be
filled with the following dummy value::
#define USDHC_DUMMY_PIN NULL , 0
Based on the definition of macro ``MICROPY_USDHC1`` and/or ``MICROPY_USDHC2``
the ``machine.SDCard`` module either supports one or two slots. If only one of
the defines is provided, calling ``machine.SDCard()`` or ``machine.SDCard(1)``
will return an instance using the respective USDHC peripheral. When both macros
are defined, calling ``machine.SDCard(2)`` returns an instance using USDHC2.
.. currentmodule:: machine
.. _machine.SPI:
class SPI -- a Serial Peripheral Interface bus protocol (controller side)
=========================================================================
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
can share the same bus. Each device should have a separate, 4th signal,
CS (Chip Select), to select a particular device on a bus with which
communication takes place. Management of a CS signal should happen in
user code (via machine.Pin class).
Both hardware and software SPI implementations exist via the
:ref:`machine.SPI <machine.SPI>` and `machine.SoftSPI` classes. Hardware SPI uses underlying
hardware support of the system to perform the reads/writes and is usually
efficient and fast but may have restrictions on which pins can be used.
Software SPI is implemented by bit-banging and can be used on any pin but
is not as efficient. These classes have the same methods available and
differ primarily in the way they are constructed.
Example usage::
from machine import SPI, Pin
spi = SPI(0, baudrate=400000) # Create SPI peripheral 0 at frequency of 400kHz.
# Depending on the use case, extra parameters may be required
# to select the bus characteristics and/or pins to use.
cs = Pin(4, mode=Pin.OUT, value=1) # Create chip-select on pin 4.
try:
cs(0) # Select peripheral.
spi.write(b"12345678") # Write 8 bytes, and don't care about received data.
finally:
cs(1) # Deselect peripheral.
try:
cs(0) # Select peripheral.
rxdata = spi.read(8, 0x42) # Read 8 bytes while writing 0x42 for each byte.
finally:
cs(1) # Deselect peripheral.
rxdata = bytearray(8)
try:
cs(0) # Select peripheral.
spi.readinto(rxdata, 0x42) # Read 8 bytes inplace while writing 0x42 for each byte.
finally:
cs(1) # Deselect peripheral.
txdata = b"12345678"
rxdata = bytearray(len(txdata))
try:
cs(0) # Select peripheral.
spi.write_readinto(txdata, rxdata) # Simultaneously write and read bytes.
finally:
cs(1) # Deselect peripheral.
Constructors
------------
.. class:: SPI(id, ...)
Construct an SPI object on the given bus, *id*. Values of *id* depend
on a particular port and its hardware. Values 0, 1, etc. are commonly used
to select hardware SPI block #0, #1, etc.
With no additional parameters, the SPI object is created but not
initialised (it has the settings from the last initialisation of
the bus, if any). If extra arguments are given, the bus is initialised.
See ``init`` for parameters of initialisation.
.. _machine.SoftSPI:
.. class:: SoftSPI(baudrate=500000, *, polarity=0, phase=0, bits=8, firstbit=MSB, sck=None, mosi=None, miso=None)
Construct a new software SPI object. Additional parameters must be
given, usually at least *sck*, *mosi* and *miso*, and these are used
to initialise the bus. See `SPI.init` for a description of the parameters.
Methods
-------
.. method:: SPI.init(baudrate=1000000, *, polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=None, mosi=None, miso=None, pins=(SCK, MOSI, MISO))
Initialise the SPI bus with the given parameters:
- ``baudrate`` is the SCK clock rate.
- ``polarity`` can be 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.
- ``bits`` is the width in bits of each transfer. Only 8 is guaranteed to be supported by all hardware.
- ``firstbit`` can be ``SPI.MSB`` or ``SPI.LSB``.
- ``sck``, ``mosi``, ``miso`` are pins (machine.Pin) objects to use for bus signals. For most
hardware SPI blocks (as selected by ``id`` parameter to the constructor), pins are fixed
and cannot be changed. In some cases, hardware blocks allow 2-3 alternative pin sets for
a hardware SPI block. Arbitrary pin assignments are possible only for a bitbanging SPI driver
(``id`` = -1).
- ``pins`` - WiPy port doesn't ``sck``, ``mosi``, ``miso`` arguments, and instead allows to
specify them as a tuple of ``pins`` parameter.
In the case of hardware SPI the actual clock frequency may be lower than the
requested baudrate. This is dependant on the platform hardware. The actual
rate may be determined by printing the SPI object.
.. method:: SPI.deinit()
Turn off the SPI bus.
.. method:: SPI.read(nbytes, write=0x00)
Read a number of bytes specified by ``nbytes`` while continuously writing
the single byte given by ``write``.
Returns a ``bytes`` object with the data that was read.
.. method:: SPI.readinto(buf, write=0x00)
Read into the buffer specified by ``buf`` while continuously writing the
single byte given by ``write``.
Returns ``None``.
Note: on WiPy this function returns the number of bytes read.
.. method:: SPI.write(buf)
Write the bytes contained in ``buf``.
Returns ``None``.
Note: on WiPy this function returns the number of bytes written.
.. method:: SPI.write_readinto(write_buf, read_buf)
Write the bytes from ``write_buf`` while reading into ``read_buf``. The
buffers can be the same or different, but both buffers must have the
same length.
Returns ``None``.
Note: on WiPy this function returns the number of bytes written.
Constants
---------
.. data:: SPI.CONTROLLER
for initialising the SPI bus to controller; this is only used for the WiPy
.. data:: SPI.MSB
SoftSPI.MSB
set the first bit to be the most significant bit
.. data:: SPI.LSB
SoftSPI.LSB
set the first bit to be the least significant bit
.. currentmodule:: machine
.. _machine.Signal:
class Signal -- control and sense external I/O devices
======================================================
The Signal class is a simple extension of the `Pin` class. Unlike Pin, which
can be only in "absolute" 0 and 1 states, a Signal can be in "asserted"
(on) or "deasserted" (off) states, while being inverted (active-low) or
not. In other words, it adds logical inversion support to Pin functionality.
While this may seem a simple addition, it is exactly what is needed to
support wide array of simple digital devices in a way portable across
different boards, which is one of the major MicroPython goals. Regardless
of whether different users have an active-high or active-low LED, a normally
open or normally closed relay - you can develop a single, nicely looking
application which works with each of them, and capture hardware
configuration differences in few lines in the config file of your app.
Example::
from machine import Pin, Signal
# Suppose you have an active-high LED on pin 0
led1_pin = Pin(0, Pin.OUT)
# ... and active-low LED on pin 1
led2_pin = Pin(1, Pin.OUT)
# Now to light up both of them using Pin class, you'll need to set
# them to different values
led1_pin.value(1)
led2_pin.value(0)
# Signal class allows to abstract away active-high/active-low
# difference
led1 = Signal(led1_pin, invert=False)
led2 = Signal(led2_pin, invert=True)
# Now lighting up them looks the same
led1.value(1)
led2.value(1)
# Even better:
led1.on()
led2.on()
Following is the guide when Signal vs Pin should be used:
* Use Signal: If you want to control a simple on/off (including software
PWM!) devices like LEDs, multi-segment indicators, relays, buzzers, or
read simple binary sensors, like normally open or normally closed buttons,
pulled high or low, Reed switches, moisture/flame detectors, etc. etc.
Summing up, if you have a real physical device/sensor requiring GPIO
access, you likely should use a Signal.
* Use Pin: If you implement a higher-level protocol or bus to communicate
with more complex devices.
The split between Pin and Signal come from the use cases above and the
architecture of MicroPython: Pin offers the lowest overhead, which may
be important when bit-banging protocols. But Signal adds additional
flexibility on top of Pin, at the cost of minor overhead (much smaller
than if you implemented active-high vs active-low device differences in
Python manually!). Also, Pin is a low-level object which needs to be
implemented for each support board, while Signal is a high-level object
which comes for free once Pin is implemented.
If in doubt, give the Signal a try! Once again, it is offered to save
developers from the need to handle unexciting differences like active-low
vs active-high signals, and allow other users to share and enjoy your
application, instead of being frustrated by the fact that it doesn't
work for them simply because their LEDs or relays are wired in a slightly
different way.
Constructors
------------
.. class:: Signal(pin_obj, invert=False)
Signal(pin_arguments..., *, invert=False)
Create a Signal object. There're two ways to create it:
* By wrapping existing Pin object - universal method which works for
any board.
* By passing required Pin parameters directly to Signal constructor,
skipping the need to create intermediate Pin object. Available on
many, but not all boards.
The arguments are:
- ``pin_obj`` is existing Pin object.
- ``pin_arguments`` are the same arguments as can be passed to Pin constructor.
- ``invert`` - if True, the signal will be inverted (active low).
Methods
-------
.. method:: Signal.value([x])
This method allows to set and get the value of the signal, depending on whether
the argument ``x`` is supplied or not.
If the argument is omitted then this method gets the signal level, 1 meaning
signal is asserted (active) and 0 - signal inactive.
If the argument is supplied then this method sets the signal level. The
argument ``x`` can be anything that converts to a boolean. If it converts
to ``True``, the signal is active, otherwise it is inactive.
Correspondence between signal being active and actual logic level on the
underlying pin depends on whether signal is inverted (active-low) or not.
For non-inverted signal, active status corresponds to logical 1, inactive -
to logical 0. For inverted/active-low signal, active status corresponds
to logical 0, while inactive - to logical 1.
.. method:: Signal.on()
Activate signal.
.. method:: Signal.off()
Deactivate signal.
.. currentmodule:: machine
.. _machine.Timer:
class Timer -- control hardware timers
======================================
Hardware timers deal with timing of periods and events. Timers are perhaps
the most flexible and heterogeneous kind of hardware in MCUs and SoCs,
differently greatly from a model to a model. MicroPython's Timer class
defines a baseline operation of executing a callback with a given period
(or once after some delay), and allow specific boards to define more
non-standard behaviour (which thus won't be portable to other boards).
See discussion of :ref:`important constraints <machine_callbacks>` on
Timer callbacks.
.. note::
Memory can't be allocated inside irq handlers (an interrupt) and so
exceptions raised within a handler don't give much information. See
:func:`micropython.alloc_emergency_exception_buf` for how to get around this
limitation.
If you are using a WiPy board please refer to :ref:`machine.TimerWiPy <machine.TimerWiPy>`
instead of this class.
Constructors
------------
.. class:: Timer(id, /, ...)
Construct a new timer object of the given ``id``. ``id`` of -1 constructs a
virtual timer (if supported by a board).
``id`` shall not be passed as a keyword argument.
See ``init`` for parameters of initialisation.
Methods
-------
.. method:: Timer.init(*, mode=Timer.PERIODIC, freq=-1, period=-1, callback=None)
Initialise the timer. Example::
def mycallback(t):
pass
# periodic at 1kHz
tim.init(mode=Timer.PERIODIC, freq=1000, callback=mycallback)
# periodic with 100ms period
tim.init(period=100, callback=mycallback)
# one shot firing after 1000ms
tim.init(mode=Timer.ONE_SHOT, period=1000, callback=mycallback)
Keyword arguments:
- ``mode`` can be one of:
- ``Timer.ONE_SHOT`` - The timer runs once until the configured
period of the channel expires.
- ``Timer.PERIODIC`` - The timer runs periodically at the configured
frequency of the channel.
- ``freq`` - The timer frequency, in units of Hz. The upper bound of
the frequency is dependent on the port. When both the ``freq`` and
``period`` arguments are given, ``freq`` has a higher priority and
``period`` is ignored.
- ``period`` - The timer period, in milliseconds.
- ``callback`` - The callable to call upon expiration of the timer period.
The callback must take one argument, which is passed the Timer object.
The ``callback`` argument shall be specified. Otherwise an exception
will occurr upon timer expiration:
``TypeError: 'NoneType' object isn't callable``
.. method:: Timer.deinit()
Deinitialises the timer. Stops the timer, and disables the timer peripheral.
Constants
---------
.. data:: Timer.ONE_SHOT
Timer.PERIODIC
Timer operating mode.
.. currentmodule:: machine
.. _machine.TimerWiPy:
class TimerWiPy -- control hardware timers
==========================================
.. note::
This class is a non-standard Timer implementation for the WiPy.
It is available simply as ``machine.Timer`` on the WiPy but is named in the
documentation below as ``machine.TimerWiPy`` to distinguish it from the
more general :ref:`machine.Timer <machine.Timer>` class.
Hardware timers deal with timing of periods and events. Timers are perhaps
the most flexible and heterogeneous kind of hardware in MCUs and SoCs,
differently greatly from a model to a model. MicroPython's Timer class
defines a baseline operation of executing a callback with a given period
(or once after some delay), and allow specific boards to define more
non-standard behaviour (which thus won't be portable to other boards).
See discussion of :ref:`important constraints <machine_callbacks>` on
Timer callbacks.
.. note::
Memory can't be allocated inside irq handlers (an interrupt) and so
exceptions raised within a handler don't give much information. See
:func:`micropython.alloc_emergency_exception_buf` for how to get around this
limitation.
Constructors
------------
.. class:: TimerWiPy(id, ...)
Construct a new timer object of the given id. Id of -1 constructs a
virtual timer (if supported by a board).
Methods
-------
.. method:: TimerWiPy.init(mode, *, width=16)
Initialise the timer. Example::
tim.init(Timer.PERIODIC) # periodic 16-bit timer
tim.init(Timer.ONE_SHOT, width=32) # one shot 32-bit timer
Keyword arguments:
- ``mode`` can be one of:
- ``TimerWiPy.ONE_SHOT`` - The timer runs once until the configured
period of the channel expires.
- ``TimerWiPy.PERIODIC`` - The timer runs periodically at the configured
frequency of the channel.
- ``TimerWiPy.PWM`` - Output a PWM signal on a pin.
- ``width`` must be either 16 or 32 (bits). For really low frequencies < 5Hz
(or large periods), 32-bit timers should be used. 32-bit mode is only available
for ``ONE_SHOT`` AND ``PERIODIC`` modes.
.. method:: TimerWiPy.deinit()
Deinitialises the timer. Stops the timer, and disables the timer peripheral.
.. method:: TimerWiPy.channel(channel, **, freq, period, polarity=TimerWiPy.POSITIVE, duty_cycle=0)
If only a channel identifier passed, then a previously initialized channel
object is returned (or ``None`` if there is no previous channel).
Otherwise, a TimerChannel object is initialized and returned.
The operating mode is is the one configured to the Timer object that was used to
create the channel.
- ``channel`` if the width of the timer is 16-bit, then must be either ``TIMER.A``, ``TIMER.B``.
If the width is 32-bit then it **must be** ``TIMER.A | TIMER.B``.
Keyword only arguments:
- ``freq`` sets the frequency in Hz.
- ``period`` sets the period in microseconds.
.. note::
Either ``freq`` or ``period`` must be given, never both.
- ``polarity`` this is applicable for ``PWM``, and defines the polarity of the duty cycle
- ``duty_cycle`` only applicable to ``PWM``. It's a percentage (0.00-100.00). Since the WiPy
doesn't support floating point numbers the duty cycle must be specified in the range 0-10000,
where 10000 would represent 100.00, 5050 represents 50.50, and so on.
.. note::
When the channel is in PWM mode, the corresponding pin is assigned automatically, therefore
there's no need to assign the alternate function of the pin via the ``Pin`` class. The pins which
support PWM functionality are the following:
- ``GP24`` on Timer 0 channel A.
- ``GP25`` on Timer 1 channel A.
- ``GP9`` on Timer 2 channel B.
- ``GP10`` on Timer 3 channel A.
- ``GP11`` on Timer 3 channel B.
class TimerChannel --- setup a channel for a timer
==================================================
Timer channels are used to generate/capture a signal using a timer.
TimerChannel objects are created using the Timer.channel() method.
Methods
-------
.. method:: timerchannel.irq(*, trigger, priority=1, handler=None)
The behaviour of this callback is heavily dependent on the operating
mode of the timer channel:
- If mode is ``TimerWiPy.PERIODIC`` the callback is executed periodically
with the configured frequency or period.
- If mode is ``TimerWiPy.ONE_SHOT`` the callback is executed once when
the configured timer expires.
- If mode is ``TimerWiPy.PWM`` the callback is executed when reaching the duty
cycle value.
The accepted params are:
- ``priority`` level of the interrupt. Can take values in the range 1-7.
Higher values represent higher priorities.
- ``handler`` is an optional function to be called when the interrupt is triggered.
- ``trigger`` must be ``TimerWiPy.TIMEOUT`` when the operating mode is either ``TimerWiPy.PERIODIC`` or
``TimerWiPy.ONE_SHOT``. In the case that mode is ``TimerWiPy.PWM`` then trigger must be equal to
``TimerWiPy.MATCH``.
Returns a callback object.
.. method:: timerchannel.freq([value])
Get or set the timer channel frequency (in Hz).
.. method:: timerchannel.period([value])
Get or set the timer channel period (in microseconds).
.. method:: timerchannel.duty_cycle([value])
Get or set the duty cycle of the PWM signal. It's a percentage (0.00-100.00). Since the WiPy
doesn't support floating point numbers the duty cycle must be specified in the range 0-10000,
where 10000 would represent 100.00, 5050 represents 50.50, and so on.
Constants
---------
.. data:: TimerWiPy.ONE_SHOT
.. data:: TimerWiPy.PERIODIC
Timer operating mode.