diff options
Diffstat (limited to 'docs')
59 files changed, 963 insertions, 569 deletions
diff --git a/docs/conf.py b/docs/conf.py index 8fb53e890c..a8df373150 100755 --- a/docs/conf.py +++ b/docs/conf.py @@ -96,10 +96,9 @@ copyright = '2014-2017, Damien P. George, Paul Sokolovsky, and contributors' # |version| and |release|, also used in various other places throughout the # built documents. # -# The short X.Y version. -version = '1.9' -# The full version, including alpha/beta/rc tags. -release = '1.9.1' +# We don't follow "The short X.Y version" vs "The full version, including alpha/beta/rc tags" +# breakdown, so use the same version identifier for both to avoid confusion. +version = release = '1.9.2' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -113,11 +112,11 @@ release = '1.9.1' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ['build'] +exclude_patterns = ['build', '.venv'] # The reST default role (used for this markup: `text`) to use for all # documents. -#default_role = None +default_role = 'any' # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True @@ -139,6 +138,12 @@ pygments_style = 'sphinx' # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False +# Global include files. Sphinx docs suggest using rst_epilog in preference +# of rst_prolog, so we follow. Absolute paths below mean "from the base +# of the doctree". +rst_epilog = """ +.. include:: /templates/replace.inc +""" # -- Options for HTML output ---------------------------------------------- @@ -246,6 +251,8 @@ latex_elements = { # Additional stuff for the LaTeX preamble. #'preamble': '', +# Include 3 levels of headers in PDF ToC +'preamble': '\setcounter{tocdepth}{2}', } # Grouping the document tree into LaTeX files. List of tuples @@ -315,7 +322,7 @@ texinfo_documents = [ # Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = {'http://docs.python.org/': None} +intersphinx_mapping = {'python': ('http://docs.python.org/3', None)} # Append the other ports' specific folders/files to the exclude pattern exclude_patterns.extend([port + '*' for port in ports if port != micropy_port]) diff --git a/docs/differences/index_template.txt b/docs/differences/index_template.txt index 6ade2c2dab..eb8b3ba640 100644 --- a/docs/differences/index_template.txt +++ b/docs/differences/index_template.txt @@ -1,4 +1,6 @@ -MicroPython Differences from CPython +.. _cpython_diffs: + +MicroPython differences from CPython ==================================== The operations listed in this section produce conflicting results in MicroPython when compared to standard Python. diff --git a/docs/esp8266/general.rst b/docs/esp8266/general.rst index 47df80d7ba..e23acb469b 100644 --- a/docs/esp8266/general.rst +++ b/docs/esp8266/general.rst @@ -116,9 +116,32 @@ Real-time clock RTC in ESP8266 has very bad accuracy, drift may be seconds per minute. As a workaround, to measure short enough intervals you can use ``utime.time()``, etc. functions, and for wall clock time, synchronize from -the net using included ``ntpdate.py`` module. +the net using included ``ntptime.py`` module. Due to limitations of the ESP8266 chip the internal real-time clock (RTC) will overflow every 7:45h. If a long-term working RTC time is required then ``time()`` or ``localtime()`` must be called at least once within 7 hours. MicroPython will then handle the overflow. + +Sockets and WiFi buffers overflow +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Socket instances remain active until they are explicitly closed. This has two +consequences. Firstly they occupy RAM, so an application which opens sockets +without closing them may eventually run out of memory. Secondly not properly +closed socket can cause the low-level part of the vendor WiFi stack to emit +``Lmac`` errors. This occurs if data comes in for a socket and is not +processed in a timely manner. This can overflow the WiFi stack input queue +and lead to a deadlock. The only recovery is by a hard reset. + +The above may also happen after an application terminates and quits to the REPL +for any reason including an exception. Subsequent arrival of data provokes the +failure with the above error message repeatedly issued. So, sockets should be +closed in any case, regardless whether an application terminates successfully +or by an exeption, for example using try/finally:: + + sock = socket(...) + try: + # Use sock + finally: + sock.close() diff --git a/docs/esp8266/tutorial/intro.rst b/docs/esp8266/tutorial/intro.rst index 67ed0ba67c..711db3fceb 100644 --- a/docs/esp8266/tutorial/intro.rst +++ b/docs/esp8266/tutorial/intro.rst @@ -50,12 +50,16 @@ From here, you have 3 main choices * Daily firmware builds for 1024kb modules and above. * Daily firmware builds for 512kb modules. -The best bet is nearly always to go for the Stable firmware builds. -An exception to this though is if you have an ESP8266 module with only 512kb -of onboard storage. You can easily tell by trying to load a Stable firmware -build and if you get the error below, then you may have to use the Daily -firmware builds for 512kb modules. - WARNING: Unlikely to work as data goes beyond end of flash. +If you are just starting with MicroPython, the best bet is to go for the Stable +firmware builds. If you are an advanced, experienced MicroPython ESP8266 user +who would like to follow development closely and help with testing new +features, there are daily builds (note: you actually may need some +development experience, e.g. being ready to follow git history to know +what new changes and features were introduced). + +Support for 512kb modules is provided on a feature preview basis. For end +users, it's recommended to use modules with flash of 1024kb or more. As +such, only daily builds for 512kb modules are provided. Deploying the firmware ---------------------- @@ -161,7 +165,9 @@ after it, here are troubleshooting recommendations: * If lower baud rate didn't help, you may want to try older version of esptool.py, which had a different programming algorithm:: + pip install esptool==1.0.1 + This version doesn't support ``--flash_size=detect`` option, so you will need to specify FlashROM size explicitly (in megabits). It also requires Python 2.7, so you may need to use ``pip2`` instead of ``pip`` in the @@ -176,8 +182,10 @@ after it, here are troubleshooting recommendations: * Additionally, you can check the firmware integrity from a MicroPython REPL prompt (assuming you were able to flash it and ``--verify`` option doesn't report errors):: + import esp esp.check_fw() + If the last output value is True, the firmware is OK. Otherwise, it's corrupted and need to be reflashed correctly. diff --git a/docs/esp8266/tutorial/powerctrl.rst b/docs/esp8266/tutorial/powerctrl.rst index 9e44339c86..3502624ab5 100644 --- a/docs/esp8266/tutorial/powerctrl.rst +++ b/docs/esp8266/tutorial/powerctrl.rst @@ -22,7 +22,7 @@ processing power, at the expense of current consumption:: 160000000 You can change to the higher frequency just while your code does the heavy -processing and then change back when its finished. +processing and then change back when it's finished. Deep-sleep mode --------------- diff --git a/docs/esp8266_contents.rst b/docs/esp8266_contents.rst deleted file mode 100644 index 7c35460bd9..0000000000 --- a/docs/esp8266_contents.rst +++ /dev/null @@ -1,12 +0,0 @@ -MicroPython documentation contents -================================== - -.. toctree:: - - esp8266/quickref.rst - esp8266/general.rst - esp8266/tutorial/index.rst - library/index.rst - reference/index.rst - genrst/index.rst - license.rst diff --git a/docs/esp8266_index.rst b/docs/esp8266_index.rst index 8654c43aa0..519acecda5 100644 --- a/docs/esp8266_index.rst +++ b/docs/esp8266_index.rst @@ -4,14 +4,9 @@ MicroPython documentation and references .. toctree:: esp8266/quickref.rst + esp8266/general.rst + esp8266/tutorial/index.rst library/index.rst + reference/index.rst genrst/index.rst license.rst - esp8266_contents.rst - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` diff --git a/docs/library/array.rst b/docs/library/array.rst index f52b4b385e..d096c6ec48 100644 --- a/docs/library/array.rst +++ b/docs/library/array.rst @@ -4,8 +4,7 @@ .. module:: array :synopsis: efficient arrays of numeric data -See `Python array <https://docs.python.org/3/library/array.html>`_ for more -information. +|see_cpython_module| :mod:`python:array`. Supported format codes: ``b``, ``B``, ``h``, ``H``, ``i``, ``I``, ``l``, ``L``, ``q``, ``Q``, ``f``, ``d`` (the latter 2 depending on the diff --git a/docs/library/btree.rst b/docs/library/btree.rst index bd7890586a..9322d32e6a 100644 --- a/docs/library/btree.rst +++ b/docs/library/btree.rst @@ -22,8 +22,14 @@ Example:: # First, we need to open a stream which holds a database # This is usually a file, but can be in-memory database - # using uio.BytesIO, a raw flash section, etc. - f = open("mydb", "w+b") + # using uio.BytesIO, a raw flash partition, etc. + # Oftentimes, you want to create a database file if it doesn't + # exist and open if it exists. Idiom below takes care of this. + # DO NOT open database with "a+b" access mode. + try: + f = open("mydb", "r+b") + except OSError: + f = open("mydb", "w+b") # Now open a database itself db = btree.open(f) @@ -33,6 +39,11 @@ Example:: db[b"1"] = b"one" db[b"2"] = b"two" + # Assume that any changes are cached in memory unless + # explicitly flushed (or database closed). Flush database + # at the end of each "transaction". + db.flush() + # Prints b'two' print(db[b"2"]) @@ -71,18 +82,18 @@ Functions other parameters are optional and keyword-only, and allow to tweak advanced parameters of the database operation (most users will not need them): - * `flags` - Currently unused. - * `cachesize` - Suggested maximum memory cache size in bytes. For a + * *flags* - Currently unused. + * *cachesize* - Suggested maximum memory cache size in bytes. For a board with enough memory using larger values may improve performance. The value is only a recommendation, the module may use more memory if values set too low. - * `pagesize` - Page size used for the nodes in BTree. Acceptable range + * *pagesize* - Page size used for the nodes in BTree. Acceptable range is 512-65536. If 0, underlying I/O block size will be used (the best compromise between memory usage and performance). - * `minkeypage` - Minimum number of keys to store per page. Default value + * *minkeypage* - Minimum number of keys to store per page. Default value of 0 equivalent to 2. - Returns a `BTree` object, which implements a dictionary protocol (set + Returns a BTree object, which implements a dictionary protocol (set of methods), and some additional methods described below. Methods @@ -92,7 +103,7 @@ Methods Close the database. It's mandatory to close the database at the end of processing, as some unwritten data may be still in the cache. Note that - this does not close underlying streamw with which the database was opened, + this does not close underlying stream with which the database was opened, it should be closed separately (which is also mandatory to make sure that data flushed from buffer to the underlying storage). @@ -101,10 +112,10 @@ Methods Flush any data in cache to the underlying stream. .. method:: btree.__getitem__(key) -.. method:: btree.get(key, default=None) -.. method:: btree.__setitem__(key, val) -.. method:: btree.__detitem__(key) -.. method:: btree.__contains__(key) + btree.get(key, default=None) + btree.__setitem__(key, val) + btree.__detitem__(key) + btree.__contains__(key) Standard dictionary methods. @@ -114,20 +125,20 @@ Methods to get access to all keys in order. .. method:: btree.keys([start_key, [end_key, [flags]]]) -.. method:: btree.values([start_key, [end_key, [flags]]]) -.. method:: btree.items([start_key, [end_key, [flags]]]) + btree.values([start_key, [end_key, [flags]]]) + btree.items([start_key, [end_key, [flags]]]) These methods are similar to standard dictionary methods, but also can take optional parameters to iterate over a key sub-range, instead of - the entire database. Note that for all 3 methods, `start_key` and - `end_key` arguments represent key values. For example, ``values()`` + the entire database. Note that for all 3 methods, *start_key* and + *end_key* arguments represent key values. For example, `values()` method will iterate over values corresponding to they key range - given. None values for `start_key` means "from the first key", no - `end_key` or its value of None means "until the end of database". - By default, range is inclusive of `start_key` and exclusive of - `end_key`, you can include `end_key` in iteration by passing `flags` + given. None values for *start_key* means "from the first key", no + *end_key* or its value of None means "until the end of database". + By default, range is inclusive of *start_key* and exclusive of + *end_key*, you can include *end_key* in iteration by passing *flags* of `btree.INCL`. You can iterate in descending key direction - by passing `flags` of `btree.DESC`. The flags values can be ORed + by passing *flags* of `btree.DESC`. The flags values can be ORed together. Constants diff --git a/docs/library/builtins.rst b/docs/library/builtins.rst index 46f762660a..365248dc76 100644 --- a/docs/library/builtins.rst +++ b/docs/library/builtins.rst @@ -1,8 +1,11 @@ -Builtin Functions -================= +Builtin functions and exceptions +================================ -All builtin functions are described here. They are also available via -``builtins`` module. +All builtin functions and exceptions are described here. They are also +available via ``builtins`` module. + +Functions and types +------------------- .. function:: abs() @@ -18,6 +21,8 @@ All builtin functions are described here. They are also available via .. class:: bytes() + |see_cpython| `python:bytes`. + .. function:: callable() .. function:: chr() @@ -144,3 +149,51 @@ All builtin functions are described here. They are also available via .. function:: type() .. function:: zip() + + +Exceptions +---------- + +.. exception:: AssertionError + +.. exception:: AttributeError + +.. exception:: Exception + +.. exception:: ImportError + +.. exception:: IndexError + +.. exception:: KeyboardInterrupt + +.. exception:: KeyError + +.. exception:: MemoryError + +.. exception:: NameError + +.. exception:: NotImplementedError + +.. exception:: OSError + + |see_cpython| `python:OSError`. MicroPython doesn't implement ``errno`` + attribute, instead use the standard way to access exception arguments: + ``exc.args[0]``. + +.. exception:: RuntimeError + +.. exception:: StopIteration + +.. exception:: SyntaxError + +.. exception:: SystemExit + + |see_cpython| `python:SystemExit`. + +.. exception:: TypeError + + |see_cpython| `python:TypeError`. + +.. exception:: ValueError + +.. exception:: ZeroDivisionError diff --git a/docs/library/cmath.rst b/docs/library/cmath.rst index 465cf54ad3..59e4ec1722 100644 --- a/docs/library/cmath.rst +++ b/docs/library/cmath.rst @@ -4,6 +4,8 @@ .. module:: cmath :synopsis: mathematical functions for complex numbers +|see_cpython_module| :mod:`python:cmath`. + The ``cmath`` module provides some basic mathematical functions for working with complex numbers. diff --git a/docs/library/esp.rst b/docs/library/esp.rst index 8cafb92cd0..121a80d42e 100644 --- a/docs/library/esp.rst +++ b/docs/library/esp.rst @@ -14,7 +14,7 @@ Functions Get or set the sleep type. - If the ``sleep_type`` parameter is provided, sets the sleep type to its + If the *sleep_type* parameter is provided, sets the sleep type to its value. If the function is called without parameters, returns the current sleep type. @@ -55,23 +55,23 @@ Functions 1MByte of flash (which is memory mapped), and this function controls the location. - If `start` and `length` are both `None` then the native code location is + If *start* and *length* are both ``None`` then the native code location is set to the unused portion of memory at the end of the iRAM1 region. The size of this unused portion depends on the firmware and is typically quite small (around 500 bytes), and is enough to store a few very small functions. The advantage of using this iRAM1 region is that it does not get worn out by writing to it. - If neither `start` nor `length` are `None` then they should be integers. - `start` should specify the byte offset from the beginning of the flash at - which native code should be stored. `length` specifies how many bytes of - flash from `start` can be used to store native code. `start` and `length` + If neither *start* nor *length* are ``None`` then they should be integers. + *start* should specify the byte offset from the beginning of the flash at + which native code should be stored. *length* specifies how many bytes of + flash from *start* can be used to store native code. *start* and *length* should be multiples of the sector size (being 4096 bytes). The flash will be automatically erased before writing to it so be sure to use a region of flash that is not otherwise used, for example by the firmware or the filesystem. - When using the flash to store native code `start+length` must be less + When using the flash to store native code *start+length* must be less than or equal to 1MByte. Note that the flash can be worn out if repeated erasures (and writes) are made so use this feature sparingly. In particular, native code needs to be recompiled and rewritten to flash diff --git a/docs/library/framebuf.rst b/docs/library/framebuf.rst index 61f0635f36..b92bd08eff 100644 --- a/docs/library/framebuf.rst +++ b/docs/library/framebuf.rst @@ -32,25 +32,25 @@ Constructors Construct a FrameBuffer object. The parameters are: - - `buffer` is an object with a buffer protocol which must be large + - *buffer* is an object with a buffer protocol which must be large enough to contain every pixel defined by the width, height and format of the FrameBuffer. - - `width` is the width of the FrameBuffer in pixels - - `height` is the height of the FrameBuffer in pixels - - `format` specifies the type of pixel used in the FrameBuffer; + - *width* is the width of the FrameBuffer in pixels + - *height* is the height of the FrameBuffer in pixels + - *format* specifies the type of pixel used in the FrameBuffer; valid values are ``framebuf.MVLSB``, ``framebuf.RGB565`` and ``framebuf.GS4_HMSB``. MVLSB is monochrome 1-bit color, RGB565 is RGB 16-bit color, and GS4_HMSB is grayscale 4-bit color. Where a color value c is passed to a method, c is a small integer with an encoding that is dependent on the format of the FrameBuffer. - - `stride` is the number of pixels between each horizontal line - of pixels in the FrameBuffer. This defaults to `width` but may + - *stride* is the number of pixels between each horizontal line + of pixels in the FrameBuffer. This defaults to *width* but may need adjustments when implementing a FrameBuffer within another - larger FrameBuffer or screen. The `buffer` size must accommodate + larger FrameBuffer or screen. The *buffer* size must accommodate an increased step size. - One must specify valid `buffer`, `width`, `height`, `format` and - optionally `stride`. Invalid `buffer` size or dimensions may lead to + One must specify valid *buffer*, *width*, *height*, *format* and + optionally *stride*. Invalid *buffer* size or dimensions may lead to unexpected errors. Drawing primitive shapes @@ -64,8 +64,8 @@ The following methods draw shapes onto the FrameBuffer. .. method:: FrameBuffer.pixel(x, y[, c]) - If `c` is not given, get the color value of the specified pixel. - If `c` is given, set the specified pixel to the given color. + If *c* is not given, get the color value of the specified pixel. + If *c* is given, set the specified pixel to the given color. .. method:: FrameBuffer.hline(x, y, w, c) .. method:: FrameBuffer.vline(x, y, h, c) @@ -106,7 +106,7 @@ Other methods .. method:: FrameBuffer.blit(fbuf, x, y[, key]) Draw another FrameBuffer on top of the current one at the given coordinates. - If `key` is specified then it should be a color integer and the + If *key* is specified then it should be a color integer and the corresponding color will be considered transparent: all pixels with that color value will not be drawn. diff --git a/docs/library/gc.rst b/docs/library/gc.rst index 01e63ae51e..c823aed3e6 100644 --- a/docs/library/gc.rst +++ b/docs/library/gc.rst @@ -4,6 +4,8 @@ .. module:: gc :synopsis: control the garbage collector +|see_cpython_module| :mod:`python:gc`. + Functions --------- @@ -24,6 +26,41 @@ Functions Return the number of bytes of heap RAM that are allocated. + .. admonition:: Difference to CPython + :class: attention + + This function is MicroPython extension. + .. function:: mem_free() - Return the number of bytes of available heap RAM. + Return the number of bytes of available heap RAM, or -1 if this amount + is not known. + + .. admonition:: Difference to CPython + :class: attention + + This function is MicroPython extension. + +.. function:: threshold([amount]) + + Set or query the additional GC allocation threshold. Normally, a collection + is triggered only when a new allocation cannot be satisfied, i.e. on an + out-of-memory (OOM) condition. If this function is called, in addition to + OOM, a collection will be triggered each time after *amount* bytes have been + allocated (in total, since the previous time such an amount of bytes + have been allocated). *amount* is usually specified as less than the + full heap size, with the intention to trigger a collection earlier than when the + heap becomes exhausted, and in the hope that an early collection will prevent + excessive memory fragmentation. This is a heuristic measure, the effect + of which will vary from application to application, as well as + the optimal value of the *amount* parameter. + + Calling the function without argument will return the current value of + the threshold. A value of -1 means a disabled allocation threshold. + + .. admonition:: Difference to CPython + :class: attention + + This function is a MicroPython extension. CPython has a similar + function - ``set_threshold()``, but due to different GC + implementations, its signature and semantics are different. diff --git a/docs/library/index.rst b/docs/library/index.rst index 770920a1ff..0789ea43d9 100644 --- a/docs/library/index.rst +++ b/docs/library/index.rst @@ -1,3 +1,5 @@ +.. _micropython_lib: + MicroPython libraries ===================== @@ -38,8 +40,7 @@ information pertaining to a specific port. 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 the `micropython-lib repository -<https://github.com/micropython/micropython-lib>`_. +extensions to it, can be found in `micropython-lib`. Python standard libraries and micro-libraries --------------------------------------------- @@ -52,7 +53,7 @@ e.g. ``ujson`` instead of ``json``. This is to signify that such a module is micro-library, i.e. implements only a subset of CPython module functionality. By naming them differently, a user has a choice to write a Python-level module to extend functionality for better compatibility with CPython (indeed, this is -what done by micropython-lib project mentioned above). +what done by the `micropython-lib` project mentioned above). On some embedded platforms, where it may be cumbersome to add Python-level wrapper modules to achieve naming compatibility with CPython, micro-modules @@ -72,16 +73,17 @@ it will fallback to loading the built-in ``ujson`` module. cmath.rst gc.rst math.rst - select.rst sys.rst ubinascii.rst ucollections.rst + uerrno.rst uhashlib.rst uheapq.rst uio.rst ujson.rst uos.rst ure.rst + uselect.rst usocket.rst ustruct.rst utime.rst @@ -97,16 +99,17 @@ it will fallback to loading the built-in ``ujson`` module. cmath.rst gc.rst math.rst - select.rst sys.rst ubinascii.rst ucollections.rst + uerrno.rst uhashlib.rst uheapq.rst uio.rst ujson.rst uos.rst ure.rst + uselect.rst usocket.rst ustruct.rst utime.rst @@ -120,12 +123,12 @@ it will fallback to loading the built-in ``ujson`` module. builtins.rst array.rst gc.rst - select.rst sys.rst ubinascii.rst ujson.rst uos.rst ure.rst + uselect.rst usocket.rst ussl.rst utime.rst @@ -142,12 +145,14 @@ it will fallback to loading the built-in ``ujson`` module. sys.rst ubinascii.rst ucollections.rst + uerrno.rst uhashlib.rst uheapq.rst uio.rst ujson.rst uos.rst ure.rst + uselect.rst usocket.rst ussl.rst ustruct.rst diff --git a/docs/library/lcd160cr.rst b/docs/library/lcd160cr.rst index bd47412986..567994640b 100644 --- a/docs/library/lcd160cr.rst +++ b/docs/library/lcd160cr.rst @@ -41,21 +41,21 @@ Constructors Construct an LCD160CR object. The parameters are: - - `connect` is a string specifying the physical connection of the LCD + - *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 (ie they are `None`) will be created based on the - value of `connect`. This allows to override the default interface to the + - *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: @@ -103,12 +103,12 @@ 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. + 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 + Set the orientation of the display. The *orient* parameter can be one of `PORTRAIT`, `LANDSCAPE`, `PORTRAIT_UPSIDEDOWN`, `LANDSCAPE_UPSIDEDOWN`. .. method:: LCD160CR.set_brightness(value) @@ -117,7 +117,7 @@ Setup commands .. method:: LCD160CR.set_i2c_addr(addr) - Set the I2C address of the display. The `addr` value must have the + Set the I2C address of the display. The *addr* value must have the lower 2 bits cleared. .. method:: LCD160CR.set_uart_baudrate(baudrate) @@ -126,7 +126,7 @@ Setup commands .. method:: LCD160CR.set_startup_deco(value) - Set the start-up decoration of the display. The `value` parameter can be a + 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() @@ -151,17 +151,17 @@ The following methods manipulate individual pixels on the display. .. 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 + 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)`. + 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 + 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) @@ -188,18 +188,18 @@ To draw text one sets the position, color and font, and then uses 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 + - *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 + - *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 + 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 + - *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 + - *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) @@ -252,7 +252,7 @@ Primitive drawing commands use a foreground and background color set by the .. 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 + 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) @@ -266,25 +266,25 @@ Touch screen methods Configure the touch panel: - - If `calib` is `True` then the call will trigger a touch calibration of + - 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 + - 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 + - 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, + 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 + 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 @@ -308,7 +308,7 @@ Advanced commands .. method:: LCD160CR.show_framebuf(buf) - Show the given buffer on the display. `buf` should be an array of bytes containing + 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. @@ -325,35 +325,35 @@ Advanced commands Configure a window region for scrolling: - - `win` is the window id to configure. There are 0..7 standard windows for + - *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. + - *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 + - *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. + - *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 + 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 + 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`. @@ -380,15 +380,15 @@ Constants --------- .. data:: lcd160cr.PORTRAIT -.. data:: lcd160cr.LANDSCAPE -.. data:: lcd160cr.PORTRAIT_UPSIDEDOWN -.. data:: lcd160cr.LANDSCAPE_UPSIDEDOWN + lcd160cr.LANDSCAPE + lcd160cr.PORTRAIT_UPSIDEDOWN + lcd160cr.LANDSCAPE_UPSIDEDOWN - orientation of the display, used by :meth:`LCD160CR.set_orient` + Orientations of the display, used by :meth:`LCD160CR.set_orient`. .. data:: lcd160cr.STARTUP_DECO_NONE -.. data:: lcd160cr.STARTUP_DECO_MLOGO -.. data:: lcd160cr.STARTUP_DECO_INFO + lcd160cr.STARTUP_DECO_MLOGO + lcd160cr.STARTUP_DECO_INFO - type of start-up decoration, can be or'd together, used by - :meth:`LCD160CR.set_startup_deco` + Types of start-up decoration, can be OR'ed together, used by + :meth:`LCD160CR.set_startup_deco`. diff --git a/docs/library/machine.I2C.rst b/docs/library/machine.I2C.rst index a1b4178905..a69c58999f 100644 --- a/docs/library/machine.I2C.rst +++ b/docs/library/machine.I2C.rst @@ -37,16 +37,16 @@ Constructors Construct and return a new I2C object using the following parameters: - - `id` identifies the particular I2C peripheral. The default + - *id* identifies a particular I2C peripheral. The default value of -1 selects a software implementation of I2C which can work (in most cases) with arbitrary pins for SCL and SDA. - If `id` is -1 then `scl` and `sda` must be specified. Other - allowed values for `id` depend on the particular port/board, - and specifying `scl` and `sda` may or may not be required or + If *id* is -1 then *scl* and *sda* must be specified. Other + allowed values for *id* depend on the particular port/board, + and specifying *scl* and *sda* may or may not be required or allowed in this case. - - `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 + - *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. General Methods @@ -56,9 +56,9 @@ General Methods 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 + - *scl* is a pin object for the SCL line + - *sda* is a pin object for the SDA line + - *freq* is the SCL clock rate .. method:: I2C.deinit() @@ -93,9 +93,9 @@ control over the bus, otherwise the standard methods (see below) can be used. .. 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` + 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 slave assumes more bytes are going to be read in a later call). @@ -103,7 +103,7 @@ control over the bus, otherwise the standard methods (see below) can be used. .. method:: I2C.write(buf) - Write the bytes from `buf` to the bus. Checks that an ACK is received + 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. @@ -117,23 +117,23 @@ operations that target a given slave device. .. method:: I2C.readfrom(addr, nbytes, stop=True) - Read `nbytes` from the slave specified by `addr`. - If `stop` is true then a STOP condition is generated at the end of the transfer. + Read *nbytes* from the slave 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 slave 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. + Read into *buf* from the slave 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`. + The method returns ``None``. .. method:: I2C.writeto(addr, buf, stop=True) - Write the bytes from `buf` to the slave 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 + Write the bytes from *buf* to the slave 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. @@ -147,26 +147,26 @@ methods are convenience functions to communicate with such devices. .. method:: I2C.readfrom_mem(addr, memaddr, nbytes, \*, addrsize=8) - Read `nbytes` from the slave specified by `addr` starting from the memory - address specified by `memaddr`. - The argument `addrsize` specifies the address size in bits. + Read *nbytes* from the slave 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 slave 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 + Read into *buf* from the slave 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`. + The method returns ``None``. .. method:: I2C.writeto_mem(addr, memaddr, buf, \*, addrsize=8) - Write `buf` to the slave specified by `addr` starting from the - memory address specified by `memaddr`. - The argument `addrsize` specifies the address size in bits (on ESP8266 + Write *buf* to the slave 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`. + The method returns ``None``. diff --git a/docs/library/machine.RTC.rst b/docs/library/machine.RTC.rst index 2a53b91469..95fa2b4ce6 100644 --- a/docs/library/machine.RTC.rst +++ b/docs/library/machine.RTC.rst @@ -38,7 +38,7 @@ Methods Resets the RTC to the time of January 1, 2015 and starts running it again. -.. method:: RTC.alarm(id, time, /*, repeat=False) +.. 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 diff --git a/docs/library/machine.UART.rst b/docs/library/machine.UART.rst index 64ff28e1ab..983ef0a947 100644 --- a/docs/library/machine.UART.rst +++ b/docs/library/machine.UART.rst @@ -18,7 +18,7 @@ UART objects can be created and initialised using:: Supported parameters differ on a board: -Pyboard: Bits can be 7, 8 or 9. Stop can be 1 or 2. With `parity=None`, +Pyboard: Bits can be 7, 8 or 9. Stop can be 1 or 2. With *parity=None*, only 8 and 9 bits are supported. With parity enabled, only 7 and 8 bits are supported. diff --git a/docs/library/machine.rst b/docs/library/machine.rst index 7ea7f565e7..087f19cc6c 100644 --- a/docs/library/machine.rst +++ b/docs/library/machine.rst @@ -13,7 +13,7 @@ damage. .. _machine_callbacks: -A note of callbacks used by functions and class methods of ``machine`` module: +A note of callbacks used by functions and class methods of :mod:`machine` module: all these callbacks should be considered as executing in an interrupt context. This is true for both physical devices with IDs >= 0 and "virtual" devices with negative IDs like -1 (these "virtual" devices are still thin shims on @@ -38,14 +38,14 @@ Interrupt related functions Disable interrupt requests. Returns the previous IRQ state which should be considered an opaque value. - This return value should be passed to the ``enable_irq`` function to restore - interrupts to their original state, before ``disable_irq`` was called. + This return value should be passed to the `enable_irq()` function to restore + interrupts to their original state, before `disable_irq()` was called. .. function:: enable_irq(state) Re-enable interrupt requests. - The ``state`` parameter should be the value that was returned from the most - recent call to the ``disable_irq`` function. + The *state* parameter should be the value that was returned from the most + recent call to the `disable_irq()` function. Power related functions ----------------------- @@ -71,8 +71,8 @@ Power related functions Stops the CPU and all peripherals (including networking interfaces, if any). Execution is resumed from the main script, just as with a reset. The reset cause can be checked - to know that we are coming from ``machine.DEEPSLEEP``. For wake up to actually happen, - wake sources should be configured first, like ``Pin`` change or ``RTC`` timeout. + to know that we are coming from `machine.DEEPSLEEP`. For wake up to actually happen, + wake sources should be configured first, like `Pin` change or `RTC` timeout. .. only:: port_wipy @@ -98,18 +98,18 @@ Miscellaneous functions .. function:: time_pulse_us(pin, pulse_level, timeout_us=1000000) - Time a pulse on the given `pin`, and return the duration of the pulse in - microseconds. The `pulse_level` argument should be 0 to time a low pulse + Time a pulse on the given *pin*, and return the duration of the pulse in + microseconds. The *pulse_level* argument should be 0 to time a low pulse or 1 to time a high pulse. - If the current input value of the pin is different to `pulse_level`, - the function first (*) waits until the pin input becomes equal to `pulse_level`, - then (**) times the duration that the pin is equal to `pulse_level`. - If the pin is already equal to `pulse_level` then timing starts straight away. + If the current input value of the pin is different to *pulse_level*, + the function first (*) waits until the pin input becomes equal to *pulse_level*, + then (**) times the duration that the pin is equal to *pulse_level*. + If the pin is already equal to *pulse_level* then timing starts straight away. The function will return -2 if there was timeout waiting for condition marked (*) above, and -1 if there was timeout during the main measurement, marked (**) - above. The timeout is the same for both cases and given by `timeout_us` (which + above. The timeout is the same for both cases and given by *timeout_us* (which is in microseconds). .. _machine_constants: diff --git a/docs/library/math.rst b/docs/library/math.rst index 9d5cf7b4ba..a6f13d48c1 100644 --- a/docs/library/math.rst +++ b/docs/library/math.rst @@ -4,6 +4,8 @@ .. module:: math :synopsis: mathematical functions +|see_cpython_module| :mod:`python:math`. + The ``math`` module provides some basic mathematical functions for working with floating-point numbers. diff --git a/docs/library/micropython.rst b/docs/library/micropython.rst index 7f40028565..4ff0b0c159 100644 --- a/docs/library/micropython.rst +++ b/docs/library/micropython.rst @@ -23,30 +23,30 @@ Functions variable, and does not take up any memory during execution. This `const` function is recognised directly by the MicroPython parser and is - provided as part of the `micropython` module mainly so that scripts can be + provided as part of the :mod:`micropython` module mainly so that scripts can be written which run under both CPython and MicroPython, by following the above pattern. .. function:: opt_level([level]) - If `level` is given then this function sets the optimisation level for subsequent - compilation of scripts, and returns `None`. Otherwise it returns the current + If *level* is given then this function sets the optimisation level for subsequent + compilation of scripts, and returns ``None``. Otherwise it returns the current optimisation level. .. function:: alloc_emergency_exception_buf(size) - Allocate ``size`` bytes of RAM for the emergency exception buffer (a good + Allocate *size* bytes of RAM for the emergency exception buffer (a good size is around 100 bytes). The buffer is used to create exceptions in cases when normal RAM allocation would fail (eg within an interrupt handler) and therefore give useful traceback information in these situations. A good way to use this function is to put it at the start of your main script - (eg boot.py or main.py) and then the emergency exception buffer will be active + (eg ``boot.py`` or ``main.py``) and then the emergency exception buffer will be active for all the code following it. .. function:: mem_info([verbose]) - Print information about currently used memory. If the ``verbose`` argument + Print information about currently used memory. If the *verbose`* argument is given then extra information is printed. The information that is printed is implementation dependent, but currently @@ -55,7 +55,7 @@ Functions .. function:: qstr_info([verbose]) - Print information about currently interned strings. If the ``verbose`` + Print information about currently interned strings. If the *verbose* argument is given then extra information is printed. The information that is printed is implementation dependent, but currently @@ -89,10 +89,10 @@ Functions incoming stream of characters that is usually used for the REPL, in case that stream is used for other purposes. -.. function:: schedule(fun, arg) +.. function:: schedule(func, arg) - Schedule the function `fun` to be executed "very soon". The function - is passed the value `arg` as its single argument. "very soon" means that + Schedule the function *func* to be executed "very soon". The function + is passed the value *arg* as its single argument. "Very soon" means that the MicroPython runtime will do its best to execute the function at the earliest possible time, given that it is also trying to be efficient, and that the following conditions hold: diff --git a/docs/library/network.rst b/docs/library/network.rst index 27fa0dcb2f..de93c0e01d 100644 --- a/docs/library/network.rst +++ b/docs/library/network.rst @@ -72,7 +72,7 @@ parameter should be `id`. connection parameters. For various medium types, there are different sets of predefined/recommended parameters, among them: - * WiFi: `bssid` keyword to connect by BSSID (MAC address) instead + * WiFi: *bssid* keyword to connect by BSSID (MAC address) instead of access point name .. method:: disconnect() @@ -118,7 +118,7 @@ parameter should be `id`. Get or set general network interface parameters. These methods allow to work with additional parameters beyond standard IP configuration (as dealt with by - ``ifconfig()``). These include network-specific and hardware-specific + `ifconfig()`). These include network-specific and hardware-specific parameters and status values. For setting parameters, the keyword argument syntax should be used, and multiple parameters can be set at once. For querying, a parameter name should be quoted as a string, and only one @@ -170,11 +170,11 @@ parameter should be `id`. Arguments are: - - ``spi`` is an :ref:`SPI object <pyb.SPI>` which is the SPI bus that the CC3000 is + - *spi* is an :ref:`SPI object <pyb.SPI>` which is the SPI bus that the CC3000 is connected to (the MOSI, MISO and CLK pins). - - ``pin_cs`` is a :ref:`Pin object <pyb.Pin>` which is connected to the CC3000 CS pin. - - ``pin_en`` is a :ref:`Pin object <pyb.Pin>` which is connected to the CC3000 VBEN pin. - - ``pin_irq`` is a :ref:`Pin object <pyb.Pin>` which is connected to the CC3000 IRQ pin. + - *pin_cs* is a :ref:`Pin object <pyb.Pin>` which is connected to the CC3000 CS pin. + - *pin_en* is a :ref:`Pin object <pyb.Pin>` which is connected to the CC3000 VBEN pin. + - *pin_irq* is a :ref:`Pin object <pyb.Pin>` which is connected to the CC3000 IRQ pin. All of these objects will be initialised by the driver, so there is no need to initialise them yourself. For example, you can use:: @@ -256,10 +256,10 @@ parameter should be `id`. Arguments are: - - ``spi`` is an :ref:`SPI object <pyb.SPI>` which is the SPI bus that the WIZnet5x00 is + - *spi* is an :ref:`SPI object <pyb.SPI>` which is the SPI bus that the WIZnet5x00 is connected to (the MOSI, MISO and SCLK pins). - - ``pin_cs`` is a :ref:`Pin object <pyb.Pin>` which is connected to the WIZnet5x00 nSS pin. - - ``pin_rst`` is a :ref:`Pin object <pyb.Pin>` which is connected to the WIZnet5x00 nRESET pin. + - *pin_cs* is a :ref:`Pin object <pyb.Pin>` which is connected to the WIZnet5x00 nSS pin. + - *pin_rst* is a :ref:`Pin object <pyb.Pin>` which is connected to the WIZnet5x00 nRESET pin. All of these objects will be initialised by the driver, so there is no need to initialise them yourself. For example, you can use:: @@ -294,7 +294,7 @@ parameter should be `id`. Get or set the PHY mode. - If the ``mode`` parameter is provided, sets the mode to its value. If + If the *mode* parameter is provided, sets the mode to its value. If the function is called without parameters, returns the current mode. The possible modes are defined as constants: @@ -322,7 +322,7 @@ parameter should be `id`. ``network.STA_IF`` (station aka client, connects to upstream WiFi access points) and ``network.AP_IF`` (access point, allows other WiFi clients to connect). Availability of the methods below depends on interface type. - For example, only STA interface may ``connect()`` to an access point. + For example, only STA interface may `connect()` to an access point. Methods ------- @@ -350,8 +350,8 @@ parameter should be `id`. (ssid, bssid, channel, RSSI, authmode, hidden) - `bssid` is hardware address of an access point, in binary form, returned as - bytes object. You can use ``ubinascii.hexlify()`` to convert it to ASCII form. + *bssid* is hardware address of an access point, in binary form, returned as + bytes object. You can use `ubinascii.hexlify()` to convert it to ASCII form. There are five values for authmode: @@ -399,7 +399,7 @@ parameter should be `id`. Get or set general network interface parameters. These methods allow to work with additional parameters beyond standard IP configuration (as dealt with by - ``wlan.ifconfig()``). These include network-specific and hardware-specific + `wlan.ifconfig()`). These include network-specific and hardware-specific parameters. For setting parameters, keyword argument syntax should be used, multiple parameters can be set at once. For querying, parameters name should be quoted as a string, and only one parameter can be queries at time:: @@ -450,7 +450,7 @@ parameter should be `id`. .. class:: WLAN(id=0, ...) - Create a WLAN object, and optionally configure it. See ``init`` for params of configuration. + Create a WLAN object, and optionally configure it. See `init()` for params of configuration. .. note:: @@ -469,14 +469,14 @@ parameter should be `id`. Arguments are: - - ``mode`` can be either ``WLAN.STA`` or ``WLAN.AP``. - - ``ssid`` is a string with the ssid name. Only needed when mode is ``WLAN.AP``. - - ``auth`` is a tuple with (sec, key). Security can be ``None``, ``WLAN.WEP``, + - *mode* can be either ``WLAN.STA`` or ``WLAN.AP``. + - *ssid* is a string with the ssid name. Only needed when mode is ``WLAN.AP``. + - *auth* is a tuple with (sec, key). Security can be ``None``, ``WLAN.WEP``, ``WLAN.WPA`` or ``WLAN.WPA2``. The key is a string with the network password. If ``sec`` is ``WLAN.WEP`` the key must be a string representing hexadecimal values (e.g. 'ABC1DE45BF'). Only needed when mode is ``WLAN.AP``. - - ``channel`` a number in the range 1-11. Only needed when mode is ``WLAN.AP``. - - ``antenna`` selects between the internal and the external antenna. Can be either + - *channel* a number in the range 1-11. Only needed when mode is ``WLAN.AP``. + - *antenna* selects between the internal and the external antenna. Can be either ``WLAN.INT_ANT`` or ``WLAN.EXT_ANT``. For example, you can do:: @@ -494,13 +494,13 @@ parameter should be `id`. Connect to a WiFi access point using the given SSID, and other security parameters. - - ``auth`` is a tuple with (sec, key). Security can be ``None``, ``WLAN.WEP``, + - *auth* is a tuple with (sec, key). Security can be ``None``, ``WLAN.WEP``, ``WLAN.WPA`` or ``WLAN.WPA2``. The key is a string with the network password. If ``sec`` is ``WLAN.WEP`` the key must be a string representing hexadecimal values (e.g. 'ABC1DE45BF'). - - ``bssid`` is the MAC address of the AP to connect to. Useful when there are several + - *bssid* is the MAC address of the AP to connect to. Useful when there are several APs with the same ssid. - - ``timeout`` is the maximum time in milliseconds to wait for the connection to succeed. + - *timeout* is the maximum time in milliseconds to wait for the connection to succeed. .. method:: wlan.scan() @@ -518,7 +518,7 @@ parameter should be `id`. .. method:: wlan.ifconfig(if_id=0, config=['dhcp' or configtuple]) - With no parameters given returns a 4-tuple of ``(ip, subnet_mask, gateway, DNS_server)``. + With no parameters given returns a 4-tuple of *(ip, subnet_mask, gateway, DNS_server)*. if ``'dhcp'`` is passed as a parameter then the DHCP client is enabled and the IP params are negotiated with the AP. @@ -556,8 +556,8 @@ parameter should be `id`. Create a callback to be triggered when a WLAN event occurs during ``machine.SLEEP`` mode. Events are triggered by socket activity or by WLAN connection/disconnection. - - ``handler`` is the function that gets called when the IRQ is triggered. - - ``wake`` must be ``machine.SLEEP``. + - *handler* is the function that gets called when the IRQ is triggered. + - *wake* must be ``machine.SLEEP``. Returns an IRQ object. diff --git a/docs/library/pyb.Switch.rst b/docs/library/pyb.Switch.rst index bc62b6eee9..0d5dc63b74 100644 --- a/docs/library/pyb.Switch.rst +++ b/docs/library/pyb.Switch.rst @@ -8,7 +8,8 @@ A Switch object is used to control a push-button switch. Usage:: sw = pyb.Switch() # create a switch object - sw() # get state (True if pressed, False otherwise) + sw.value() # get state (True if pressed, False otherwise) + sw() # shorthand notation to get the switch state sw.callback(f) # register a callback to be called when the # switch is pressed down sw.callback(None) # remove the callback @@ -34,6 +35,10 @@ Methods Call switch object directly to get its state: ``True`` if pressed down, ``False`` otherwise. +.. method:: Switch.value() + + Get the switch state. Returns `True` if pressed down, otherwise `False`. + .. method:: Switch.callback(fun) Register the given function to be called when the switch is pressed down. diff --git a/docs/library/pyb.rst b/docs/library/pyb.rst index 9c4933808a..7991601457 100644 --- a/docs/library/pyb.rst +++ b/docs/library/pyb.rst @@ -21,7 +21,7 @@ Time related functions Returns the number of milliseconds since the board was last reset. - The result is always a micropython smallint (31-bit signed number), so + The result is always a MicroPython smallint (31-bit signed number), so after 2^30 milliseconds (about 12.4 days) this will start to return negative numbers. @@ -33,7 +33,7 @@ Time related functions Returns the number of microseconds since the board was last reset. - The result is always a micropython smallint (31-bit signed number), so + The result is always a MicroPython smallint (31-bit signed number), so after 2^30 microseconds (about 17.8 minutes) this will start to return negative numbers. @@ -85,10 +85,10 @@ Reset related functions Enable or disable hard-fault debugging. A hard-fault is when there is a fatal error in the underlying system, like an invalid memory access. - If the `value` argument is `False` then the board will automatically reset if + If the *value* argument is ``False`` then the board will automatically reset if there is a hard fault. - If `value` is `True` then, when the board has a hard fault, it will print the + If *value* is ``True`` then, when the board has a hard fault, it will print the registers and the stack trace, and then cycle the LEDs indefinitely. The default value is disabled, i.e. to automatically reset. diff --git a/docs/library/sys.rst b/docs/library/sys.rst index 1d7579754f..d49577306e 100644 --- a/docs/library/sys.rst +++ b/docs/library/sys.rst @@ -4,19 +4,21 @@ .. module:: sys :synopsis: system specific functions +|see_cpython_module| :mod:`python:sys`. + Functions --------- .. function:: exit(retval=0) Terminate current program with a given exit code. Underlyingly, this - function raise as ``SystemExit`` exception. If an argument is given, its - value given as an argument to ``SystemExit``. + function raise as `SystemExit` exception. If an argument is given, its + value given as an argument to `SystemExit`. .. function:: print_exception(exc, file=sys.stdout) - Print exception with a traceback to a file-like object `file` (or - ``sys.stdout`` by default). + Print exception with a traceback to a file-like object *file* (or + `sys.stdout` by default). .. admonition:: Difference to CPython :class: attention @@ -24,9 +26,9 @@ Functions This is simplified version of a function which appears in the ``traceback`` module in CPython. Unlike ``traceback.print_exception()``, this function takes just exception value instead of exception type, - exception value, and traceback object; `file` argument should be + exception value, and traceback object; *file* argument should be positional; further arguments are not supported. CPython-compatible - ``traceback`` module can be found in micropython-lib. + ``traceback`` module can be found in `micropython-lib`. Constants --------- @@ -37,15 +39,15 @@ Constants .. data:: byteorder - The byte order of the system ("little" or "big"). + The byte order of the system (``"little"`` or ``"big"``). .. data:: implementation Object with information about the current Python implementation. For MicroPython, it has following attributes: - * `name` - string "micropython" - * `version` - tuple (major, minor, micro), e.g. (1, 7, 0) + * *name* - string "micropython" + * *version* - tuple (major, minor, micro), e.g. (1, 7, 0) This object is the recommended way to distinguish MicroPython from other Python implementations (note that it still may not exist in the very @@ -95,10 +97,10 @@ Constants The platform that MicroPython is running on. For OS/RTOS ports, this is usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it - is an identifier of a board, e.g. "pyboard" for the original MicroPython + is an identifier of a board, e.g. ``"pyboard"`` for the original MicroPython reference board. It thus can be used to distinguish one board from another. If you need to check whether your program runs on MicroPython (vs other - Python implementation), use ``sys.implementation`` instead. + Python implementation), use `sys.implementation` instead. .. data:: stderr diff --git a/docs/library/ubinascii.rst b/docs/library/ubinascii.rst index 4931f90482..192d34514b 100644 --- a/docs/library/ubinascii.rst +++ b/docs/library/ubinascii.rst @@ -4,6 +4,8 @@ .. module:: ubinascii :synopsis: binary/ASCII conversions +|see_cpython_module| :mod:`python:binascii`. + This module implements conversions between binary data and various encodings of it in ASCII form (in both directions). @@ -17,7 +19,7 @@ Functions .. admonition:: Difference to CPython :class: attention - If additional argument, `sep` is supplied, it is used as a separator + If additional argument, *sep* is supplied, it is used as a separator between hexadecimal values. .. function:: unhexlify(data) @@ -27,8 +29,12 @@ Functions .. function:: a2b_base64(data) - Convert Base64-encoded data to binary representation. Returns bytes string. + Decode base64-encoded data, ignoring invalid characters in the input. + Conforms to `RFC 2045 s.6.8 <https://tools.ietf.org/html/rfc2045#section-6.8>`_. + Returns a bytes object. .. function:: b2a_base64(data) - Encode binary data in Base64 format. Returns string. + Encode binary data in base64 format, as in `RFC 3548 + <https://tools.ietf.org/html/rfc3548.html>`_. Returns the encoded data + followed by a newline character, as a bytes object. diff --git a/docs/library/ucollections.rst b/docs/library/ucollections.rst index 4e9de9ac67..96de67acc4 100644 --- a/docs/library/ucollections.rst +++ b/docs/library/ucollections.rst @@ -4,6 +4,8 @@ .. module:: ucollections :synopsis: collection and container types +|see_cpython_module| :mod:`python:collections`. + This module implements advanced collection and container types to hold/accumulate various objects. diff --git a/docs/library/uerrno.rst b/docs/library/uerrno.rst new file mode 100644 index 0000000000..0cdcc84487 --- /dev/null +++ b/docs/library/uerrno.rst @@ -0,0 +1,34 @@ +:mod:`uerrno` -- system error codes +=================================== + +.. module:: uerrno + :synopsis: system error codes + +|see_cpython_module| :mod:`python:errno`. + +This module provides access to symbolic error codes for `OSError` exception. +A particular inventory of codes depends on `MicroPython port`. + +Constants +--------- + +.. data:: EEXIST, EAGAIN, etc. + + Error codes, based on ANSI C/POSIX standard. All error codes start with + "E". As mentioned above, inventory of the codes depends on + `MicroPython port`. Errors are usually accessible as ``exc.args[0]`` + where `exc` is an instance of `OSError`. Usage example:: + + try: + uos.mkdir("my_dir") + except OSError as exc: + if exc.args[0] == uerrno.EEXIST: + print("Directory already exists") + +.. data:: errorcode + + Dictionary mapping numeric error codes to strings with symbolic error + code (see above):: + + >>> print(uerrno.errorcode[uerrno.EEXIST]) + EEXIST diff --git a/docs/library/uhashlib.rst b/docs/library/uhashlib.rst index 6b9a764ba8..50ed658cc1 100644 --- a/docs/library/uhashlib.rst +++ b/docs/library/uhashlib.rst @@ -4,6 +4,8 @@ .. module:: uhashlib :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: diff --git a/docs/library/uheapq.rst b/docs/library/uheapq.rst index c17dac0675..f822f1e7f3 100644 --- a/docs/library/uheapq.rst +++ b/docs/library/uheapq.rst @@ -4,6 +4,8 @@ .. module:: uheapq :synopsis: heap queue algorithm +|see_cpython_module| :mod:`python:heapq`. + This module implements the heap queue algorithm. A heap queue is simply a list that has its elements stored in a certain way. diff --git a/docs/library/uio.rst b/docs/library/uio.rst index 1239c6394e..7042a9e376 100644 --- a/docs/library/uio.rst +++ b/docs/library/uio.rst @@ -4,6 +4,8 @@ .. module:: uio :synopsis: input/output streams +|see_cpython_module| :mod:`python:io`. + This module contains additional types of stream (file-like) objects and helper functions. diff --git a/docs/library/ujson.rst b/docs/library/ujson.rst index 724bc90ee1..0932d0ab55 100644 --- a/docs/library/ujson.rst +++ b/docs/library/ujson.rst @@ -4,6 +4,8 @@ .. module:: ujson :synopsis: JSON encoding and decoding +|see_cpython_module| :mod:`python:json`. + This modules allows to convert between Python objects and the JSON data format. diff --git a/docs/library/uos.rst b/docs/library/uos.rst index 3d0aa46c70..7c52c1eead 100644 --- a/docs/library/uos.rst +++ b/docs/library/uos.rst @@ -4,6 +4,8 @@ .. module:: uos :synopsis: basic "operating system" services +|see_cpython_module| :mod:`python:os`. + The ``uos`` module contains functions for filesystem access and ``urandom`` function. @@ -22,15 +24,15 @@ Functions This function returns an iterator which then yields 3-tuples corresponding to the entries in the directory that it is listing. With no argument it lists the - current directory, otherwise it lists the directory given by `dir`. + current directory, otherwise it lists the directory given by *dir*. - The 3-tuples have the form `(name, type, inode)`: + The 3-tuples have the form *(name, type, inode)*: - - `name` is a string (or bytes if `dir` is a bytes object) and is the name of + - *name* is a string (or bytes if *dir* is a bytes object) and is the name of the entry; - - `type` is an integer that specifies the type of the entry, with 0x4000 for + - *type* is an integer that specifies the type of the entry, with 0x4000 for directories and 0x8000 for regular files; - - `inode` is an integer corresponding to the inode of the file, and may be 0 + - *inode* is an integer corresponding to the inode of the file, and may be 0 for filesystems that don't have such a notion. .. function:: listdir([dir]) @@ -90,5 +92,5 @@ Functions .. function:: dupterm(stream_object) Duplicate or switch MicroPython terminal (the REPL) on the passed stream-like - object. The given object must implement the `.readinto()` and `.write()` + object. The given object must implement the ``readinto()`` and ``write()`` methods. If ``None`` is passed, previously set redirection is cancelled. diff --git a/docs/library/ure.rst b/docs/library/ure.rst index ee360bcc47..67f4f54a1d 100644 --- a/docs/library/ure.rst +++ b/docs/library/ure.rst @@ -1,9 +1,11 @@ -:mod:`ure` -- regular expressions -================================= +:mod:`ure` -- simple regular expressions +======================================== .. module:: ure :synopsis: regular expressions +|see_cpython_module| :mod:`python:re`. + This module implements regular expression operations. Regular expression syntax supported is a subset of CPython ``re`` module (and actually is a subset of POSIX extended regular expressions). @@ -32,6 +34,10 @@ Supported operators are: ``'+?'`` +``'()'`` + Grouping. Each group is capturing (a substring it captures can be accessed + with `match.group()` method). + Counted repetitions (``{m,n}``), more advanced assertions, named groups, etc. are not supported. @@ -39,18 +45,18 @@ etc. are not supported. Functions --------- -.. function:: compile(regex) +.. function:: compile(regex_str) - Compile regular expression, return ``regex`` object. + Compile regular expression, return `regex <regex>` object. -.. function:: match(regex, string) +.. function:: match(regex_str, string) - Match ``regex`` against ``string``. Match always happens from starting - position in a string. + Compile *regex_str* and match against *string*. Match always happens + from starting position in a string. -.. function:: search(regex, string) +.. function:: search(regex_str, string) - Search ``regex`` in a ``string``. Unlike ``match``, this will search + Compile *regex_str* and search it in a *string*. Unlike `match`, this will search string for first position which matches regex (which still may be 0 if regex is anchored). @@ -59,24 +65,33 @@ Functions Flag value, display debug information about compiled expression. +.. _regex: + Regex objects ------------- Compiled regular expression. Instances of this class are created using -``ure.compile()``. +`ure.compile()`. .. method:: regex.match(string) + regex.search(string) -.. method:: regex.search(string) + Similar to the module-level functions :meth:`match` and :meth:`search`. + Using methods is (much) more efficient if the same regex is applied to + multiple strings. .. method:: regex.split(string, max_split=-1) + Split a *string* using regex. If *max_split* is given, it specifies + maximum number of splits to perform. Returns list of strings (there + may be up to *max_split+1* elements if it's specified). Match objects ------------- -Match objects as returned by ``match()`` and ``search()`` methods. +Match objects as returned by `match()` and `search()` methods. .. method:: match.group([index]) - Only numeric groups are supported. + Return matching (sub)string. *index* is 0 for entire match, + 1 and above for each capturing group. Only numeric groups are supported. diff --git a/docs/library/select.rst b/docs/library/uselect.rst index 8dcd4080f1..e330207dbd 100644 --- a/docs/library/select.rst +++ b/docs/library/uselect.rst @@ -1,18 +1,13 @@ -:mod:`select` -- wait for events on a set of streams +:mod:`uselect` -- wait for events on a set of streams ======================================================================== -.. module:: select +.. module:: uselect :synopsis: wait for events on a set of streams -This module provides functions to wait for events on streams (select streams -which are ready for operations). +|see_cpython_module| :mod:`python:select`. -Pyboard specifics ------------------ - -Polling is an efficient way of waiting for read/write activity on multiple -objects. Current objects that support polling are: :class:`pyb.UART`, -:class:`pyb.USB_VCP`. +This module provides functions to efficiently wait for events on multiple +streams (select streams which are ready for operations). Functions --------- @@ -25,8 +20,8 @@ Functions Wait for activity on a set of objects. - This function is provided for compatibility and is not efficient. Usage - of :class:`Poll` is recommended instead. + This function is provided by some MicroPython ports for compatibility + and is not efficient. Usage of :class:`Poll` is recommended instead. .. _class: Poll @@ -38,30 +33,46 @@ Methods .. method:: poll.register(obj[, eventmask]) - Register ``obj`` for polling. ``eventmask`` is logical OR of: + Register *obj* for polling. *eventmask* is logical OR of: * ``select.POLLIN`` - data available for reading * ``select.POLLOUT`` - more data can be written * ``select.POLLERR`` - error occurred * ``select.POLLHUP`` - end of stream/connection termination detected - ``eventmask`` defaults to ``select.POLLIN | select.POLLOUT``. + *eventmask* defaults to ``select.POLLIN | select.POLLOUT``. .. method:: poll.unregister(obj) - Unregister ``obj`` from polling. + Unregister *obj* from polling. .. method:: poll.modify(obj, eventmask) - Modify the ``eventmask`` for ``obj``. + Modify the *eventmask* for *obj*. .. method:: poll.poll([timeout]) Wait for at least one of the registered objects to become ready. Returns list of (``obj``, ``event``, ...) tuples, ``event`` element specifies - which events happened with a stream and is a combination of `select.POLL*` + which events happened with a stream and is a combination of ``select.POLL*`` constants described above. There may be other elements in tuple, depending on a platform and version, so don't assume that its size is 2. In case of timeout, an empty list is returned. Timeout is in milliseconds. + + .. admonition:: Difference to CPython + :class: attention + + Tuples returned may contain more than 2 elements as described above. + +.. method:: poll.ipoll([timeout]) + + Like :meth:`poll.poll`, but instead returns an iterator which yields + callee-owned tuples. This function provides efficient, allocation-free + way to poll on streams. + + .. admonition:: Difference to CPython + :class: attention + + This function is a MicroPython extension. diff --git a/docs/library/usocket.rst b/docs/library/usocket.rst index 71deaebc41..65e24e2662 100644 --- a/docs/library/usocket.rst +++ b/docs/library/usocket.rst @@ -5,43 +5,72 @@ .. module:: usocket :synopsis: socket module -This module provides access to the BSD socket interface. - -See the corresponding `CPython module <https://docs.python.org/3/library/socket.html>`_ -for comparison. - -.. admonition:: Difference to CPython - :class: attention +|see_cpython_module| :mod:`python:socket`. - CPython used to have a ``socket.error`` exception which is now deprecated, - and is an alias of OSError. In MicroPython, use OSError directly. +This module provides access to the BSD socket interface. .. admonition:: Difference to CPython :class: attention For efficiency and consistency, socket objects in MicroPython implement a stream (file-like) interface directly. In CPython, you need to convert a socket to - a file-like object using ``makefile()`` method. This method is still supported + a file-like object using `makefile()` method. This method is still supported by MicroPython (but is a no-op), so where compatibility with CPython matters, be sure to use it. Socket address format(s) ------------------------ -The functions below which expect a network address, accept it in the format of -`(ipv4_address, port)`, where `ipv4_address` is a string with dot-notation numeric -IPv4 address, e.g. ``"8.8.8.8"``, and port is integer port number in the range -1-65535. Note the domain names are not accepted as `ipv4_address`, they should be -resolved first using ``socket.getaddrinfo()``. +The native socket address format of the ``usocket`` module is an opaque data type +returned by `getaddrinfo` function, which must be used to resolve textual address +(including numeric addresses):: + + sockaddr = usocket.getaddrinfo('www.micropython.org', 80)[0][-1] + # You must use getaddrinfo() even for numeric addresses + sockaddr = usocket.getaddrinfo('127.0.0.1', 80)[0][-1] + # Now you can use that address + sock.connect(addr) + +Using `getaddrinfo` is the most efficient (both in terms of memory and processing +power) and portable way to work with addresses. + +However, ``socket`` module (note the difference with native MicroPython +``usocket`` module described here) provides CPython-compatible way to specify +addresses using tuples, as described below. Note that depending on a +`MicroPython port`, ``socket`` module can be builtin or need to be +installed from `micropython-lib` (as in the case of `MicroPython Unix port`), +and some ports still accept only numeric addresses in the tuple format, +and require to use `getaddrinfo` function to resolve domain names. + +Summing up: + +* Always use `getaddrinfo` when writing portable applications. +* Tuple addresses described below can be used as a shortcut for + quick hacks and interactive use, if your port supports them. + +Tuple address format for ``socket`` module: + +* IPv4: *(ipv4_address, port)*, where *ipv4_address* is a string with + dot-notation numeric IPv4 address, e.g. ``"8.8.8.8"``, and *port* is and + integer port number in the range 1-65535. Note the domain names are not + accepted as *ipv4_address*, they should be resolved first using + `usocket.getaddrinfo()`. +* IPv6: *(ipv6_address, port, flowinfo, scopeid)*, where *ipv6_address* + is a string with colon-notation numeric IPv6 address, e.g. ``"2001:db8::1"``, + and *port* is an integer port number in the range 1-65535. *flowinfo* + must be 0. *scopeid* is the interface scope identifier for link-local + addresses. Note the domain names are not accepted as *ipv6_address*, + they should be resolved first using `usocket.getaddrinfo()`. Availability + of IPv6 support depends on a `MicroPython port`. Functions --------- -.. function:: socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) +.. function:: socket(af=AF_INET, type=SOCK_STREAM, proto=IPPROTO_TCP) Create a new socket using the given address family, socket type and protocol number. -.. function:: socket.getaddrinfo(host, port) +.. function:: getaddrinfo(host, port) Translate the host/port argument into a sequence of 5-tuples that contain all the necessary arguments for creating a socket connected to that service. The list of @@ -57,11 +86,11 @@ Functions .. admonition:: Difference to CPython :class: attention - CPython raises a ``socket.gaierror`` exception (OSError subclass) in case + CPython raises a ``socket.gaierror`` exception (`OSError` subclass) in case of error in this function. MicroPython doesn't have ``socket.gaierror`` - and raises OSError directly. Note that error numbers of ``getaddrinfo()`` + and raises OSError directly. Note that error numbers of `getaddrinfo()` form a separate namespace and may not match error numbers from - ``uerrno`` module. To distinguish ``getaddrinfo()`` errors, they are + `uerrno` module. To distinguish `getaddrinfo()` errors, they are represented by negative numbers, whereas standard system errors are positive numbers (error numbers are accessible using ``e.args[0]`` property from an exception object). The use of negative values is a provisional @@ -70,32 +99,34 @@ Functions Constants --------- -.. data:: socket.AF_INET - socket.AF_INET6 +.. data:: AF_INET + AF_INET6 Address family types. Availability depends on a particular board. -.. data:: socket.SOCK_STREAM - socket.SOCK_DGRAM +.. data:: SOCK_STREAM + SOCK_DGRAM Socket types. -.. data:: socket.IPPROTO_UDP - socket.IPPROTO_TCP +.. data:: IPPROTO_UDP + IPPROTO_TCP IP protocol numbers. -.. data:: socket.SOL_* +.. data:: usocket.SOL_* - Socket option levels (an argument to ``setsockopt()``). The exact inventory depends on a board. + Socket option levels (an argument to `setsockopt()`). The exact + inventory depends on a MicroPython port. -.. data:: socket.SO_* +.. data:: usocket.SO_* - Socket options (an argument to ``setsockopt()``). The exact inventory depends on a board. + Socket options (an argument to `setsockopt()`). The exact + inventory depends on a MicroPython port. Constants specific to WiPy: -.. data:: socket.IPPROTO_SEC +.. data:: IPPROTO_SEC Special protocol value to create SSL-compatible socket. @@ -105,21 +136,22 @@ class socket Methods ------- -.. method:: socket.close +.. method:: socket.close() - Mark the socket closed. Once that happens, all future operations on the socket - object will fail. The remote end will receive no more data (after queued data is flushed). + Mark the socket closed and release all resources. Once that happens, all future operations + on the socket object will fail. The remote end will receive EOF indication if + supported by protocol. Sockets are automatically closed when they are garbage-collected, but it is recommended - to close() them explicitly, or to use a with statement around them. + to `close()` them explicitly as soon you finished working with them. .. method:: socket.bind(address) - Bind the socket to address. The socket must not already be bound. + Bind the socket to *address*. The socket must not already be bound. .. method:: socket.listen([backlog]) - Enable a server to accept connections. If backlog is specified, it must be at least 0 + Enable a server to accept connections. If *backlog* is specified, it must be at least 0 (if it's lower, it will be set to 0); and specifies the number of unaccepted connections that the system will allow before refusing new connections. If not specified, a default reasonable value is chosen. @@ -133,7 +165,7 @@ Methods .. method:: socket.connect(address) - Connect to a remote socket at address. + Connect to a remote socket at *address*. .. method:: socket.send(bytes) @@ -144,11 +176,11 @@ Methods .. method:: socket.sendall(bytes) Send all data to the socket. The socket must be connected to a remote socket. - Unlike ``send()``, this method will try to send all of data, by sending data + Unlike `send()`, this method will try to send all of data, by sending data chunk by chunk consecutively. The behavior of this method on non-blocking sockets is undefined. Due to this, - on MicroPython, it's recommended to use ``write()`` method instead, which + on MicroPython, it's recommended to use `write()` method instead, which has the same "no short writes" policy for blocking sockets, and will return number of bytes sent on non-blocking sockets. @@ -160,25 +192,25 @@ Methods .. method:: socket.sendto(bytes, address) Send data to the socket. The socket should not be connected to a remote socket, since the - destination socket is specified by `address`. + destination socket is specified by *address*. .. method:: socket.recvfrom(bufsize) - Receive data from the socket. The return value is a pair (bytes, address) where bytes is a - bytes object representing the data received and address is the address of the socket sending + Receive data from the socket. The return value is a pair *(bytes, address)* where *bytes* is a + bytes object representing the data received and *address* is the address of the socket sending the data. .. method:: socket.setsockopt(level, optname, value) Set the value of the given socket option. The needed symbolic constants are defined in the - socket module (SO_* etc.). The value can be an integer or a bytes-like object representing + socket module (SO_* etc.). The *value* can be an integer or a bytes-like object representing a buffer. .. method:: socket.settimeout(value) Set a timeout on blocking socket operations. The value argument can be a nonnegative floating point number expressing seconds, or None. If a non-zero value is given, subsequent socket operations - will raise an ``OSError`` exception if the timeout period value has elapsed before the operation has + will raise an `OSError` exception if the timeout period value has elapsed before the operation has completed. If zero is given, the socket is put in non-blocking mode. If None is given, the socket is put in blocking mode. @@ -186,7 +218,7 @@ Methods :class: attention CPython raises a ``socket.timeout`` exception in case of timeout, - which is an ``OSError`` subclass. MicroPython raises an OSError directly + which is an `OSError` subclass. MicroPython raises an OSError directly instead. If you use ``except OSError:`` to catch the exception, your code will work both in MicroPython and CPython. @@ -195,7 +227,7 @@ Methods Set blocking or non-blocking mode of the socket: if flag is false, the socket is set to non-blocking, else to blocking mode. - This method is a shorthand for certain ``settimeout()`` calls: + This method is a shorthand for certain `settimeout()` calls: * ``sock.setblocking(True)`` is equivalent to ``sock.settimeout(None)`` * ``sock.setblocking(False)`` is equivalent to ``sock.settimeout(0)`` @@ -204,12 +236,12 @@ Methods Return a file object associated with the socket. The exact returned type depends on the arguments given to makefile(). The support is limited to binary modes only ('rb', 'wb', and 'rwb'). - CPython's arguments: ``encoding``, ``errors`` and ``newline`` are not supported. + CPython's arguments: *encoding*, *errors* and *newline* are not supported. .. admonition:: Difference to CPython :class: attention - As MicroPython doesn't support buffered streams, values of ``buffering`` + As MicroPython doesn't support buffered streams, values of *buffering* parameter is ignored and treated as if it was 0 (unbuffered). .. admonition:: Difference to CPython @@ -220,19 +252,19 @@ Methods .. method:: socket.read([size]) - Read up to size bytes from the socket. Return a bytes object. If ``size`` is not given, it - reads all data available from the socket until ``EOF``; as such the method will not return until + Read up to size bytes from the socket. Return a bytes object. If *size* is not given, it + reads all data available from the socket until EOF; as such the method will not return until the socket is closed. This function tries to read as much data as requested (no "short reads"). This may be not possible with non-blocking socket though, and then less data will be returned. .. method:: socket.readinto(buf[, nbytes]) - Read bytes into the ``buf``. If ``nbytes`` is specified then read at most - that many bytes. Otherwise, read at most ``len(buf)`` bytes. Just as - ``read()``, this method follows "no short reads" policy. + Read bytes into the *buf*. If *nbytes* is specified then read at most + that many bytes. Otherwise, read at most *len(buf)* bytes. Just as + `read()`, this method follows "no short reads" policy. - Return value: number of bytes read and stored into ``buf``. + Return value: number of bytes read and stored into *buf*. .. method:: socket.readline() @@ -245,6 +277,16 @@ Methods Write the buffer of bytes to the socket. This function will try to write all data to a socket (no "short writes"). This may be not possible with a non-blocking socket though, and returned value will be less than - the length of ``buf``. + the length of *buf*. Return value: number of bytes written. + +.. exception:: socket.error + + MicroPython does NOT have this exception. + + .. admonition:: Difference to CPython + :class: attention + + CPython used to have a ``socket.error`` exception which is now deprecated, + and is an alias of `OSError`. In MicroPython, use `OSError` directly. diff --git a/docs/library/ussl.rst b/docs/library/ussl.rst index 36f6d65a4a..c71b283ccb 100644 --- a/docs/library/ussl.rst +++ b/docs/library/ussl.rst @@ -4,6 +4,8 @@ .. module:: ussl :synopsis: TLS/SSL wrapper for socket objects +|see_cpython_module| :mod:`python:ssl`. + This module provides access to Transport Layer Security (previously and widely known as “Secure Sockets Layer”) encryption and peer authentication facilities for network sockets, both client-side and server-side. @@ -13,7 +15,7 @@ Functions .. function:: ssl.wrap_socket(sock, server_side=False, keyfile=None, certfile=None, cert_reqs=CERT_NONE, ca_certs=None) - Takes a stream `sock` (usually usocket.socket instance of ``SOCK_STREAM`` type), + Takes a stream *sock* (usually usocket.socket instance of ``SOCK_STREAM`` type), and returns an instance of ssl.SSLSocket, which wraps the underlying stream in an SSL context. Returned object has the usual stream interface methods like `read()`, `write()`, etc. In MicroPython, the returned object does not expose @@ -43,4 +45,4 @@ Constants ssl.CERT_OPTIONAL ssl.CERT_REQUIRED - Supported values for `cert_reqs` parameter. + Supported values for *cert_reqs* parameter. diff --git a/docs/library/ustruct.rst b/docs/library/ustruct.rst index 74e42af07a..81915d0a8d 100644 --- a/docs/library/ustruct.rst +++ b/docs/library/ustruct.rst @@ -4,8 +4,7 @@ .. module:: ustruct :synopsis: pack and unpack primitive data types -See `Python struct <https://docs.python.org/3/library/struct.html>`_ for more -information. +|see_cpython_module| :mod:`python:struct`. Supported size/byte order prefixes: ``@``, ``<``, ``>``, ``!``. @@ -18,26 +17,26 @@ Functions .. function:: calcsize(fmt) - Return the number of bytes needed to store the given `fmt`. + Return the number of bytes needed to store the given *fmt*. .. function:: pack(fmt, v1, v2, ...) - Pack the values `v1`, `v2`, ... according to the format string `fmt`. + Pack the values *v1*, *v2*, ... according to the format string *fmt*. The return value is a bytes object encoding the values. .. function:: pack_into(fmt, buffer, offset, v1, v2, ...) - Pack the values `v1`, `v2`, ... according to the format string `fmt` - into a `buffer` starting at `offset`. `offset` may be negative to count - from the end of `buffer`. + Pack the values *v1*, *v2*, ... according to the format string *fmt* + into a *buffer* starting at *offset*. *offset* may be negative to count + from the end of *buffer*. .. function:: unpack(fmt, data) - Unpack from the `data` according to the format string `fmt`. + Unpack from the *data* according to the format string *fmt*. The return value is a tuple of the unpacked values. .. function:: unpack_from(fmt, data, offset=0) - Unpack from the `data` starting at `offset` according to the format string - `fmt`. `offset` may be negative to count from the end of `buffer`. The return + Unpack from the *data* starting at *offset* according to the format string + *fmt*. *offset* may be negative to count from the end of *buffer*. The return value is a tuple of the unpacked values. diff --git a/docs/library/utime.rst b/docs/library/utime.rst index f3a067cdef..a39f5ee733 100644 --- a/docs/library/utime.rst +++ b/docs/library/utime.rst @@ -4,6 +4,8 @@ .. module:: utime :synopsis: time related functions +|see_cpython_module| :mod:`python:time`. + The ``utime`` module provides functions for getting the current time and date, measuring time intervals, and for delays. @@ -57,10 +59,10 @@ Functions .. function:: sleep(seconds) - Sleep for the given number of seconds. Some boards may accept `seconds` as a + Sleep for the given number of seconds. Some boards may accept *seconds* as a floating-point number to sleep for a fractional number of seconds. Note that other boards may not accept a floating-point argument, for compatibility with - them use ``sleep_ms()`` and ``sleep_us()`` functions. + them use `sleep_ms()` and `sleep_us()` functions. .. function:: sleep_ms(ms) @@ -73,30 +75,32 @@ Functions .. function:: ticks_ms() Returns an increasing millisecond counter with an arbitrary reference point, that - wraps around after some value. This value is not explicitly exposed, but we will - refer to it as ``TICKS_MAX`` to simplify discussion. Period of the values is - ``TICKS_PERIOD = TICKS_MAX + 1``. ``TICKS_PERIOD`` is guaranteed to be a power of + wraps around after some value. + + The wrap-around value is not explicitly exposed, but we will + refer to it as *TICKS_MAX* to simplify discussion. Period of the values is + *TICKS_PERIOD = TICKS_MAX + 1*. *TICKS_PERIOD* is guaranteed to be a power of two, but otherwise may differ from port to port. The same period value is used - for all of ``ticks_ms()``, ``ticks_us()``, ``ticks_cpu()`` functions (for - simplicity). Thus, these functions will return a value in range [``0`` .. - ``TICKS_MAX``], inclusive, total ``TICKS_PERIOD`` values. Note that only + for all of `ticks_ms()`, `ticks_us()`, `ticks_cpu()` functions (for + simplicity). Thus, these functions will return a value in range [*0* .. + *TICKS_MAX*], inclusive, total *TICKS_PERIOD* values. Note that only non-negative values are used. For the most part, you should treat values returned by these functions as opaque. The only operations available for them are - ``ticks_diff()`` and ``ticks_add()`` functions described below. + `ticks_diff()` and `ticks_add()` functions described below. Note: Performing standard mathematical operations (+, -) or relational operators (<, <=, >, >=) directly on these value will lead to invalid result. Performing mathematical operations and then passing their results - as arguments to ``ticks_diff()`` or ``ticks_add()`` will also lead to + as arguments to `ticks_diff()` or `ticks_add()` will also lead to invalid results from the latter functions. .. function:: ticks_us() - Just like ``ticks_ms()`` above, but in microseconds. + Just like `ticks_ms()` above, but in microseconds. .. function:: ticks_cpu() - Similar to ``ticks_ms()`` and ``ticks_us()``, but with the highest possible resolution + Similar to `ticks_ms()` and `ticks_us()`, but with the highest possible resolution in the system. This is usually CPU clocks, and that's why the function is named that way. But it doesn't have to be a CPU clock, some other timing source available in a system (e.g. high-resolution timer) can be used instead. The exact timing unit @@ -111,13 +115,13 @@ Functions .. function:: ticks_add(ticks, delta) Offset ticks value by a given number, which can be either positive or negative. - Given a ``ticks`` value, this function allows to calculate ticks value ``delta`` + Given a *ticks* value, this function allows to calculate ticks value *delta* ticks before or after it, following modular-arithmetic definition of tick values - (see ``ticks_ms()`` above). ``ticks`` parameter must be a direct result of call - to ``ticks_ms()``, ``ticks_us()``, or ``ticks_cpu()`` functions (or from previous - call to ``ticks_add()``). However, ``delta`` can be an arbitrary integer number - or numeric expression. ``ticks_add()`` is useful for calculating deadlines for - events/tasks. (Note: you must use ``ticks_diff()`` function to work with + (see `ticks_ms()` above). *ticks* parameter must be a direct result of call + to `ticks_ms()`, `ticks_us()`, or `ticks_cpu()` functions (or from previous + call to `ticks_add()`). However, *delta* can be an arbitrary integer number + or numeric expression. `ticks_add()` is useful for calculating deadlines for + events/tasks. (Note: you must use `ticks_diff()` function to work with deadlines.) Examples:: @@ -136,23 +140,25 @@ Functions .. function:: ticks_diff(ticks1, ticks2) - Measure ticks difference between values returned from ``ticks_ms()``, ``ticks_us()``, - or ``ticks_cpu()`` functions. The argument order is the same as for subtraction + Measure ticks difference between values returned from `ticks_ms()`, `ticks_us()`, + or `ticks_cpu()` functions, as a signed value which may wrap around. + + The argument order is the same as for subtraction operator, ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. - However, values returned by ``ticks_ms()``, etc. functions may wrap around, so + However, values returned by `ticks_ms()`, etc. functions may wrap around, so directly using subtraction on them will produce incorrect result. That is why - ``ticks_diff()`` is needed, it implements modular (or more specifically, ring) + `ticks_diff()` is needed, it implements modular (or more specifically, ring) arithmetics to produce correct result even for wrap-around values (as long as they not too distant inbetween, see below). The function returns **signed** value in the range - [``-TICKS_PERIOD/2`` .. ``TICKS_PERIOD/2-1``] (that's a typical range definition for + [*-TICKS_PERIOD/2* .. *TICKS_PERIOD/2-1*] (that's a typical range definition for two's-complement signed binary integers). If the result is negative, it means that - ``ticks1`` occurred earlier in time than ``ticks2``. Otherwise, it means that - ``ticks1`` occurred after ``ticks2``. This holds ``only`` if ``ticks1`` and ``ticks2`` - are apart from each other for no more than ``TICKS_PERIOD/2-1`` ticks. If that does + *ticks1* occurred earlier in time than *ticks2*. Otherwise, it means that + *ticks1* occurred after *ticks2*. This holds **only** if *ticks1* and *ticks2* + are apart from each other for no more than *TICKS_PERIOD/2-1* ticks. If that does not hold, incorrect result will be returned. Specifically, if two tick values are - apart for ``TICKS_PERIOD/2-1`` ticks, that value will be returned by the function. - However, if ``TICKS_PERIOD/2`` of real-time ticks has passed between them, the - function will return ``-TICKS_PERIOD/2`` instead, i.e. result value will wrap around + apart for *TICKS_PERIOD/2-1* ticks, that value will be returned by the function. + However, if *TICKS_PERIOD/2* of real-time ticks has passed between them, the + function will return *-TICKS_PERIOD/2* instead, i.e. result value will wrap around to the negative range of possible values. Informal rationale of the constraints above: Suppose you are locked in a room with no @@ -164,10 +170,10 @@ Functions behavior: don't let your application run any single task for too long. Run tasks in steps, and do time-keeping inbetween. - ``ticks_diff()`` is designed to accommodate various usage patterns, among them: + `ticks_diff()` is designed to accommodate various usage patterns, among them: - Polling with timeout. In this case, the order of events is known, and you will deal - only with positive results of ``ticks_diff()``:: + * Polling with timeout. In this case, the order of events is known, and you will deal + only with positive results of `ticks_diff()`:: # Wait for GPIO pin to be asserted, but at most 500us start = time.ticks_us() @@ -175,8 +181,8 @@ Functions if time.ticks_diff(time.ticks_us(), start) > 500: raise TimeoutError - Scheduling events. In this case, ``ticks_diff()`` result may be negative - if an event is overdue:: + * Scheduling events. In this case, `ticks_diff()` result may be negative + if an event is overdue:: # This code snippet is not optimized now = time.ticks_ms() @@ -192,8 +198,8 @@ Functions print("Oops, running late, tell task to run faster!") task.run(run_faster=true) - Note: Do not pass ``time()`` values to ``ticks_diff()``, you should use - normal mathematical operations on them. But note that ``time()`` may (and will) + Note: Do not pass `time()` values to `ticks_diff()`, you should use + normal mathematical operations on them. But note that `time()` may (and will) also overflow. This is known as https://en.wikipedia.org/wiki/Year_2038_problem . @@ -205,8 +211,8 @@ Functions embedded boards without a battery-backed RTC, usually since power up or reset). If you want to develop portable MicroPython application, you should not rely on this function to provide higher than second precision. If you need higher precision, use - ``ticks_ms()`` and ``ticks_us()`` functions, if you need calendar time, - ``localtime()`` without an argument is a better choice. + `ticks_ms()` and `ticks_us()` functions, if you need calendar time, + `localtime()` without an argument is a better choice. .. admonition:: Difference to CPython :class: attention diff --git a/docs/library/uzlib.rst b/docs/library/uzlib.rst index 8775ec3e07..fb1746fe8e 100644 --- a/docs/library/uzlib.rst +++ b/docs/library/uzlib.rst @@ -4,13 +4,35 @@ .. module:: uzlib :synopsis: zlib decompression -This modules allows to decompress binary data compressed with DEFLATE -algorithm (commonly used in zlib library and gzip archiver). Compression +|see_cpython_module| :mod:`python:zlib`. + +This module allows to decompress binary data compressed with +`DEFLATE algorithm <https://en.wikipedia.org/wiki/DEFLATE>`_ +(commonly used in zlib library and gzip archiver). Compression is not yet implemented. Functions --------- -.. function:: decompress(data) +.. function:: decompress(data, wbits=0, bufsize=0) + + Return decompressed *data* as bytes. *wbits* is DEFLATE dictionary window + size used during compression (8-15, the dictionary size is power of 2 of + that value). Additionally, if value is positive, *data* is assumed to be + zlib stream (with zlib header). Otherwise, if it's negative, it's assumed + to be raw DEFLATE stream. *bufsize* parameter is for compatibility with + CPython and is ignored. + +.. class:: DecompIO(stream, wbits=0) + + Create a stream wrapper which allows transparent decompression of + compressed data in another *stream*. This allows to process compressed + streams with data larger than available heap size. In addition to + values described in :func:`decompress`, *wbits* may take values + 24..31 (16 + 8..15), meaning that input stream has gzip header. + + .. admonition:: Difference to CPython + :class: attention - Return decompressed data as bytes. + This class is MicroPython extension. It's included on provisional + basis and may be changed considerably or removed in later versions. diff --git a/docs/license.rst b/docs/license.rst index bbc5016ed7..73caa90351 100644 --- a/docs/license.rst +++ b/docs/license.rst @@ -3,7 +3,7 @@ MicroPython license information The MIT License (MIT) -Copyright (c) 2013-2015 Damien P. George, and others +Copyright (c) 2013-2017 Damien P. George, and others Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/docs/pyboard/general.rst b/docs/pyboard/general.rst index 1d040f6ccc..97e9aabc0b 100644 --- a/docs/pyboard/general.rst +++ b/docs/pyboard/general.rst @@ -1,6 +1,8 @@ General information about the pyboard ===================================== +.. contents:: + Local filesystem and SD card ---------------------------- @@ -67,3 +69,12 @@ There are currently 2 kinds of errors that you might see: 2. If all 4 LEDs cycle on and off slowly, then there was a hard fault. This cannot be recovered from and you need to do a hard reset. +Guide for using the pyboard with Windows +---------------------------------------- + +The following PDF guide gives information about using the pyboard with Windows, +including setting up the serial prompt and downloading new firmware using +DFU programming: +`PDF guide <http://micropython.org/resources/Micro-Python-Windows-setup.pdf>`__. + +.. include:: hardware/index.rst diff --git a/docs/pyboard/hardware/index.rst b/docs/pyboard/hardware/index.rst index bc4726ce2d..91fea24e7a 100644 --- a/docs/pyboard/hardware/index.rst +++ b/docs/pyboard/hardware/index.rst @@ -1,7 +1,7 @@ .. _hardware_index: The pyboard hardware -==================== +-------------------- For the pyboard: @@ -16,14 +16,14 @@ For the official skin modules: * LCD160CRv1.0: see :mod:`lcd160cr` Datasheets for the components on the pyboard -============================================ +-------------------------------------------- * The microcontroller: `STM32F405RGT6 <http://www.st.com/web/catalog/mmc/FM141/SC1169/SS1577/LN1035/PF252144>`_ (link to manufacturer's site) * The accelerometer: `Freescale MMA7660 <http://micropython.org/resources/datasheets/MMA7660FC.pdf>`_ (800kiB PDF) * The LDO voltage regulator: `Microchip MCP1802 <http://micropython.org/resources/datasheets/MCP1802-22053C.pdf>`_ (400kiB PDF) Datasheets for other components -=============================== +------------------------------- * The LCD display on the LCD touch-sensor skin: `Newhaven Display NHD-C12832A1Z-FSW-FBW-3V3 <http://micropython.org/resources/datasheets/NHD-C12832A1Z-FSW-FBW-3V3.pdf>`_ (460KiB PDF) * The touch sensor chip on the LCD touch-sensor skin: `Freescale MPR121 <http://micropython.org/resources/datasheets/MPR121.pdf>`_ (280KiB PDF) diff --git a/docs/pyboard/tutorial/amp_skin.rst b/docs/pyboard/tutorial/amp_skin.rst index 64f139bb7e..697637f9d2 100644 --- a/docs/pyboard/tutorial/amp_skin.rst +++ b/docs/pyboard/tutorial/amp_skin.rst @@ -69,4 +69,30 @@ Then you can do:: >>> f = wave.open('test.wav') >>> dac.write_timed(f.readframes(f.getnframes()), f.getframerate()) -This should play the WAV file. +This should play the WAV file. Note that this will read the whole file into RAM +so it has to be small enough to fit in it. + +To play larger wave files you will have to use the micro-SD card to store it. +Also the file must be read and sent to the DAC in small chunks that will fit +the RAM limit of the microcontroller. Here is an example function that can +play 8-bit wave files with up to 16kHz sampling:: + + import wave + from pyb import DAC + from pyb import delay + dac = DAC(1) + + def play(filename): + f = wave.open(filename, 'r') + total_frames = f.getnframes() + framerate = f.getframerate() + + for position in range(0, total_frames, framerate): + f.setpos(position) + dac.write_timed(f.readframes(framerate), framerate) + delay(1000) + +This function reads one second worth of data and sends it to DAC. It then waits +one second and moves the file cursor to the new position to read the next second +of data in the next iteration of the for-loop. It plays one second of audio at +a time every one second. diff --git a/docs/pyboard/tutorial/index.rst b/docs/pyboard/tutorial/index.rst index 07f136c9b4..1dc155f149 100644 --- a/docs/pyboard/tutorial/index.rst +++ b/docs/pyboard/tutorial/index.rst @@ -1,7 +1,7 @@ .. _tutorial-index: -MicroPython tutorial -==================== +MicroPython tutorial for the pyboard +==================================== This tutorial is intended to get you started with your pyboard. All you need is a pyboard and a micro-USB cable to connect it to diff --git a/docs/pyboard/tutorial/switch.rst b/docs/pyboard/tutorial/switch.rst index 945e89aa05..91683fba45 100644 --- a/docs/pyboard/tutorial/switch.rst +++ b/docs/pyboard/tutorial/switch.rst @@ -15,12 +15,18 @@ the name ``pyb`` does not exist. With the switch object you can get its status:: - >>> sw() + >>> sw.value() False This will print ``False`` if the switch is not held, or ``True`` if it is held. Try holding the USR switch down while running the above command. +There is also a shorthand notation to get the switch status, by "calling" the +switch object:: + + >>> sw() + False + Switch callbacks ---------------- diff --git a/docs/pyboard_contents.rst b/docs/pyboard_contents.rst deleted file mode 100644 index 658dd366f2..0000000000 --- a/docs/pyboard_contents.rst +++ /dev/null @@ -1,14 +0,0 @@ -MicroPython documentation contents -================================== - -.. toctree:: - - pyboard/quickref.rst - pyboard/general.rst - pyboard/tutorial/index.rst - library/index.rst - reference/index.rst - pyboard/hardware/index.rst - genrst/index.rst - license.rst - diff --git a/docs/pyboard_index.rst b/docs/pyboard_index.rst index 4caa4cc883..2255a75607 100644 --- a/docs/pyboard_index.rst +++ b/docs/pyboard_index.rst @@ -7,14 +7,6 @@ MicroPython documentation and references pyboard/general.rst pyboard/tutorial/index.rst library/index.rst - pyboard/hardware/index.rst + reference/index.rst genrst/index.rst license.rst - pyboard_contents.rst - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` diff --git a/docs/reference/constrained.rst b/docs/reference/constrained.rst index 7c1b6a3eb2..14286aa262 100644 --- a/docs/reference/constrained.rst +++ b/docs/reference/constrained.rst @@ -119,10 +119,10 @@ symbols that have already been defined, e.g. ``1 << BIT``. Where there is a substantial volume of constant data and the platform supports execution from Flash, RAM may be saved as follows. The data should be located in -Python modules and frozen as bytecode. The data must be defined as ``bytes`` -objects. The compiler 'knows' that ``bytes`` objects are immutable and ensures +Python modules and frozen as bytecode. The data must be defined as `bytes` +objects. The compiler 'knows' that `bytes` objects are immutable and ensures that the objects remain in flash memory rather than being copied to RAM. The -``ustruct`` module can assist in converting between ``bytes`` types and other +`ustruct` module can assist in converting between `bytes` types and other Python built-in types. When considering the implications of frozen bytecode, note that in Python @@ -185,7 +185,7 @@ a file it will save RAM if this is done in a piecemeal fashion. Rather than creating a large string object, create a substring and feed it to the stream before dealing with the next. -The best way to create dynamic strings is by means of the string ``format`` +The best way to create dynamic strings is by means of the string `format` method: .. code:: @@ -226,26 +226,26 @@ function ``foo()``: foo(b'\1\2\xff') In the first call a tuple of integers is created in RAM. The second efficiently -creates a ``bytes`` object consuming the minimum amount of RAM. If the module -were frozen as bytecode, the ``bytes`` object would reside in flash. +creates a `bytes` object consuming the minimum amount of RAM. If the module +were frozen as bytecode, the `bytes` object would reside in flash. **Strings Versus Bytes** Python3 introduced Unicode support. This introduced a distinction between a string and an array of bytes. MicroPython ensures that Unicode strings take no additional space so long as all characters in the string are ASCII (i.e. have -a value < 126). If values in the full 8-bit range are required ``bytes`` and -``bytearray`` objects can be used to ensure that no additional space will be -required. Note that most string methods (e.g. ``strip()``) apply also to ``bytes`` +a value < 126). If values in the full 8-bit range are required `bytes` and +`bytearray` objects can be used to ensure that no additional space will be +required. Note that most string methods (e.g. :meth:`str.strip()`) apply also to `bytes` instances so the process of eliminating Unicode can be painless. .. code:: - s = 'the quick brown fox' # A string instance - b = b'the quick brown fox' # a bytes instance + s = 'the quick brown fox' # A string instance + b = b'the quick brown fox' # A bytes instance -Where it is necessary to convert between strings and bytes the string ``encode`` -and the bytes ``decode`` methods can be used. Note that both strings and bytes +Where it is necessary to convert between strings and bytes the :meth:`str.encode` +and the :meth:`bytes.decode` methods can be used. Note that both strings and bytes are immutable. Any operation which takes as input such an object and produces another implies at least one RAM allocation to produce the result. In the second line below a new bytes object is allocated. This would also occur if ``foo`` @@ -258,10 +258,10 @@ were a string. **Runtime compiler execution** -The Python keywords ``eval`` and ``exec`` invoke the compiler at runtime, which -requires significant amounts of RAM. Note that the ``pickle`` library employs -``exec``. It may be more RAM efficient to use the ``json`` library for object -serialisation. +The Python funcitons `eval` and `exec` invoke the compiler at runtime, which +requires significant amounts of RAM. Note that the `pickle` library from +`micropython-lib` employs `exec`. It may be more RAM efficient to use the +`ujson` library for object serialisation. **Storing strings in flash** @@ -300,7 +300,7 @@ from a fixed size pool known as the heap. When the object goes out of scope (in other words becomes inaccessible to code) the redundant object is known as "garbage". A process known as "garbage collection" (GC) reclaims that memory, returning it to the free heap. This process runs automatically, however it can -be invoked directly by issuing ``gc.collect()``. +be invoked directly by issuing `gc.collect()`. The discourse on this is somewhat involved. For a 'quick fix' issue the following periodically: @@ -332,7 +332,7 @@ Reporting ~~~~~~~~~ A number of library functions are available to report on memory allocation and -to control GC. These are to be found in the ``gc`` and ``micropython`` modules. +to control GC. These are to be found in the `gc` and `micropython` modules. The following example may be pasted at the REPL (``ctrl e`` to enter paste mode, ``ctrl d`` to run it). @@ -357,17 +357,17 @@ The following example may be pasted at the REPL (``ctrl e`` to enter paste mode, Methods employed above: -* ``gc.collect()`` Force a garbage collection. See footnote. -* ``micropython.mem_info()`` Print a summary of RAM utilisation. -* ``gc.mem_free()`` Return the free heap size in bytes. -* ``gc.mem_alloc()`` Return the number of bytes currently allocated. +* `gc.collect()` Force a garbage collection. See footnote. +* `micropython.mem_info()` Print a summary of RAM utilisation. +* `gc.mem_free()` Return the free heap size in bytes. +* `gc.mem_alloc()` Return the number of bytes currently allocated. * ``micropython.mem_info(1)`` Print a table of heap utilisation (detailed below). The numbers produced are dependent on the platform, but it can be seen that declaring the function uses a small amount of RAM in the form of bytecode emitted by the compiler (the RAM used by the compiler has been reclaimed). Running the function uses over 10KiB, but on return ``a`` is garbage because it -is out of scope and cannot be referenced. The final ``gc.collect()`` recovers +is out of scope and cannot be referenced. The final `gc.collect()` recovers that memory. The final output produced by ``micropython.mem_info(1)`` will vary in detail but @@ -394,7 +394,7 @@ line of the heap dump represents 0x400 bytes or 1KiB of RAM. Control of Garbage Collection ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -A GC can be demanded at any time by issuing ``gc.collect()``. It is advantageous +A GC can be demanded at any time by issuing `gc.collect()`. It is advantageous to do this at intervals, firstly to pre-empt fragmentation and secondly for performance. A GC can take several milliseconds but is quicker when there is little work to do (about 1ms on the Pyboard). An explicit call can minimise that @@ -417,7 +417,7 @@ occupied. In general modules should instantiate data objects at runtime using constructors or other initialisation functions. The reason is that if this occurs on initialisation the compiler may be starved of RAM when subsequent modules are -imported. If modules do instantiate data on import then ``gc.collect()`` issued +imported. If modules do instantiate data on import then `gc.collect()` issued after the import will ameliorate the problem. String Operations @@ -444,13 +444,13 @@ RAM usage and speed. Where variables are required whose size is neither a byte nor a machine word there are standard libraries which can assist in storing these efficiently and -in performing conversions. See the ``array``, ``ustruct`` and ``uctypes`` +in performing conversions. See the `array`, `ustruct` and `uctypes` modules. Footnote: gc.collect() return value ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -On Unix and Windows platforms the ``gc.collect()`` method returns an integer +On Unix and Windows platforms the `gc.collect()` method returns an integer which signifies the number of distinct memory regions that were reclaimed in the collection (more precisely, the number of heads that were turned into frees). For efficiency reasons bare metal ports do not return this value. diff --git a/docs/reference/glossary.rst b/docs/reference/glossary.rst new file mode 100644 index 0000000000..98979afa92 --- /dev/null +++ b/docs/reference/glossary.rst @@ -0,0 +1,105 @@ +Glossary +======== + +.. glossary:: + + baremetal + A system without (full-fledged) OS, like an :term:`MCU`. When + running on a baremetal system, MicroPython effectively becomes + its user-facing OS with a command interpreter (REPL). + + board + A PCB board. Oftentimes, the term is used to denote a particular + model of an :term:`MCU` system. Sometimes, it is used to actually + refer to :term:`MicroPython port` to a particular board (and then + may also refer to "boardless" ports like + :term:`Unix port <MicroPython Unix port>`). + + CPython + CPython is the reference implementation of Python programming + language, and the most well-known one, which most of the people + run. It is however one of many implementations (among which + Jython, IronPython, PyPy, and many more, including MicroPython). + As there is no formal specification of the Python language, only + CPython documentation, it is not always easy to draw a line + between Python the language and CPython its particular + implementation. This however leaves more freedom for other + implementations. For example, MicroPython does a lot of things + differently than CPython, while still aspiring to be a Python + language implementation. + + GPIO + General-purpose input/output. The simplest means to control + electrical signals. With GPIO, user can configure hardware + signal pin to be either input or output, and set or get + its digital signal value (logical "0" or "1"). MicroPython + abstracts GPIO access using :class:`machine.Pin` and :class:`machine.Signal` + classes. + + GPIO port + A group of :term:`GPIO` pins, usually based on hardware + properties of these pins (e.g. controllable by the same + register). + + MCU + Microcontroller. Microcontrollers usually have much less resources + than a full-fledged computing system, but smaller, cheaper and + require much less power. MicroPython is designed to be small and + optimized enough to run on an average modern microcontroller. + + micropython-lib + MicroPython is (usually) distributed as a single executable/binary + file with just few builtin modules. There is no extensive standard + library comparable with :term:`CPython`. Instead, there is a related, but + separate project + `micropython-lib <https://github.com/micropython/micropython-lib>`_ + which provides implementations for many modules from CPython's + standard library. However, large subset of these modules require + POSIX-like environment (Linux, MacOS, Windows may be partially + supported), and thus would work or make sense only with MicroPython + Unix port. Some subset of modules is however usable for baremetal ports + too. + + Unlike monolithic :term:`CPython` stdlib, micropython-lib modules + are intended to be installed individually - either using manual + copying or using :term:`upip`. + + MicroPython port + MicroPython supports different :term:`boards <board>`, RTOSes, + and OSes, and can be relatively easily adapted to new systems. + MicroPython with support for a particular system is called a + "port" to that system. Different ports may have widely different + functionality. This documentation is intended to be a reference + of the generic APIs available across different ports ("MicroPython + core"). Note that some ports may still omit some APIs described + here (e.g. due to resource constraints). Any such differences, + and port-specific extensions beyond MicroPython core functionality, + would be described in the separate port-specific documentation. + + MicroPython Unix port + Unix port is one of the major :term:`MicroPython ports <MicroPython port>`. + It is intended to run on POSIX-compatible operating systems, like + Linux, MacOS, FreeBSD, Solaris, etc. It also serves as the basis + of Windows port. The importance of Unix port lies in the fact + that while there are many different :term:`boards <board>`, so + two random users unlikely have the same board, almost all modern + OSes have some level of POSIX compatibility, so Unix port serves + as a kind of "common ground" to which any user can have access. + So, Unix port is used for initial prototyping, different kinds + of testing, development of machine-independent features, etc. + All users of MicroPython, even those which are interested only + in running MicroPython on :term:`MCU` systems, are recommended + to be familiar with Unix (or Windows) port, as it is important + productivity helper and a part of normal MicroPython workflow. + + port + Either :term:`MicroPython port` or :term:`GPIO port`. If not clear + from context, it's recommended to use full specification like one + of the above. + + upip + (Literally, "micro pip"). A package manage for MicroPython, inspired + by :term:`CPython`'s pip, but much smaller and with reduced functionality. + upip runs both on :term:`Unix port <MicroPython Unix port>` and on + :term:`baremetal` ports (those which offer filesystem and networking + support). diff --git a/docs/reference/index.rst b/docs/reference/index.rst index 7a85fc5cf3..4d822d6fa6 100644 --- a/docs/reference/index.rst +++ b/docs/reference/index.rst @@ -1,17 +1,25 @@ The MicroPython language ======================== -MicroPython aims to implement the Python 3.4 standard, and most of -the features of MicroPython are identical to those described by the -documentation at -`docs.python.org <https://docs.python.org/3.4/reference/index.html>`_. +MicroPython aims to implement the Python 3.4 standard (with selected +features from later versions) with respect to language syntax, and most +of the features of MicroPython are identical to those described by the +"Language Reference" documentation at +`docs.python.org <https://docs.python.org/3/reference/index.html>`_. -Differences to standard Python as well as additional features of -MicroPython are described in the sections here. +The MicroPython standard library is described in the +:ref:`corresponding chapter <micropython_lib>`. The :ref:`cpython_diffs` +chapter describes differences between MicroPython and CPython (which +mostly concern standard library and types, but also some language-level +features). + +This chapter describes features and peculiarities of MicroPython +implementation and the best practices to use them. .. toctree:: :maxdepth: 1 + glossary.rst repl.rst isr_rules.rst speed_python.rst diff --git a/docs/reference/speed_python.rst b/docs/reference/speed_python.rst index 8efba4702b..279a1bbcdc 100644 --- a/docs/reference/speed_python.rst +++ b/docs/reference/speed_python.rst @@ -1,9 +1,11 @@ -Maximising Python Speed -======================= +Maximising MicroPython Speed +============================ + +.. contents:: This tutorial describes ways of improving the performance of MicroPython code. Optimisations involving other languages are covered elsewhere, namely the use -of modules written in C and the MicroPython inline ARM Thumb-2 assembler. +of modules written in C and the MicroPython inline assembler. The process of developing high performance code comprises the following stages which should be performed in the order listed. @@ -17,6 +19,7 @@ Optimisation steps: * Improve the efficiency of the Python code. * Use the native code emitter. * Use the viper code emitter. +* Use hardware-specific optimisations. Designing for speed ------------------- @@ -50,7 +53,7 @@ once only and not permitted to grow in size. This implies that the object persis for the duration of its use: typically it will be instantiated in a class constructor and used in various methods. -This is covered in further detail :ref:`Controlling garbage collection <gc>` below. +This is covered in further detail :ref:`Controlling garbage collection <controlling_gc>` below. Buffers ~~~~~~~ @@ -60,8 +63,8 @@ used for communication with a device. A typical driver will create the buffer in constructor and use it in its I/O methods which will be called repeatedly. The MicroPython libraries typically provide support for pre-allocated buffers. For -example, objects which support stream interface (e.g., file or UART) provide ``read()`` -method which allocate new buffer for read data, but also a ``readinto()`` method +example, objects which support stream interface (e.g., file or UART) provide `read()` +method which allocates new buffer for read data, but also a `readinto()` method to read data into an existing buffer. Floating Point @@ -79,14 +82,14 @@ Arrays ~~~~~~ Consider the use of the various types of array classes as an alternative to lists. -The ``array`` module supports various element types with 8-bit elements supported -by Python's built in ``bytes`` and ``bytearray`` classes. These data structures all store +The `array` module supports various element types with 8-bit elements supported +by Python's built in `bytes` and `bytearray` classes. These data structures all store elements in contiguous memory locations. Once again to avoid memory allocation in critical code these should be pre-allocated and passed as arguments or as bound objects. -When passing slices of objects such as ``bytearray`` instances, Python creates +When passing slices of objects such as `bytearray` instances, Python creates a copy which involves allocation of the size proportional to the size of slice. -This can be alleviated using a ``memoryview`` object. ``memoryview`` itself +This can be alleviated using a `memoryview` object. `memoryview` itself is allocated on heap, but is a small, fixed-size object, regardless of the size of slice it points too. @@ -97,7 +100,7 @@ of slice it points too. mv = memoryview(ba) # small object is allocated func(mv[30:2000]) # a pointer to memory is passed -A ``memoryview`` can only be applied to objects supporting the buffer protocol - this +A `memoryview` can only be applied to objects supporting the buffer protocol - this includes arrays but not lists. Small caveat is that while memoryview object is live, it also keeps alive the original buffer object. So, a memoryview isn't a universal panacea. For instance, in the example above, if you are done with 10K buffer and @@ -105,11 +108,11 @@ just need those bytes 30:2000 from it, it may be better to make a slice, and let the 10K buffer go (be ready for garbage collection), instead of making a long-living memoryview and keeping 10K blocked for GC. -Nonetheless, ``memoryview`` is indispensable for advanced preallocated buffer -management. ``.readinto()`` method discussed above puts data at the beginning +Nonetheless, `memoryview` is indispensable for advanced preallocated buffer +management. `readinto()` method discussed above puts data at the beginning of buffer and fills in entire buffer. What if you need to put data in the middle of existing buffer? Just create a memoryview into the needed section -of buffer and pass it to ``.readinto()``. +of buffer and pass it to `readinto()`. Identifying the slowest section of code --------------------------------------- @@ -118,8 +121,7 @@ This is a process known as profiling and is covered in textbooks and (for standard Python) supported by various software tools. For the type of smaller embedded application likely to be running on MicroPython platforms the slowest function or method can usually be established by judicious use -of the timing ``ticks`` group of functions documented -`here <http://docs.micropython.org/en/latest/pyboard/library/time.html>`_. +of the timing ``ticks`` group of functions documented in `utime`. Code execution time can be measured in ms, us, or CPU cycles. The following enables any function or method to be timed by adding an @@ -130,9 +132,9 @@ The following enables any function or method to be timed by adding an def timed_function(f, *args, **kwargs): myname = str(f).split(' ')[1] def new_func(*args, **kwargs): - t = time.ticks_us() + t = utime.ticks_us() result = f(*args, **kwargs) - delta = time.ticks_diff(time.ticks_us(), t) + delta = utime.ticks_diff(utime.ticks_us(), t) print('Function {} Time = {:6.3f}ms'.format(myname, delta/1000)) return result return new_func @@ -170,7 +172,7 @@ by caching the object in a local variable: This avoids the need repeatedly to look up ``self.ba`` and ``obj_display.framebuffer`` in the body of the method ``bar()``. -.. _gc: +.. _controlling_gc: Controlling garbage collection ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -182,7 +184,7 @@ process known as garbage collection reclaims the memory used by these redundant objects and the allocation is then tried again - a process which can take several milliseconds. -There are benefits in pre-empting this by periodically issuing ``gc.collect()``. +There may be benefits in pre-empting this by periodically issuing `gc.collect()`. Firstly doing a collection before it is actually required is quicker - typically on the order of 1ms if done frequently. Secondly you can determine the point in code where this time is used rather than have a longer delay occur at random points, @@ -190,34 +192,11 @@ possibly in a speed critical section. Finally performing collections regularly can reduce fragmentation in the heap. Severe fragmentation can lead to non-recoverable allocation failures. -Accessing hardware directly -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This comes into the category of more advanced programming and involves some knowledge -of the target MCU. Consider the example of toggling an output pin on the Pyboard. The -standard approach would be to write - -.. code:: python - - mypin.value(mypin.value() ^ 1) # mypin was instantiated as an output pin - -This involves the overhead of two calls to the ``Pin`` instance's ``value()`` -method. This overhead can be eliminated by performing a read/write to the relevant bit -of the chip's GPIO port output data register (odr). To facilitate this the ``stm`` -module provides a set of constants providing the addresses of the relevant registers. -A fast toggle of pin ``P4`` (CPU pin ``A14``) - corresponding to the green LED - -can be performed as follows: - -.. code:: python - - BIT14 = const(1 << 14) - stm.mem16[stm.GPIOA + stm.GPIO_ODR] ^= BIT14 - The Native code emitter ----------------------- -This causes the MicroPython compiler to emit ARM native opcodes rather than -bytecode. It covers the bulk of the Python language so most functions will require +This causes the MicroPython compiler to emit native CPU opcodes rather than +bytecode. It covers the bulk of the MicroPython functionality, so most functions will require no adaptation (but see below). It is invoked by means of a function decorator: .. code:: python @@ -276,7 +255,7 @@ Viper provides pointer types to assist the optimiser. These comprise * ``ptr32`` Points to a 32 bit machine word. The concept of a pointer may be unfamiliar to Python programmers. It has similarities -to a Python ``memoryview`` object in that it provides direct access to data stored in memory. +to a Python `memoryview` object in that it provides direct access to data stored in memory. Items are accessed using subscript notation, but slices are not supported: a pointer can return a single item only. Its purpose is to provide fast random access to data stored in contiguous memory locations - such as data stored in objects which support the buffer protocol, and @@ -330,3 +309,34 @@ The following example illustrates the use of a ``ptr16`` cast to toggle pin X1 ` A detailed technical description of the three code emitters may be found on Kickstarter here `Note 1 <https://www.kickstarter.com/projects/214379695/micro-python-python-for-microcontrollers/posts/664832>`_ and here `Note 2 <https://www.kickstarter.com/projects/214379695/micro-python-python-for-microcontrollers/posts/665145>`_ + +Accessing hardware directly +--------------------------- + +.. note:: + + Code examples in this section are given for the Pyboard. The techniques + described however may be applied to other MicroPython ports too. + +This comes into the category of more advanced programming and involves some knowledge +of the target MCU. Consider the example of toggling an output pin on the Pyboard. The +standard approach would be to write + +.. code:: python + + mypin.value(mypin.value() ^ 1) # mypin was instantiated as an output pin + +This involves the overhead of two calls to the `Pin` instance's :meth:`~machine.Pin.value()` +method. This overhead can be eliminated by performing a read/write to the relevant bit +of the chip's GPIO port output data register (odr). To facilitate this the ``stm`` +module provides a set of constants providing the addresses of the relevant registers. +A fast toggle of pin ``P4`` (CPU pin ``A14``) - corresponding to the green LED - +can be performed as follows: + +.. code:: python + + import machine + import stm + + BIT14 = const(1 << 14) + machine.mem16[stm.GPIOA + stm.GPIO_ODR] ^= BIT14 diff --git a/docs/templates/replace.inc b/docs/templates/replace.inc new file mode 100644 index 0000000000..319c53735f --- /dev/null +++ b/docs/templates/replace.inc @@ -0,0 +1,9 @@ +.. comment: This file is intended for global "replace" definitions. + +.. |see_cpython| replace:: See CPython documentation: + +.. |see_cpython_module| replace:: + + *This module implements a subset of the corresponding* `CPython` *module, + as described below. For more information, refer to the original + CPython documentation:* diff --git a/docs/topindex.html b/docs/templates/topindex.html index f32f3cea6b..76e5e18d72 100644 --- a/docs/topindex.html +++ b/docs/templates/topindex.html @@ -57,16 +57,6 @@ <a class="biglink" href="{{ pathto("reference/index") }}">Language Reference</a><br/> <span class="linkdescr">information about MicroPython specific language features</span> </p> - {% if port == "pyboard" %} - <p class="biglink"> - <a class="biglink" href="{{ pathto(port + "/hardware/index") }}">The {{ port }} hardware</a><br/> - <span class="linkdescr">schematics, dimensions and component datasheets</span> - </p> - <p class="biglink"> - <a class="biglink" href="http://micropython.org/resources/Micro-Python-Windows-setup.pdf">Guide for {{ port_name }} on Windows (PDF)</a><br/> - <span class="linkdescr">including DFU programming</span> - </p> - {% endif %} <p class="biglink"> <a class="biglink" href="{{ pathto("license") }}">License</a><br/> <span class="linkdescr">MicroPython license information</span> @@ -88,7 +78,11 @@ </td> <td width="40%" style="padding-left:2em;"> <p class="biglink"> - <a class="biglink" href="{{ pathto(port + "_contents") }}">Table of contents</a><br/> + <a class="biglink" href="{{ pathto("reference/glossary") }}">Glossary</a><br/> + <span class="linkdescr">MicroPython terms explained</span> + </p> + <p class="biglink"> + <a class="biglink" href="{{ pathto(port + "_index") }}">Table of contents</a><br/> <span class="linkdescr">a list of all sections and subsections</span> </p> </td></tr> @@ -112,12 +106,6 @@ <a class="biglink" href="https://github.com/micropython">MicroPython on GitHub</a><br/> <span class="linkdescr">contribute to the source code on GitHub</span> </p> - {% if port == "wipy" %} - <p class="biglink"> - <a class="biglink" href="http://wipy.io">The WiPy homepage</a><br/> - <span class="linkdescr">the official WiPy site</span> - </p> - {% endif %} </td> </tr></table> diff --git a/docs/unix_contents.rst b/docs/unix_contents.rst deleted file mode 100644 index 8c5a586b29..0000000000 --- a/docs/unix_contents.rst +++ /dev/null @@ -1,9 +0,0 @@ -MicroPython documentation contents -================================== - -.. toctree:: - - library/index.rst - reference/index.rst - genrst/index.rst - license.rst diff --git a/docs/unix_index.rst b/docs/unix_index.rst index 7fa1753c23..1bfeb0bdac 100644 --- a/docs/unix_index.rst +++ b/docs/unix_index.rst @@ -4,13 +4,6 @@ MicroPython documentation and references .. toctree:: library/index.rst + reference/index.rst genrst/index.rst license.rst - unix_contents.rst - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` diff --git a/docs/wipy_contents.rst b/docs/wipy_contents.rst deleted file mode 100644 index 0e50a7c6ee..0000000000 --- a/docs/wipy_contents.rst +++ /dev/null @@ -1,12 +0,0 @@ -MicroPython documentation contents -================================== - -.. toctree:: - - wipy/quickref.rst - wipy/general.rst - wipy/tutorial/index.rst - library/index.rst - reference/index.rst - genrst/index.rst - license.rst diff --git a/docs/wipy_index.rst b/docs/wipy_index.rst index a390aecb1e..15c04c0fba 100644 --- a/docs/wipy_index.rst +++ b/docs/wipy_index.rst @@ -7,13 +7,6 @@ MicroPython documentation and references wipy/general.rst wipy/tutorial/index.rst library/index.rst + reference/index.rst genrst/index.rst license.rst - wipy_contents.rst - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` |