diff options
Diffstat (limited to 'docs/library')
-rw-r--r-- | docs/library/esp.rst | 6 | ||||
-rw-r--r-- | docs/library/index.rst | 152 | ||||
-rw-r--r-- | docs/library/machine.I2C.rst | 154 | ||||
-rw-r--r-- | docs/library/machine.Pin.rst | 113 | ||||
-rw-r--r-- | docs/library/machine.rst | 82 | ||||
-rw-r--r-- | docs/library/network.rst | 51 | ||||
-rw-r--r-- | docs/library/pyb.UART.rst | 93 | ||||
-rw-r--r-- | docs/library/struct.rst | 25 | ||||
-rw-r--r-- | docs/library/sys.rst | 84 | ||||
-rw-r--r-- | docs/library/time.rst | 89 | ||||
-rw-r--r-- | docs/library/ubinascii.rst | 8 | ||||
-rw-r--r-- | docs/library/ucollections.rst | 53 | ||||
-rw-r--r-- | docs/library/uio.rst | 46 | ||||
-rw-r--r-- | docs/library/uos.rst (renamed from docs/library/os.rst) | 6 | ||||
-rw-r--r-- | docs/library/usocket.rst | 42 | ||||
-rw-r--r-- | docs/library/ussl.rst | 4 | ||||
-rw-r--r-- | docs/library/ustruct.rst | 37 | ||||
-rw-r--r-- | docs/library/utime.rst | 139 |
18 files changed, 832 insertions, 352 deletions
diff --git a/docs/library/esp.rst b/docs/library/esp.rst index 040d62f769..34d3c278d9 100644 --- a/docs/library/esp.rst +++ b/docs/library/esp.rst @@ -39,3 +39,9 @@ Functions .. function:: flash_id() Read the device ID of the flash memory. + +.. function:: flash_read(byte_offset, length_or_buffer) + +.. function:: flash_write(byte_offset, bytes) + +.. function:: flash_erase(sector_no) diff --git a/docs/library/index.rst b/docs/library/index.rst index 47cd2eeb8e..03e6502d95 100644 --- a/docs/library/index.rst +++ b/docs/library/index.rst @@ -1,59 +1,88 @@ MicroPython libraries ===================== -Functionality specific to the MicroPython implementation is available in -the following library. +The following standard Python libraries are built in to MicroPython. -.. toctree:: - :maxdepth: 1 +For additional libraries, please download them from the `micropython-lib repository +<https://github.com/micropython/micropython-lib>`_. - micropython.rst +Python standard libraries and micro-libraries +--------------------------------------------- -Python standard libraries -------------------------- +The following standard Python libraries have been "micro-ified" to fit in with +the philosophy of MicroPython. They provide the core functionality of that +module and are intended to be a drop-in replacement for the standard Python +library. -The following standard Python libraries are built in to MicroPython. +.. only:: not port_unix -For additional libraries, please download them from the `micropython-lib repository -<https://github.com/micropython/micropython-lib>`_. + The modules are available by their u-name, and also by their non-u-name. The + non-u-name can be overridden by a file of that name in your package path. + For example, ``import json`` will first search for a file ``json.py`` or + directory ``json`` and load that package if it is found. If nothing is found, + it will fallback to loading the built-in ``ujson`` module. .. only:: port_unix .. toctree:: :maxdepth: 1 - + cmath.rst gc.rst math.rst - os.rst - struct.rst + select.rst sys.rst - time.rst + ubinascii.rst + ucollections.rst + uhashlib.rst + uheapq.rst + uio.rst + ujson.rst + uos.rst + ure.rst + usocket.rst + ustruct.rst + utime.rst + uzlib.rst .. only:: port_pyboard .. toctree:: :maxdepth: 1 - + cmath.rst gc.rst math.rst - os.rst select.rst - struct.rst sys.rst - time.rst + ubinascii.rst + ucollections.rst + uhashlib.rst + uheapq.rst + uio.rst + ujson.rst + uos.rst + ure.rst + usocket.rst + ustruct.rst + utime.rst + uzlib.rst .. only:: port_wipy .. toctree:: :maxdepth: 1 - + gc.rst - os.rst select.rst sys.rst - time.rst + ubinascii.rst + ujson.rst + uos.rst + ure.rst + usocket.rst + ussl.rst + utime.rst .. only:: port_esp8266 @@ -62,52 +91,35 @@ For additional libraries, please download them from the `micropython-lib reposit gc.rst math.rst - struct.rst sys.rst - time.rst - -Python micro-libraries ----------------------- + ubinascii.rst + ucollections.rst + uhashlib.rst + uheapq.rst + uio.rst + ujson.rst + uos.rst + ure.rst + usocket.rst + ustruct.rst + utime.rst + uzlib.rst + + +MicroPython-specific libraries +------------------------------ -The following standard Python libraries have been "micro-ified" to fit in with -the philosophy of MicroPython. They provide the core functionality of that -module and are intended to be a drop-in replacement for the standard Python -library. - -.. only:: not port_unix - - The modules are available by their u-name, and also by their non-u-name. The - non-u-name can be overridden by a file of that name in your package path. - For example, ``import json`` will first search for a file ``json.py`` or - directory ``json`` and load that package if it is found. If nothing is found, - it will fallback to loading the built-in ``ujson`` module. - -.. only:: port_pyboard or port_unix - - .. toctree:: - :maxdepth: 1 - - ubinascii.rst - uctypes.rst - uhashlib.rst - uheapq.rst - ujson.rst - ure.rst - usocket.rst - uzlib.rst +Functionality specific to the MicroPython implementation is available in +the following libraries. -.. only:: port_esp8266 +.. toctree:: + :maxdepth: 1 - .. toctree:: - :maxdepth: 1 + machine.rst + micropython.rst + network.rst + uctypes.rst - ubinascii.rst - uctypes.rst - uhashlib.rst - uheapq.rst - ujson.rst - ure.rst - uzlib.rst .. only:: port_pyboard @@ -120,18 +132,6 @@ library. :maxdepth: 2 pyb.rst - network.rst - -.. only:: port_wipy - - .. toctree:: - :maxdepth: 1 - - ubinascii.rst - ujson.rst - ure.rst - usocket.rst - ussl.rst .. only:: port_wipy @@ -143,8 +143,6 @@ library. .. toctree:: :maxdepth: 2 - machine.rst - network.rst wipy.rst @@ -158,6 +156,4 @@ library. .. toctree:: :maxdepth: 2 - network.rst esp.rst - machine.rst diff --git a/docs/library/machine.I2C.rst b/docs/library/machine.I2C.rst index aa1caed209..a7e90ca39b 100644 --- a/docs/library/machine.I2C.rst +++ b/docs/library/machine.I2C.rst @@ -49,12 +49,15 @@ Constructors Construct an I2C object on the given bus. `bus` can only be 0. If the bus is not given, the default one will be selected (0). -Methods -------- +.. only:: port_esp8266 -.. method:: i2c.deinit() + .. class:: machine.I2C(scl, sda, \*, freq=400000) - Turn off the I2C bus. + Construct and return a new I2C object. + See the init method below for a description of the arguments. + +General Methods +--------------- .. only:: port_wipy @@ -66,48 +69,131 @@ Methods - ``baudrate`` is the SCL clock rate - ``pins`` is an optional tuple with the pins to assign to the I2C bus. - .. method:: i2c.readfrom(addr, nbytes) +.. only:: port_esp8266 + + .. method:: i2c.init(scl, sda, \*, freq=400000) + + Initialise the I2C bus with the given arguments: - Read ``nbytes`` from the slave specified by ``addr``. - Returns a ``bytes`` object with the data read. + - `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.readfrom_into(addr, buf) +.. method:: i2c.deinit() - Read into ``buf`` from the slave specified by ``addr``. - Returns the number of bytes read. + Turn off the I2C bus. - .. method:: i2c.writeto(addr, buf, \*, stop=True) + Availability: WiPy. - Write ``buf`` to the slave specified by ``addr``. Set ``stop`` to ``False`` - if the transfer should be continued. - Returns the number of bytes written. +.. method:: i2c.scan() - .. method:: i2c.readfrom_mem(addr, memaddr, nbytes, \*, addrsize=8) + Scan all I2C addresses between 0x08 and 0x77 inclusive and return a list of + those that respond. A device responds if it pulls the SDA line low after + its address (including a read bit) is sent on the bus. - Read ``nbytes`` from the slave specified by ``addr`` starting from the memory - address specified by ``memaddr``. - Param ``addrsize`` specifies the address size in bits. - Returns a ``bytes`` object with the data read. + Note: on WiPy the I2C object must be in master mode for this method to be valid. - .. method:: i2c.readfrom_mem_into(addr, memaddr, buf, \*, addrsize=8) +Primitive I2C operations +------------------------ - Read into ``buf`` from the slave specified by ``addr`` starting from the memory - address specified by ``memaddr``. - Param ``addrsize`` specifies the address size in bits. - Returns the number of bytes read. +The following methods implement the primitive I2C master bus operations and can +be combined to make any I2C transaction. They are provided if you need more +control over the bus, otherwise the standard methods (see below) can be used. - .. method:: i2c.writeto_mem(addr, memaddr, buf, \*, addrsize=8) +.. method:: i2c.start() - Write ``buf`` to the slave specified by ``addr`` starting from the - memory address specified by ``memaddr``. Param ``addrsize`` specifies the - address size in bits. - Set ``stop`` to ``False`` if the transfer should be continued. - Returns the number of bytes written. + Send a start bit on the bus (SDA transitions to low while SCL is high). -.. method:: i2c.scan() + Availability: ESP8266. + +.. method:: i2c.stop() + + Send a stop bit on the bus (SDA transitions to high while SCL is high). + + Availability: ESP8266. + +.. method:: i2c.readinto(buf) + + 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, and a NACK will be sent following the last + byte. + + Availability: ESP8266. + +.. method:: i2c.write(buf) + + Write all the bytes from `buf` to the bus. Checks that an ACK is received + after each byte and raises an OSError if not. + + Availability: ESP8266. + +Standard bus operations +----------------------- + +The following methods implement the standard I2C master read and write +operations that target a given slave device. - Scan all I2C addresses from 0x01 to 0x7f and return a list of those that respond. - Only valid when in master mode. +.. method:: i2c.readfrom(addr, nbytes) + + Read `nbytes` from the slave specified by `addr`. + Returns a `bytes` object with the data read. + +.. method:: i2c.readfrom_into(addr, buf) + + Read into `buf` from the slave specified by `addr`. + The number of bytes read will be the length of `buf`. + + On WiPy the return value is the number of bytes read. Otherwise the + return value is `None`. + +.. method:: i2c.writeto(addr, buf, \*, stop=True) + + Write the bytes from `buf` to the slave specified by `addr`. + + The `stop` argument (only available on WiPy) tells if a stop bit should be + sent at the end of the transfer. If `False` the transfer should be + continued later on. + + On WiPy the return value is the number of bytes written. Otherwise the + return value is `None`. + +Memory operations +----------------- + +Some I2C devices act as a memory device (or set of registers) that can be read +from and written to. In this case there are two addresses associated with an +I2C transaction: the slave address and the memory address. The following +methods are convenience functions to communicate with such devices. + +.. method:: i2c.readfrom_mem(addr, memaddr, nbytes, \*, addrsize=8) + + Read `nbytes` from the 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). + 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 + this argument is not recognised and the address size is always 8 bits). + + On WiPy the return value is the number of bytes read. Otherwise the + return value is `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 + this argument is not recognised and the address size is always 8 bits). + + On WiPy the return value is the number of bytes written. Otherwise the + return value is `None`. Constants --------- @@ -115,3 +201,5 @@ Constants .. data:: I2C.MASTER for initialising the bus to master mode + + Availability: WiPy. diff --git a/docs/library/machine.Pin.rst b/docs/library/machine.Pin.rst index 6fa2b170e8..a2e97c87c2 100644 --- a/docs/library/machine.Pin.rst +++ b/docs/library/machine.Pin.rst @@ -39,6 +39,21 @@ Usage Model: All pin objects go through the pin mapper to come up with one of the gpio pins. +.. only:: port_esp8266 + + :: + + from machine import Pin + + # create an output pin on GPIO0 + p0 = Pin(0, Pin.OUT) + p0.value(0) + p0.value(1) + + # create an input pin on GPIO2 + p2 = Pin(2, Pin.IN, Pin.PULL_UP) + print(p2.value()) + Constructors ------------ @@ -86,6 +101,25 @@ Methods Get the pin id. +.. only:: port_esp8266 + + .. method:: pin.init(mode, pull=None, \*, value) + + Initialise the pin: + + - `mode` can be one of: + + - ``Pin.IN`` - input pin. + - ``Pin.OUT`` - output pin in push-pull mode. + + - `pull` can be one of: + + - ``None`` - no pull up or down resistor. + - ``Pin.PULL_UP`` - pull up resistor enabled. + + - if `value` is given then it is the output value to set the pin + if it is in output mode. + .. method:: pin.value([value]) Get or set the digital logic level of the pin: @@ -95,17 +129,19 @@ Methods anything that converts to a boolean. If it converts to ``True``, the pin is set high, otherwise it is set low. +.. method:: pin([value]) + + Pin objects are callable. The call method provides a (fast) shortcut to set and get the value of the pin. + See **pin.value** for more details. + .. method:: pin.alt_list() Returns a list of the alternate functions supported by the pin. List items are a tuple of the form: ``('ALT_FUN_NAME', ALT_FUN_INDEX)`` -.. only:: port_wipy - - .. method:: pin([value]) + Availability: WiPy. - Pin objects are callable. The call method provides a (fast) shortcut to set and get the value of the pin. - See **pin.value** for more details. +.. only:: port_wipy .. method:: pin.toggle() @@ -155,6 +191,23 @@ Methods Returns a callback object. +.. only:: port_esp8266 + + .. method:: pin.irq(\*, trigger, handler=None) + + Create a callback to be triggered when the input level at the pin changes. + + - ``trigger`` configures the pin level which can generate an interrupt. Possible values are: + + - ``Pin.IRQ_FALLING`` interrupt on falling edge. + - ``Pin.IRQ_RISING`` interrupt on rising edge. + + The values can be OR'ed together to trigger on multiple events. + + - ``handler`` is an optional function to be called when the interrupt triggers. + + Returns a callback object. + Attributes ---------- @@ -166,44 +219,36 @@ Attributes led = Pin(Pin.board.GP25, mode=Pin.OUT) Pin.board.GP2.alt_list() + Availability: WiPy. Constants --------- -.. only:: port_wipy - - .. data:: Pin.IN - - .. data:: Pin.OUT - - .. data:: Pin.OPEN_DRAIN - - .. data:: Pin.ALT - - .. data:: Pin.ALT_OPEN_DRAIN - - Selects the pin mode. - - .. data:: Pin.PULL_UP - - .. data:: Pin.PULL_DOWN - - Selectes the wether there's pull up/down resistor. - - .. data:: Pin.LOW_POWER +The following constants are used to configure the pin objects. Note that +not all constants are available on all ports. - .. data:: Pin.MED_POWER +.. data:: IN + OUT + OPEN_DRAIN + ALT + ALT_OPEN_DRAIN - .. data:: Pin.HIGH_POWER + Selects the pin mode. - Selects the drive strength. +.. data:: PULL_UP + PULL_DOWN - .. data:: Pin.IRQ_FALLING + Selects the whether there is a pull up/down resistor. - .. data:: Pin.IRQ_RISING +.. data:: LOW_POWER + MED_POWER + HIGH_POWER - .. data:: Pin.IRQ_LOW_LEVEL + Selects the pin drive strength. - .. data:: Pin.IRQ_HIGH_LEVEL +.. data:: IRQ_FALLING + IRQ_RISING + IRQ_LOW_LEVEL + IRQ_HIGH_LEVEL - Selects the IRQ trigger type. + Selects the IRQ trigger type. diff --git a/docs/library/machine.rst b/docs/library/machine.rst index dacfe737b9..14d75cb466 100644 --- a/docs/library/machine.rst +++ b/docs/library/machine.rst @@ -18,76 +18,90 @@ Reset related functions Get the reset cause. See :ref:`constants <machine_constants>` for the possible return values. -Interrupt related functions ---------------------------- +.. only:: port_wipy -.. function:: disable_irq() + Interrupt related functions + --------------------------- - Disable interrupt requests. - Returns the previous IRQ state: ``False``/``True`` for disabled/enabled IRQs - respectively. This return value can be passed to enable_irq to restore - the IRQ to its original state. + .. function:: disable_irq() -.. function:: enable_irq(state=True) + Disable interrupt requests. + Returns the previous IRQ state: ``False``/``True`` for disabled/enabled IRQs + respectively. This return value can be passed to enable_irq to restore + the IRQ to its original state. - Enable interrupt requests. - If ``state`` is ``True`` (the default value) then IRQs are enabled. - If ``state`` is ``False`` then IRQs are disabled. The most common use of - this function is to pass it the value returned by ``disable_irq`` to - exit a critical section. + .. function:: enable_irq(state=True) + + Enable interrupt requests. + If ``state`` is ``True`` (the default value) then IRQs are enabled. + If ``state`` is ``False`` then IRQs are disabled. The most common use of + this function is to pass it the value returned by ``disable_irq`` to + exit a critical section. Power related functions ----------------------- .. function:: freq() - Returns a tuple of clock frequencies: ``(sysclk,)`` - These correspond to: + .. only:: not port_wipy + + Returns CPU frequency in hertz. + + .. only:: port_wipy - - sysclk: frequency of the CPU + Returns a tuple of clock frequencies: ``(sysclk,)`` + These correspond to: + + - sysclk: frequency of the CPU .. function:: idle() Gates the clock to the CPU, useful to reduce power consumption at any time during short or long periods. Peripherals continue working and execution resumes as soon - as any interrupt is triggered (including the systick which has a period of 1ms). - Current consumption is reduced to ~12mA (in WLAN STA mode) + as any interrupt is triggered (on many ports this includes system timer + interrupt occuring at regular intervals on the order of millisecond). .. function:: sleep() Stops the CPU and disables all peripherals except for WLAN. Execution is resumed from - the point where the sleep was requested. Wake sources are ``Pin``, ``RTC`` and ``WLAN``. - Current consumption is reduced to 950uA (in WLAN STA mode). + the point where the sleep was requested. For wake up to actually happen, wake sources + should be configured first. .. function:: deepsleep() - Stops the CPU and all peripherals including WLAN. Execution is resumed from main, just - as with a reset. The reset cause can be checked to know that we are coming from - from ``machine.DEEPSLEEP``. Wake sources are ``Pin`` and ``RTC``. Current consumption - is reduced to ~5uA. + 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. + +.. only:: port_wipy -.. function:: wake_reason() + .. function:: wake_reason() - Get the wake reason. See :ref:`constants <machine_constants>` for the possible return values. + Get the wake reason. See :ref:`constants <machine_constants>` for the possible return values. Miscellaneous functions ----------------------- -.. function:: main(filename) +.. only:: port_wipy + + .. function:: main(filename) - Set the filename of the main script to run after boot.py is finished. If - this function is not called then the default file main.py will be executed. + Set the filename of the main script to run after boot.py is finished. If + this function is not called then the default file main.py will be executed. - It only makes sense to call this function from within boot.py. + It only makes sense to call this function from within boot.py. -.. function:: rng() + .. function:: rng() - Return a 24-bit software generated random number. + Return a 24-bit software generated random number. .. function:: unique_id() - Returns a string of 6 bytes (48 bits), which is the unique ID of the MCU. - This also corresponds to the network ``MAC address``. + Returns a byte string with a unique idenifier of a board/SoC. It will vary + from a board/SoC instance to another, if underlying hardware allows. Length + varies by hardware (so use substring of a full value if you expect a short + ID). In some MicroPython ports, ID corresponds to the network MAC address. .. _machine_constants: diff --git a/docs/library/network.rst b/docs/library/network.rst index 49e7e53bf8..fe4eaa7525 100644 --- a/docs/library/network.rst +++ b/docs/library/network.rst @@ -283,14 +283,6 @@ For example:: Disconnect from the currently connected wireless network. - .. method:: wlan.mac([address]) - - Get or set the network interface MAC address. - - If the ``address`` parameter is provided, sets the address to its - value, which should be bytes object of length 6. If the function - is called wihout parameters, returns the current address. - .. method:: wlan.scan() Scan for the available wireless networks. @@ -300,6 +292,9 @@ For example:: (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. + There are five values for authmode: * 0 -- open @@ -332,6 +327,46 @@ For example:: point and has a valid IP address. In AP mode returns ``True`` when a station is connected. Returns ``False`` otherwise. + .. method:: wlan.ifconfig([(ip, subnet, gateway, dns)]) + + Get/set IP-level network interface paremeters: IP address, subnet mask, + gateway and DNS server. When called with no arguments, this method returns + a 4-tuple with the above information. To set the above values, pass a + 4-tuple with the required information. For example:: + + nic.ifconfig(('192.168.0.4', '255.255.255.0', '192.168.0.1', '8.8.8.8')) + + .. method:: wlan.config('param') + .. method:: wlan.config(param=value, ...) + + 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 + parameters. For setting parameters, keyword argument syntax should be used, + multiple parameters can be set at once. For querying, paremeters name should + be quoted as a string, and only one paramter can be queries at time:: + + # Set WiFi access point name (formally known as ESSID) and WiFi channel + ap.config(essid='My AP', channel=11) + # Queey params one by one + print(ap.config('essid')) + print(ap.config('channel')) + + Following are commonly supported parameters (availability of a specific parameter + depends on network technology type, driver, and MicroPython port). + + ========= =========== + Parameter Description + ========= =========== + mac MAC address (bytes) + essid WiFi access point name (string) + channel WiFi channel (integer) + hidden Whether ESSID is hidden (boolean) + authmode Authentication mode supported (enumeration, see module constants) + password Access password (string) + ========= =========== + + .. only:: port_wipy diff --git a/docs/library/pyb.UART.rst b/docs/library/pyb.UART.rst index 5fc5b22a5a..536b6f467d 100644 --- a/docs/library/pyb.UART.rst +++ b/docs/library/pyb.UART.rst @@ -40,7 +40,8 @@ using the standard stream methods:: To check if there is anything to be read, use:: - uart.any() # returns True if any characters waiting + uart.any() # returns the number of characters waiting + *Note:* The stream functions ``read``, ``write``, etc. are new in MicroPython v1.3.4. Earlier versions use ``uart.send`` and ``uart.recv``. @@ -57,7 +58,7 @@ Constructors initialised (it has the settings from the last initialisation of the bus, if any). If extra arguments are given, the bus is initialised. See ``init`` for parameters of initialisation. - + The physical pins of the UART busses are: - ``UART(4)`` is on ``XA``: ``(TX, RX) = (X1, X2) = (PA0, PA1)`` @@ -66,12 +67,16 @@ Constructors - ``UART(3)`` is on ``YB``: ``(TX, RX) = (Y9, Y10) = (PB10, PB11)`` - ``UART(2)`` is on: ``(TX, RX) = (X3, X4) = (PA2, PA3)`` + The Pyboard Lite supports UART(1), UART(2) and UART(6) only. Pins are as above except: + + - ``UART(2)`` is on: ``(TX, RX) = (X1, X2) = (PA2, PA3)`` + Methods ------- .. only:: port_pyboard - .. method:: uart.init(baudrate, bits=8, parity=None, stop=1, \*, timeout=1000, flow=None, timeout_char=0, read_buf_len=64) + .. method:: uart.init(baudrate, bits=8, parity=None, stop=1, \*, timeout=1000, flow=0, timeout_char=0, read_buf_len=64) Initialise the UART bus with the given parameters: @@ -79,7 +84,7 @@ Methods - ``bits`` is the number of bits per character, 7, 8 or 9. - ``parity`` is the parity, ``None``, 0 (even) or 1 (odd). - ``stop`` is the number of stop bits, 1 or 2. - - ``flow`` sets the flow control type. Can be None, ``UART.RTS``, ``UART.CTS`` + - ``flow`` sets the flow control type. Can be 0, ``UART.RTS``, ``UART.CTS`` or ``UART.RTS | UART.CTS``. - ``timeout`` is the timeout in milliseconds to wait for the first character. - ``timeout_char`` is the timeout in milliseconds to wait between characters. @@ -103,16 +108,18 @@ Methods .. method:: uart.any() - Returns the number of characters waiting (may be 0). + Returns the number of bytes waiting (may be 0). .. method:: uart.writechar(char) Write a single character on the bus. ``char`` is an integer to write. - Return value: ``None``. + Return value: ``None``. See note below if CTS flow control is used. .. method:: uart.read([nbytes]) Read characters. If ``nbytes`` is specified then read at most that many bytes. + If ``nbytes`` are available in the buffer, returns immediately, otherwise returns + when sufficient characters arrive or the timeout elapses. .. only:: port_pyboard @@ -124,9 +131,9 @@ Methods .. method:: uart.readall() - Read as much data as possible. + Read as much data as possible. Returns after the timeout has elapsed. - Return value: a bytes object or ``None`` on timeout. + Return value: a bytes object or ``None`` if timeout prevents any data being read. .. method:: uart.readchar() @@ -144,9 +151,11 @@ Methods .. method:: uart.readline() - Read a line, ending in a newline character. + Read a line, ending in a newline character. If such a line exists, return is + immediate. If the timeout elapses, all available data is returned regardless + of whether a newline exists. - Return value: the line read or ``None`` on timeout. + Return value: the line read or ``None`` on timeout if no data is available. .. method:: uart.write(buf) @@ -157,7 +166,8 @@ Methods bytes are used for each character (little endian), and ``buf`` must contain an even number of bytes. - Return value: number of bytes written or ``None`` on timeout. + Return value: number of bytes written. If a timeout occurs and no bytes + were written returns ``None``. .. method:: uart.sendbreak() @@ -173,4 +183,63 @@ Constants .. data:: UART.RTS .. data:: UART.CTS - to select the flow control type + to select the flow control type. + +Flow Control +------------ + +.. only:: port_pyboard + + On Pyboards V1 and V1.1 ``UART(2)`` and ``UART(3)`` support RTS/CTS hardware flow control + using the following pins: + + - ``UART(2)`` is on: ``(TX, RX, nRTS, nCTS) = (X3, X4, X2, X1) = (PA2, PA3, PA1, PA0)`` + - ``UART(3)`` is on :``(TX, RX, nRTS, nCTS) = (Y9, Y10, Y7, Y6) = (PB10, PB11, PB14, PB13)`` + + On the Pyboard Lite only ``UART(2)`` supports flow control on these pins: + + ``(TX, RX, nRTS, nCTS) = (X1, X2, X4, X3) = (PA2, PA3, PA1, PA0)`` + + In the following paragraphs the term "target" refers to the device connected to + the UART. + + When the UART's ``init()`` method is called with ``flow`` set to one or both of + ``UART.RTS`` and ``UART.CTS`` the relevant flow control pins are configured. + ``nRTS`` is an active low output, ``nCTS`` is an active low input with pullup + enabled. To achieve flow control the Pyboard's ``nCTS`` signal should be connected + to the target's ``nRTS`` and the Pyboard's ``nRTS`` to the target's ``nCTS``. + + CTS: target controls Pyboard transmitter + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + If CTS flow control is enabled the write behaviour is as follows: + + If the Pyboard's ``uart.write(buf)`` method is called, transmission will stall for + any periods when ``nCTS`` is ``False``. This will result in a timeout if the entire + buffer was not transmitted in the timeout period. The method returns the number of + bytes written, enabling the user to write the remainder of the data if required. In + the event of a timeout, a character will remain in the UART pending ``nCTS``. The + number of bytes composing this character will be included in the return value. + + If ``uart.writechar()`` is called when ``nCTS`` is ``False`` the method will time + out unless the target asserts ``nCTS`` in time. If it times out ``OSError 116`` + will be raised. The character will be transmitted as soon as the target asserts ``nCTS``. + + RTS: Pyboard controls target's transmitter + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + If RTS flow control is enabled, behaviour is as follows: + + If buffered input is used (``read_buf_len`` > 0), incoming characters are buffered. + If the buffer becomes full, the next character to arrive will cause ``nRTS`` to go + ``False``: the target should cease transmission. ``nRTS`` will go ``True`` when + characters are read from the buffer. + + Note that the ``any()`` method returns the number of bytes in the buffer. Assume a + buffer length of ``N`` bytes. If the buffer becomes full, and another character arrives, + ``nRTS`` will be set False, and ``any()`` will return the count ``N``. When + characters are read the additional character will be placed in the buffer and will + be included in the result of a subsequent ``any()`` call. + + If buffered input is not used (``read_buf_len`` == 0) the arrival of a character will + cause ``nRTS`` to go ``False`` until the character is read. diff --git a/docs/library/struct.rst b/docs/library/struct.rst deleted file mode 100644 index 71ee5c9b70..0000000000 --- a/docs/library/struct.rst +++ /dev/null @@ -1,25 +0,0 @@ -:mod:`struct` -- pack and unpack primitive data types -===================================================== - -.. module:: struct - :synopsis: pack and unpack primitive data types - -See `Python struct <https://docs.python.org/3/library/struct.html>`_ for more -information. - -Functions ---------- - -.. function:: calcsize(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``. - The return value is a bytes object encoding the values. - -.. function:: unpack(fmt, data) - - Unpack from the ``data`` according to the format string ``fmt``. - The return value is a tuple of the unpacked values. diff --git a/docs/library/sys.rst b/docs/library/sys.rst index b3e52c40c4..b5a9138c07 100644 --- a/docs/library/sys.rst +++ b/docs/library/sys.rst @@ -7,14 +7,15 @@ Functions --------- -.. function:: exit([retval]) +.. function:: exit(retval=0) - Raise a ``SystemExit`` exception. If an argument is given, it is the - value given to ``SystemExit``. + 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:: print_exception(exc, [file]) +.. function:: print_exception(exc, file=sys.stdout) - Print exception with a traceback to a file-like object ``file`` (or + Print exception with a traceback to a file-like object `file` (or ``sys.stdout`` by default). .. admonition:: Difference to CPython @@ -27,38 +28,89 @@ Constants .. data:: argv - a mutable list of arguments this program started with + A mutable list of arguments the current program was started with. .. 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) + + This object is the recommended way to distinguish MicroPython from other + Python implementations (note that it still may not exist in the very + minimal ports). + + .. admonition:: Difference to CPython + :class: attention + + CPython mandates more attributes for this object, but the actual useful + bare minimum is implemented in MicroPython. + +.. data:: maxsize + + Maximum value which a native integer type can hold on the current platform, + or maximum value representable by MicroPython integer type, if it's smaller + than platform max value (that is the case for MicroPython ports without + long int support). + + This attribute is useful for detecting "bitness" of a platform (32-bit vs + 64-bit, etc.). It's recommended to not compare this attribute to some + value directly, but instead count number of bits in it:: + + bits = 0 + v = sys.maxsize + while v: + bits += 1 + v >>= 1 + if bits > 32: + # 64-bit (or more) platform + ... + else: + # 32-bit (or less) platform + # Note that on 32-bit platform, value of bits may be less than 32 + # (e.g. 31) due to peculiarities described above, so use "> 16", + # "> 32", "> 64" style of comparisons. + +.. data:: modules + + Dictionary of loaded modules. On some ports, it may not include builtin + modules. .. data:: path - a mutable list of directories to search for imported modules + A mutable list of directories to search for imported modules. .. data:: platform - The platform that MicroPython is running on. This is "pyboard" on the - pyboard and provides a robust way of determining if a script is running - on the pyboard or not. + 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 + 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. .. data:: stderr - standard error (connected to USB VCP, and optional UART object) + Standard error stream. .. data:: stdin - standard input (connected to USB VCP, and optional UART object) + Standard input stream. .. data:: stdout - standard output (connected to USB VCP, and optional UART object) + Standard output stream. .. data:: version - Python language version that this implementation conforms to, as a string + Python language version that this implementation conforms to, as a string. .. data:: version_info - Python language version that this implementation conforms to, as a tuple of ints + Python language version that this implementation conforms to, as a tuple of ints. diff --git a/docs/library/time.rst b/docs/library/time.rst deleted file mode 100644 index 9a35f4f66a..0000000000 --- a/docs/library/time.rst +++ /dev/null @@ -1,89 +0,0 @@ -:mod:`time` -- time related functions -===================================== - -.. module:: time - :synopsis: time related functions - -The ``time`` module provides functions for getting the current time and date, -and for sleeping. - -Functions ---------- - -.. function:: localtime([secs]) - - Convert a time expressed in seconds since Jan 1, 2000 into an 8-tuple which - contains: (year, month, mday, hour, minute, second, weekday, yearday) - If secs is not provided or None, then the current time from the RTC is used. - year includes the century (for example 2014). - - * month is 1-12 - * mday is 1-31 - * hour is 0-23 - * minute is 0-59 - * second is 0-59 - * weekday is 0-6 for Mon-Sun - * yearday is 1-366 - -.. function:: mktime() - - This is inverse function of localtime. It's argument is a full 8-tuple - which expresses a time as per localtime. It returns an integer which is - the number of seconds since Jan 1, 2000. - -.. only:: port_pyboard - - .. function:: sleep(seconds) - - Sleep for the given number of seconds. Seconds can be a floating-point number to - sleep for a fractional number of seconds. - -.. only:: port_esp8266 or port_wipy - - .. function:: sleep(seconds) - - Sleep for the given number of seconds. - -.. only:: port_wipy or port_pyboard - - .. function:: sleep_ms(ms) - - Delay for given number of milliseconds, should be positive or 0. - - .. function:: sleep_us(us) - - Delay for given number of microseconds, should be positive or 0 - - .. function:: ticks_ms() - - Returns an increasing millisecond counter with arbitrary reference point, - that wraps after some (unspecified) value. The value should be treated as - opaque, suitable for use only with ticks_diff(). - - .. function:: ticks_us() - - Just like ``ticks_ms`` above, but in microseconds. - - .. function:: ticks_cpu() - - Similar to ``ticks_ms`` and ``ticks_us``, but with higher resolution (usually CPU clocks). - - .. function:: ticks_diff(old, new) - - Measure period between consecutive calls to ticks_ms(), ticks_us(), or ticks_cpu(). - The value returned by these functions may wrap around at any time, so directly - subtracting them is not supported. ticks_diff() should be used instead. "old" value should - actually precede "new" value in time, or result is undefined. This function should not be - used to measure arbitrarily long periods of time (because ticks_*() functions wrap around - and usually would have short period). The expected usage pattern is implementing event - polling with timeout:: - - # Wait for GPIO pin to be asserted, but at most 500us - start = time.ticks_us() - while pin.value() == 0: - if time.ticks_diff(start, time.ticks_us()) > 500: - raise TimeoutError - -.. function:: time() - - Returns the number of seconds, as an integer, since 1/1/2000. diff --git a/docs/library/ubinascii.rst b/docs/library/ubinascii.rst index e7967c5113..0a9adb50d4 100644 --- a/docs/library/ubinascii.rst +++ b/docs/library/ubinascii.rst @@ -12,7 +12,7 @@ Functions .. function:: hexlify(data, [sep]) - Convert binary data to hexadecimal representation. Return bytes string. + Convert binary data to hexadecimal representation. Returns bytes string. .. admonition:: Difference to CPython :class: attention @@ -22,13 +22,13 @@ Functions .. function:: unhexlify(data) - Convert hexadecimal data to binary representation. Return bytes string. + Convert hexadecimal data to binary representation. Returns bytes string. (i.e. inverse of hexlify) .. function:: a2b_base64(data) - Convert Base64-encoded data to binary representation. Return bytes string. + Convert Base64-encoded data to binary representation. Returns bytes string. .. function:: b2a_base64(data) - Encode binary data in Base64 format. Return string. + Encode binary data in Base64 format. Returns string. diff --git a/docs/library/ucollections.rst b/docs/library/ucollections.rst new file mode 100644 index 0000000000..c7ed068c7e --- /dev/null +++ b/docs/library/ucollections.rst @@ -0,0 +1,53 @@ +:mod:`ucollections` -- collection and container types +===================================================== + +.. module:: ucollections + :synopsis: collection and container types + +This module implements advanced collection and container types to +hold/accumulate various objects. + +Classes +------- + +.. function:: namedtuple(name, fields) + + This is factory function to create a new namedtuple type with a specific + name and set of fields. A namedtyple is a subclass of tuple which allows + to access its fields not just by numeric index, but also with an attribute + access syntax using symbolic field names. Fields is a sequence of strings + specifying field names. For compatibily with CPython it can also be a + a string with space-separated field named (but this is less efficient). + Example of use:: + + from ucollections import namedtuple + + MyTuple = namedtuple("MyTuple", ("id", "name")) + t1 = MyTuple(1, "foo") + t2 = MyTuple(2, "bar") + print(t1.name) + assert t2.name == t2[1] + +.. function:: OrderedDict(...) + + ``dict`` type subclass which remembers and preserves the order of keys + added. When ordered dict is iterated over, keys/items are returned in + the order they were added:: + + from ucollections import OrderedDict + + # To make benefit of ordered keys, OrderedDict should be initialized + # from sequence of (key, value) pairs. + d = OrderedDict([("z", 1), ("a", 2)]) + # More items can be added as usual + d["w"] = 5 + d["b"] = 3 + for k, v in d.items(): + print(k, v) + + Output:: + + z 1 + a 2 + w 5 + b 3 diff --git a/docs/library/uio.rst b/docs/library/uio.rst new file mode 100644 index 0000000000..1b3e2a0822 --- /dev/null +++ b/docs/library/uio.rst @@ -0,0 +1,46 @@ +:mod:`uio` -- input/output streams +================================== + +.. module:: uio + :synopsis: input/output streams + +This module contains additional types of stream (file-like) objects +and helper functions. + +Functions +--------- + +.. function:: open(name, mode='r', **kwargs) + + Open a file. Builtin ``open()`` function is alised to this function. + All ports (which provide access to file system) are required to support + `mode` parameter, but support for other arguments vary by port. + +Classes +------- + +.. class:: FileIO(...) + + This is type of a file open in binary mode, e.g. using ``open(name, "rb")``. + You should not instantiate this class directly. + +.. class:: TextIOWrapper(...) + + This is type of a file open in text mode, e.g. using ``open(name, "rt")``. + You should not instantiate this class directly. + +.. class:: StringIO([string]) +.. class:: BytesIO([string]) + + In-memory file-like objects for input/output. `StringIO` is used for + text-mode I/O (similar to a normal file opened with "t" modifier). + `BytesIO` is used for binary-mode I/O (similar to a normal file + opened with "b" modifier). Initial contents of file-like objects + can be specified with `string` parameter (should be normal string + for `StringIO` or bytes object for `BytesIO`). All the usual file + methods like ``read()``, ``write()``, ``close()`` are available on + these objects, and additionally, following method: + + .. method:: getvalue() + + Get the current contents of the underlying buffer which holds data. diff --git a/docs/library/os.rst b/docs/library/uos.rst index e6777147ac..bb95107c04 100644 --- a/docs/library/os.rst +++ b/docs/library/uos.rst @@ -1,7 +1,7 @@ -:mod:`os` -- basic "operating system" services -============================================== +:mod:`uos` -- basic "operating system" services +=============================================== -.. module:: os +.. module:: uos :synopsis: basic "operating system" services The ``os`` module contains functions for filesystem access and ``urandom`` diff --git a/docs/library/usocket.rst b/docs/library/usocket.rst index a83a87d2e0..d31e4d2fc9 100644 --- a/docs/library/usocket.rst +++ b/docs/library/usocket.rst @@ -7,6 +7,18 @@ This module provides access to the BSD socket interface. +See corresponding `CPython module <https://docs.python.org/3/library/socket.html>`_ for +comparison. + +Socket address format(s) +------------------------ + +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()``. + Functions --------- @@ -37,13 +49,15 @@ Functions The following example shows how to connect to a given url:: s = socket.socket() - s.connect(socket.getaddrinfo('www.micropython.org', 80)[0][4]) + s.connect(socket.getaddrinfo('www.micropython.org', 80)[0][-1]) + +.. only:: port_wipy -Exceptions ----------- + Exceptions + ---------- -.. data:: socket.error -.. data:: socket.timeout + .. data:: socket.error + .. data:: socket.timeout Constants --------- @@ -59,9 +73,10 @@ Constants .. data:: socket.IPPROTO_UDP .. data:: socket.IPPROTO_TCP -.. data:: socket.IPPROTO_SEC +.. only:: port_wipy + .. data:: socket.IPPROTO_SEC - protocol numbers + protocol numbers class socket ============ @@ -79,8 +94,7 @@ Methods .. method:: socket.bind(address) - Bind the socket to address. The socket must not already be bound. The format of ``address`` - is: ``(ipv4 address, port)`` + Bind the socket to address. The socket must not already be bound. .. method:: socket.listen([backlog]) @@ -98,7 +112,7 @@ Methods .. method:: socket.connect(address) - Connect to a remote socket at address. The format of address is: ``(ipv4 address, port)`` + Connect to a remote socket at address. .. method:: socket.send(bytes) @@ -116,8 +130,7 @@ 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. The ``address`` has the same format as the - rest of the methods, see above. + destination socket is specified by `address`. .. method:: socket.recvfrom(bufsize) @@ -158,9 +171,10 @@ Methods The socket must be in blocking mode; it can have a timeout, but the file object’s internal buffer may end up in a inconsistent state if a timeout occurs. - .. note:: + .. admonition:: Difference to CPython + :class: attention - **CPython difference:** closing the file object returned by makefile() WILL close the + Closing the file object returned by makefile() WILL close the original socket as well. .. method:: socket.read(size) diff --git a/docs/library/ussl.rst b/docs/library/ussl.rst index 60be894107..b66e23b2c8 100644 --- a/docs/library/ussl.rst +++ b/docs/library/ussl.rst @@ -21,7 +21,7 @@ Functions import ssl s = socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_SEC) ss = ssl.wrap_socket(s) - ss.connect(socket.getaddrinfo('www.google.com', 443)[0][4]) + ss.connect(socket.getaddrinfo('www.google.com', 443)[0][-1]) Certificates must be used in order to validate the other side of the connection, and also to authenticate ourselves with the other end. Such certificates must be stored as files using the @@ -44,7 +44,7 @@ Functions import ssl s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_SEC) ss = ssl.wrap_socket(s, cert_reqs=ssl.CERT_REQUIRED, ca_certs='/flash/cert/ca.pem') - ss.connect(socket.getaddrinfo('cloud.blynk.cc', 8441)[0][4]) + ss.connect(socket.getaddrinfo('cloud.blynk.cc', 8441)[0][-1]) SSL sockets inherit all methods and from the standard sockets, see the :mod:`usocket` module. diff --git a/docs/library/ustruct.rst b/docs/library/ustruct.rst new file mode 100644 index 0000000000..ae5b1be003 --- /dev/null +++ b/docs/library/ustruct.rst @@ -0,0 +1,37 @@ +:mod:`ustruct` -- pack and unpack primitive data types +====================================================== + +.. module:: ustruct + :synopsis: pack and unpack primitive data types + +See `Python struct <https://docs.python.org/3/library/struct.html>`_ for more +information. + +Functions +--------- + +.. function:: calcsize(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`. + 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`. + +.. function:: unpack(fmt, data) + + 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 + value is a tuple of the unpacked values. diff --git a/docs/library/utime.rst b/docs/library/utime.rst new file mode 100644 index 0000000000..0bca4692ac --- /dev/null +++ b/docs/library/utime.rst @@ -0,0 +1,139 @@ +:mod:`utime` -- time related functions +====================================== + +.. module:: utime + :synopsis: time related functions + +The ``utime`` module provides functions for getting the current time and date, +measuring time intervals, and for delays. + +**Time Epoch**: Unix port uses standard for POSIX systems epoch of +1970-01-01 00:00:00 UTC. However, embedded ports use epoch of +2000-01-01 00:00:00 UTC. + +**Maintaining actual calendar date/time**: This requires a +Real Time Clock (RTC). On systems with underlying OS (including some +RTOS), an RTC may be implicit. Setting and maintaining actual calendar +time is responsibility of OS/RTOS and is done outside of MicroPython, +it just uses OS API to query date/time. On baremetal ports however +system time depends on ``machine.RTC()`` object. The current calendar time +may be set using ``machine.RTC().datetime(tuple)`` function, and maintained +by following means: + +* By a backup battery (which may be an additional, optional component for + a particular board). +* Using networked time protocol (requires setup by a port/user). +* Set manually by a user on each power-up (many boards then maintain + RTC time across hard resets, though some may require setting it again + in such case). + +If actual calendar time is not maintained with a system/MicroPython RTC, +functions below which require reference to current absolute time may +behave not as expected. + +Functions +--------- + +.. function:: localtime([secs]) + + Convert a time expressed in seconds since the Epoch (see above) into an 8-tuple which + contains: (year, month, mday, hour, minute, second, weekday, yearday) + If secs is not provided or None, then the current time from the RTC is used. + + * year includes the century (for example 2014). + * month is 1-12 + * mday is 1-31 + * hour is 0-23 + * minute is 0-59 + * second is 0-59 + * weekday is 0-6 for Mon-Sun + * yearday is 1-366 + +.. function:: mktime() + + This is inverse function of localtime. It's argument is a full 8-tuple + which expresses a time as per localtime. It returns an integer which is + the number of seconds since Jan 1, 2000. + +.. only:: port_unix or port_pyboard or port_esp8266 + + .. function:: sleep(seconds) + + Sleep for the given number of seconds. Seconds can be a floating-point number to + sleep for a fractional number of seconds. Note that other MicroPython ports may + not accept floating-point argument, for compatibility with them use ``sleep_ms()`` + and ``sleep_us()`` functions. + +.. only:: port_wipy + + .. function:: sleep(seconds) + + Sleep for the given number of seconds. + +.. only:: port_unix or port_pyboard or port_wipy or port_esp8266 + + .. function:: sleep_ms(ms) + + Delay for given number of milliseconds, should be positive or 0. + + .. function:: sleep_us(us) + + Delay for given number of microseconds, should be positive or 0 + + .. function:: ticks_ms() + + Returns an increasing millisecond counter with arbitrary reference point, + that wraps after some (unspecified) value. The value should be treated as + opaque, suitable for use only with ticks_diff(). + + .. function:: ticks_us() + + Just like ``ticks_ms`` above, but in microseconds. + +.. only:: port_wipy or port_pyboard + + .. function:: ticks_cpu() + + Similar to ``ticks_ms`` and ``ticks_us``, but with higher resolution (usually CPU clocks). + +.. only:: port_unix or port_pyboard or port_wipy or port_esp8266 + + .. function:: ticks_diff(old, new) + + Measure period between consecutive calls to ticks_ms(), ticks_us(), or ticks_cpu(). + The value returned by these functions may wrap around at any time, so directly + subtracting them is not supported. ticks_diff() should be used instead. "old" value should + actually precede "new" value in time, or result is undefined. This function should not be + used to measure arbitrarily long periods of time (because ticks_*() functions wrap around + and usually would have short period). The expected usage pattern is implementing event + polling with timeout:: + + # Wait for GPIO pin to be asserted, but at most 500us + start = time.ticks_us() + while pin.value() == 0: + if time.ticks_diff(start, time.ticks_us()) > 500: + raise TimeoutError + +.. function:: time() + + Returns the number of seconds, as an integer, since the Epoch, assuming that underlying + RTC is set and maintained as decsribed above. If an RTC is not set, this function returns + number of seconds since a port-specific reference point in time (for 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. + + .. admonition:: Difference to CPython + :class: attention + + In CPython, this function returns number of + seconds since Unix epoch, 1970-01-01 00:00 UTC, as a floating-point, + usually having microsecond precision. With MicroPython, only Unix port + uses the same Epoch, and if floating-point precision allows, + returns sub-second precision. Embedded hardware usually doesn't have + floating-point precision to represent both long time ranges and subsecond + precision, so they use integer value with second precision. Some embedded + hardware also lacks battery-powered RTC, so returns number of seconds + since last power-up or from other relative, hardware-specific point + (e.g. reset). |