diff options
Diffstat (limited to 'docs/library')
-rw-r--r-- | docs/library/builtins.rst | 9 | ||||
-rw-r--r-- | docs/library/index.rst | 8 | ||||
-rw-r--r-- | docs/library/machine.Pin.rst | 305 | ||||
-rw-r--r-- | docs/library/machine.SPI.rst | 81 | ||||
-rw-r--r-- | docs/library/network.rst | 35 | ||||
-rw-r--r-- | docs/library/utime.rst | 141 |
6 files changed, 391 insertions, 188 deletions
diff --git a/docs/library/builtins.rst b/docs/library/builtins.rst index 42768ab999..d53c4d377b 100644 --- a/docs/library/builtins.rst +++ b/docs/library/builtins.rst @@ -28,6 +28,11 @@ All builtin functions are described here. They are also available via .. class:: complex() +.. function:: delattr(obj, name) + + The argument *name* should be a string, and this function deletes the named + attribute from the object given by *obj*. + .. class:: dict() .. function:: dir() @@ -110,6 +115,10 @@ All builtin functions are described here. They are also available via .. function:: setattr() +.. class:: slice() + + The *slice* builtin is the type that slice objects have. + .. function:: sorted() .. function:: staticmethod() diff --git a/docs/library/index.rst b/docs/library/index.rst index d502ffdfc6..b06c806f73 100644 --- a/docs/library/index.rst +++ b/docs/library/index.rst @@ -51,8 +51,8 @@ library. .. toctree:: :maxdepth: 1 - array.rst builtins.rst + array.rst cmath.rst gc.rst math.rst @@ -76,8 +76,8 @@ library. .. toctree:: :maxdepth: 1 - array.rst builtins.rst + array.rst cmath.rst gc.rst math.rst @@ -101,8 +101,8 @@ library. .. toctree:: :maxdepth: 1 - array.rst builtins.rst + array.rst gc.rst select.rst sys.rst @@ -119,8 +119,8 @@ library. .. toctree:: :maxdepth: 1 - array.rst builtins.rst + array.rst gc.rst math.rst sys.rst diff --git a/docs/library/machine.Pin.rst b/docs/library/machine.Pin.rst index db25787f94..952131f099 100644 --- a/docs/library/machine.Pin.rst +++ b/docs/library/machine.Pin.rst @@ -3,16 +3,44 @@ class Pin -- control I/O pins ============================= -A pin is the basic object to control I/O pins (also known as GPIO - -general-purpose input/output). It has methods to set -the mode of the pin (input, output, etc) and methods to get and set the -digital logic level. For analog control of a pin, see the ADC class. +A pin object is used to control I/O pins (also known as GPIO - general-purpose +input/output). Pin objects are commonly associated with a physical pin that can +drive an output voltage and read input voltages. The pin class has methods to set the mode of +the pin (IN, OUT, etc) and methods to get and set the digital logic level. +For analog control of a pin, see the :class:`ADC` class. -Usage Model: +A pin object is constructed by using an identifier which unambiguously +specifies a certain I/O pin. The allowed forms of the identifier and the +physical pin that the identifier maps to are port-specific. Possibilities +for the identifier are an integer, a string or a tuple with port and pin +number. + +Usage Model:: + + from machine import Pin + + # create an output pin on pin #0 + p0 = Pin(0, Pin.OUT) + + # set the value low then high + p0.value(0) + p0.value(1) + + # create an input pin on pin #2, with a pull up resistor + p2 = Pin(2, Pin.IN, Pin.PULL_UP) + + # read and print the pin value + print(p2.value()) + + # reconfigure pin #0 in input mode + p0.mode(p0.IN) + + # configure an irq callback + p0.irq(lambda p:print(p)) .. only:: port_wipy - Board pins are identified by their string id:: + On the WiPy board the pins are identified by their string id:: from machine import Pin g = machine.Pin('GP9', mode=Pin.OUT, pull=None, drive=Pin.MED_POWER, alt=-1) @@ -40,174 +68,224 @@ Usage Model: All pin objects go through the pin mapper to come up with one of the gpio pins. -.. only:: port_esp8266 + For the ``drive`` parameter the strengths are: - :: + - ``Pin.LOW_POWER`` - 2mA drive capability. + - ``Pin.MED_POWER`` - 4mA drive capability. + - ``Pin.HIGH_POWER`` - 6mA drive capability. - from machine import Pin + For the ``alt`` parameter please refer to the pinout and alternate functions + table at <https://raw.githubusercontent.com/wipy/wipy/master/docs/PinOUT.png>`_ + for the specific alternate functions that each pin supports. - # create an output pin on GPIO0 - p0 = Pin(0, Pin.OUT) - p0.value(0) - p0.value(1) + For interrupts, the ``priority`` can take values in the range 1-7. And the + ``wake`` parameter has the following properties: - # create an input pin on GPIO2 - p2 = Pin(2, Pin.IN, Pin.PULL_UP) - print(p2.value()) + - If ``wake_from=machine.Sleep.ACTIVE`` any pin can wake the board. + - If ``wake_from=machine.Sleep.SUSPENDED`` pins ``GP2``, ``GP4``, ``GP10``, + ``GP11``, GP17`` or ``GP24`` can wake the board. Note that only 1 + of this pins can be enabled as a wake source at the same time, so, only + the last enabled pin as a ``machine.Sleep.SUSPENDED`` wake source will have effect. + - If ``wake_from=machine.Sleep.SUSPENDED`` pins ``GP2``, ``GP4``, ``GP10``, + ``GP11``, ``GP17`` and ``GP24`` can wake the board. In this case all of the + 6 pins can be enabled as a ``machine.Sleep.HIBERNATE`` wake source at the same time. Constructors ------------ -.. class:: Pin(id, ...) +.. class:: Pin(id, mode=-1, pull=-1, \*, value, drive, alt) - Create a new Pin object associated with the id. If additional arguments are given, - they are used to initialise the pin. See :meth:`Pin.init`. + Access the pin peripheral (GPIO pin) associated with the given ``id``. If + additional arguments are given in the constructor then they are used to initialise + the pin. Any settings that are not specified will remain in their previous state. -Methods -------- + The arguments are: -.. only:: port_wipy + - ``id`` is mandatory and can be an arbitrary object. Among possible value + types are: int (an internal Pin identifier), str (a Pin name), and tuple + (pair of [port, pin]). - .. method:: Pin.init(mode, pull, \*, drive, alt) - - Initialise the pin: + - ``mode`` specifies the pin mode, which can be one of: - - ``mode`` can be one of: + - ``Pin.IN`` - Pin is configured for input. If viewed as an output the pin + is in high-impedance state. - - ``Pin.IN`` - input pin. - - ``Pin.OUT`` - output pin in push-pull mode. - - ``Pin.OPEN_DRAIN`` - output pin in open-drain mode. - - ``Pin.ALT`` - pin mapped to an alternate function. - - ``Pin.ALT_OPEN_DRAIN`` - pin mapped to an alternate function in open-drain mode. + - ``Pin.OUT`` - Pin is configured for (normal) output. - - ``pull`` can be one of: + - ``Pin.OPEN_DRAIN`` - Pin is configured for open-drain output. Open-drain + output works in the following way: if the output value is set to 0 the pin + is active at a low level; if the output value is 1 the pin is in a high-impedance + state. Not all ports implement this mode, or some might only on certain pins. - - ``None`` - no pull up or down resistor. - - ``Pin.PULL_UP`` - pull up resistor enabled. - - ``Pin.PULL_DOWN`` - pull down resistor enabled. + - ``Pin.ALT`` - Pin is configured to perform an alternative function, which is + port specific. For a pin configured in such a way any other Pin methods + (except :meth:`Pin.init`) are not applicable (calling them will lead to undefined, + or a hardware-specific, result). Not all ports implement this mode. - - ``drive`` can be one of: + - ``Pin.ALT_OPEN_DRAIN`` - The Same as ``Pin.ALT``, but the pin is configured as + open-drain. Not all ports implement this mode. - - ``Pin.LOW_POWER`` - 2mA drive capability. - - ``Pin.MED_POWER`` - 4mA drive capability. - - ``Pin.HIGH_POWER`` - 6mA drive capability. + - ``pull`` specifies if the pin has a (weak) pull resistor attached, and can be + one of: - - ``alt`` is the number of the alternate function. Please refer to the - `pinout and alternate functions table. <https://raw.githubusercontent.com/wipy/wipy/master/docs/PinOUT.png>`_ - for the specific alternate functions that each pin supports. + - ``None`` - No pull up or down resistor. + - ``Pin.PULL_UP`` - Pull up resistor enabled. + - ``Pin.PULL_DOWN`` - Pull down resistor enabled. - Returns: ``None``. + - ``value`` is valid only for Pin.OUT and Pin.OPEN_DRAIN modes and specifies initial + output pin value if given, otherwise the state of the pin peripheral remains + unchanged. - .. method:: Pin.id() + - ``drive`` specifies the output power of the pin and can be one of: ``Pin.LOW_POWER``, + ``Pin.MED_POWER`` or ``Pin.HIGH_POWER``. The actual current driving capabilities + are port dependent. Not all ports implement this argument. - Get the pin id. + - ``alt`` specifies an alternate function for the pin and the values it can take are + port dependent. This argument is valid only for ``Pin.ALT`` and ``Pin.ALT_OPEN_DRAIN`` + modes. It may be used when a pin supports more than one alternate function. If only + one pin alternate function is supported the this argument is not required. Not all + ports implement this argument. -.. only:: port_esp8266 + As specified above, the Pin class allows to set an alternate function for a particular + pin, but it does not specify any further operations on such a pin. Pins configured in + alternate-function mode are usually not used as GPIO but are instead driven by other + hardware peripherals. The only operation supported on such a pin is re-initialising, + by calling the constructor or :meth:`Pin.init` method. If a pin that is configured in + alternate-function mode is re-initialised with ``Pin.IN``, ``Pin.OUT``, or + ``Pin.OPEN_DRAIN``, the alternate function will be removed from the pin. - .. method:: Pin.init(mode, pull=None, \*, value) +Methods +------- - Initialise the pin: +.. method:: Pin.init(mode=-1, pull=-1, \*, value, drive, alt) - - `mode` can be one of: + Re-initialise the pin using the given parameters. Only those arguments that + are specified will be set. The rest of the pin peripheral state will remain + unchanged. See the constructor documentation for details of the arguments. - - ``Pin.IN`` - input pin. - - ``Pin.OUT`` - output pin in push-pull mode. + Returns ``None``. - - `pull` can be one of: +.. method:: Pin.value([x]) - - ``None`` - no pull up or down resistor. - - ``Pin.PULL_UP`` - pull up resistor enabled. + This method allows to set and get the value of the pin, depending on whether + the argument ``x`` is supplied or not. - - if `value` is given then it is the output value to set the pin - if it is in output mode. + If the argument is omitted then this method gets the digital logic level of + the pin, returning 0 or 1 corresponding to low and high voltage signals + respectively. The behaviour of this method depends on the mode of the pin: -.. method:: Pin.value([value]) + - ``Pin.IN`` - The method returns the actual input value currently present + on the pin. + - ``Pin.OUT`` - The behaviour and return value of the method is undefined. + - ``Pin.OPEN_DRAIN`` - If the pin is in state '0' then the behaviour and + return value of the method is undefined. Otherwise, if the pin is in + state '1', the method returns the actual input value currently present + on the pin. - Get or set the digital logic level of the pin: + If the argument is supplied then this method sets the digital logic level of + the pin. The argument ``x`` can be anything that converts to a boolean. + If it converts to ``True``, the pin is set to state '1', otherwise it is set + to state '0'. The behaviour of this method depends on the mode of the pin: - - With no argument, return 0 or 1 depending on the logic level of the pin. - - With ``value`` given, set the logic level of the pin. ``value`` can be - anything that converts to a boolean. If it converts to ``True``, the pin - is set high, otherwise it is set low. + - ``Pin.IN`` - The value is stored in the output buffer for the pin. The + pin state does not change, it remains in the high-impedance state. The + stored value will become active on the pin as soon as it is changed to + ``Pin.OUT`` or ``Pin.OPEN_DRAIN`` mode. + - ``Pin.OUT`` - The output buffer is set to the given value immediately. + - ``Pin.OPEN_DRAIN`` - If the value is '0' the pin is set to a low voltage + state. Otherwise the pin is set to high-impedance state. -.. method:: Pin.__call__([value]) + When setting the value this method returns ``None``. - Pin objects are callable. The call method provides a (fast) shortcut to set and get the value of the pin. - See :func:`Pin.value` for more details. +.. method:: Pin.out_value() -.. method:: Pin.alt_list() + Return the value stored in the output buffer of a pin, regardless of its mode. - 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)`` + Not all ports implement this method. - Availability: WiPy. +.. method:: Pin.__call__([x]) -.. only:: port_wipy + Pin objects are callable. The call method provides a (fast) shortcut to set + and get the value of the pin. It is equivalent to Pin.value([x]). + See :meth:`Pin.value` for more details. + +.. method:: Pin.toggle() + + Toggle the output value of the pin. Equivalent to ``pin.value(not pin.out_value())``. + Returns ``None``. + + Not all ports implement this method. - .. method:: Pin.toggle() + Availability: WiPy. - Toggle the value of the pin. +.. method:: Pin.id() - .. method:: Pin.mode([mode]) + Get the pin identifier. This may return the ``id`` as specified in the + constructor. Or it may return a canonical software-specific pin id. - Get or set the pin mode. +.. method:: Pin.mode([mode]) - .. method:: Pin.pull([pull]) + Get or set the pin mode. + See the constructor documentation for details of the ``mode`` argument. - Get or set the pin pull. +.. method:: Pin.pull([pull]) - .. method:: Pin.drive([drive]) + Get or set the pin pull state. + See the constructor documentation for details of the ``pull`` argument. - Get or set the pin drive strength. +.. method:: Pin.drive([drive]) - .. method:: Pin.irq(\*, trigger, priority=1, handler=None, wake=None) + Get or set the pin drive strength. + See the constructor documentation for details of the ``drive`` argument. - Create a callback to be triggered when the input level at the pin changes. + Not all ports implement this method. - - ``trigger`` configures the pin level which can generate an interrupt. Possible values are: + Availability: WiPy. - - ``Pin.IRQ_FALLING`` interrupt on falling edge. - - ``Pin.IRQ_RISING`` interrupt on rising edge. - - ``Pin.IRQ_LOW_LEVEL`` interrupt on low level. - - ``Pin.IRQ_HIGH_LEVEL`` interrupt on high level. - - The values can be *ORed* together, for instance mode=Pin.IRQ_FALLING | Pin.IRQ_RISING +.. method:: Pin.irq(handler=None, trigger=(Pin.IRQ_FALLING | Pin.IRQ_RISING), \*, priority=1, wake=None) - - ``priority`` level of the interrupt. Can take values in the range 1-7. - Higher values represent higher priorities. - - ``handler`` is an optional function to be called when new characters arrive. - - ``wakes`` selects the power mode in which this interrupt can wake up the - board. Please note: + Configure an interrupt handler to be called when the trigger source of the + pin is active. If the pin mode is ``Pin.IN`` then the trigger source is + the external value on the pin. If the pin mode is ``Pin.OUT`` then the + trigger source is the output buffer of the pin. Otherwise, if the pin mode + is ``Pin.OPEN_DRAIN`` then the trigger source is the output buffer for + state '0' and the external pin value for state '1'. - - If ``wake_from=machine.Sleep.ACTIVE`` any pin can wake the board. - - If ``wake_from=machine.Sleep.SUSPENDED`` pins ``GP2``, ``GP4``, ``GP10``, - ``GP11``, GP17`` or ``GP24`` can wake the board. Note that only 1 - of this pins can be enabled as a wake source at the same time, so, only - the last enabled pin as a ``machine.Sleep.SUSPENDED`` wake source will have effect. - - If ``wake_from=machine.Sleep.SUSPENDED`` pins ``GP2``, ``GP4``, ``GP10``, - ``GP11``, ``GP17`` and ``GP24`` can wake the board. In this case all of the - 6 pins can be enabled as a ``machine.Sleep.HIBERNATE`` wake source at the same time. - - Values can be ORed to make a pin generate interrupts in more than one power - mode. + The arguments are: - Returns a callback object. + - ``handler`` is an optional function to be called when the interrupt + triggers. -.. only:: port_esp8266 + - ``trigger`` configures the event which can generate an interrupt. + Possible values are: - .. method:: Pin.irq(\*, trigger, handler=None) + - ``Pin.IRQ_FALLING`` interrupt on falling edge. + - ``Pin.IRQ_RISING`` interrupt on rising edge. + - ``Pin.IRQ_LOW_LEVEL`` interrupt on low level. + - ``Pin.IRQ_HIGH_LEVEL`` interrupt on high level. - Create a callback to be triggered when the input level at the pin changes. + These values can be OR'ed together to trigger on multiple events. - - ``trigger`` configures the pin level which can generate an interrupt. Possible values are: + - ``priority`` sets the priority level of the interrupt. The values it + can take are port-specific, but higher values always represent higher + priorities. + + - ``wake`` selects the power mode in which this interrupt can wake up the + system. It can be ``machine.IDLE``, ``machine.SLEEP`` or ``machine.DEEPSLEEP``. + These values can also be OR'ed together to make a pin generate interrupts in + more than one power mode. + + This method returns a callback object. + +.. only:: port_wipy - - ``Pin.IRQ_FALLING`` interrupt on falling edge. - - ``Pin.IRQ_RISING`` interrupt on rising edge. + .. method:: Pin.alt_list() - The values can be OR'ed together to trigger on multiple events. + 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)`` - - ``handler`` is an optional function to be called when the interrupt triggers. + Availability: WiPy. - Returns a callback object. Attributes ---------- @@ -239,7 +317,8 @@ not all constants are available on all ports. .. data:: Pin.PULL_UP Pin.PULL_DOWN - Selects the whether there is a pull up/down resistor. + Selects whether there is a pull up/down resistor. Use the value + ``None`` for no pull. .. data:: Pin.LOW_POWER Pin.MED_POWER diff --git a/docs/library/machine.SPI.rst b/docs/library/machine.SPI.rst index 73b3a3996d..dda6314fa2 100644 --- a/docs/library/machine.SPI.rst +++ b/docs/library/machine.SPI.rst @@ -1,10 +1,14 @@ .. currentmodule:: machine -class SPI -- a master-driven serial protocol -============================================ +class SPI -- a Serial Peripheral Interface bus protocol (master side) +===================================================================== -SPI is a serial protocol that is driven by a master. At the physical level -there are 3 lines: SCK, MOSI, MISO. +SPI is a synchronous serial protocol that is driven by a master. At the +physical level, a bus consists of 3 lines: SCK, MOSI, MISO. Multiple devices +can share the same bus. Each device should have a separate, 4th signal, +SS (Slave Select), to select a particualr device on a bus with which +communication takes place. Management of an SS signal should happen in +user code (via machine.Pin class). .. only:: port_wipy @@ -21,65 +25,84 @@ there are 3 lines: SCK, MOSI, MISO. Constructors ------------ -.. only:: port_wipy +.. class:: SPI(id, ...) - .. class:: SPI(id, ...) + Construct an SPI object on the given bus, ``id``. Values of ``id`` depend + on a particular port and its hardware. Values 0, 1, etc. are commonly used + to select hardware SPI block #0, #1, etc. Value -1 can be used for + bitbanging (software) implementation of SPI (if supported by a port). - Construct an SPI object on the given bus. ``id`` can be only 0. - With no additional parameters, the SPI object is created but not - initialised (it has the settings from the last initialisation of - the bus, if any). If extra arguments are given, the bus is initialised. - See ``init`` for parameters of initialisation. + With no additional parameters, the SPI object is created but not + initialised (it has the settings from the last initialisation of + the bus, if any). If extra arguments are given, the bus is initialised. + See ``init`` for parameters of initialisation. Methods ------- -.. method:: SPI.init(mode, baudrate=1000000, \*, polarity=0, phase=0, bits=8, firstbit=SPI.MSB, pins=(CLK, MOSI, MISO)) +.. method:: SPI.init(baudrate=1000000, \*, polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=None, mosi=None, miso=None, pins=(SCK, MOSI, MISO)) Initialise the SPI bus with the given parameters: - - ``mode`` must be ``SPI.MASTER``. - ``baudrate`` is the SCK clock rate. - ``polarity`` can be 0 or 1, and is the level the idle clock line sits at. - ``phase`` can be 0 or 1 to sample data on the first or second clock edge respectively. - - ``bits`` is the width of each transfer, accepted values are 8, 16 and 32. - - ``firstbit`` can be ``SPI.MSB`` only. - - ``pins`` is an optional tuple with the pins to assign to the SPI bus. + - ``bits`` is the width in bits of each transfer. Only 8 is guaranteed to be supported by all hardware. + - ``firstbit`` can be ``SPI.MSB`` or ``SPI.LSB``. + - ``sck``, ``mosi``, ``miso`` are pins (machine.Pin) objects to use for bus signals. For most + hardware SPI blocks (as selected by ``id`` parameter to the constructore), pins are fixed + and cannot be changed. In some cases, hardware blocks allow 2-3 alternative pin sets for + a hardware SPI block. Arbitrary pin assignments are possible only for a bitbanging SPI driver + (``id`` = -1). + - ``pins`` - WiPy port doesn't ``sck``, ``mosi``, ``miso`` arguments, and instead allows to + specify them as a tuple of ``pins`` paramter. .. method:: SPI.deinit() Turn off the SPI bus. -.. method:: SPI.write(buf) +.. method:: SPI.read(nbytes, write=0x00) + + Read a number of bytes specified by ``nbytes`` while continuously writing + the single byte given by ``write``. + Returns a ``bytes`` object with the data that was read. + +.. method:: SPI.readinto(buf, write=0x00) - Write the data contained in ``buf``. - Returns the number of bytes written. + Read into the buffer specified by ``buf`` while continuously writing the + single byte given by ``write``. + Returns ``None``. -.. method:: SPI.read(nbytes, *, write=0x00) + Note: on WiPy this function returns the number of bytes read. - Read the ``nbytes`` while writing the data specified by ``write``. - Return the number of bytes read. +.. method:: SPI.write(buf) -.. method:: SPI.readinto(buf, *, write=0x00) + Write the bytes contained in ``buf``. + Returns ``None``. - Read into the buffer specified by ``buf`` while writing the data specified by - ``write``. - Return the number of bytes read. + Note: on WiPy this function returns the number of bytes written. .. method:: SPI.write_readinto(write_buf, read_buf) - Write from ``write_buf`` and read into ``read_buf``. Both buffers must have the + Write the bytes from ``write_buf`` while reading into ``read_buf``. The + buffers can be the same or different, but both buffers must have the same length. - Returns the number of bytes written + Returns ``None``. + + Note: on WiPy this function returns the number of bytes written. Constants --------- .. data:: SPI.MASTER - for initialising the SPI bus to master + for initialising the SPI bus to master; this is only used for the WiPy .. data:: SPI.MSB set the first bit to be the most significant bit + +.. data:: SPI.LSB + + set the first bit to be the least significant bit diff --git a/docs/library/network.rst b/docs/library/network.rst index 0e18106aa8..251e68c76e 100644 --- a/docs/library/network.rst +++ b/docs/library/network.rst @@ -5,11 +5,12 @@ .. module:: network :synopsis: network configuration -This module provides network drivers and routing configuration. Network -drivers for specific hardware are available within this module and are -used to configure a hardware network interface. Configured interfaces -are then available for use via the :mod:`socket` module. To use this module -the network build of firmware must be installed. +This module provides network drivers and routing configuration. To use this +module, a MicroPython variant/build with network capabilities must be installed. +Network drivers for specific hardware are available within this module and are +used to configure hardware network interface(s). Network services provided +by configured interfaces are then available for use via the :mod:`socket` +module. For example:: @@ -79,7 +80,7 @@ For example:: class CC3K ========== - This class provides a driver for CC3000 wifi modules. Example usage:: + This class provides a driver for CC3000 WiFi modules. Example usage:: import network nic = network.CC3K(pyb.SPI(2), pyb.Pin.board.Y5, pyb.Pin.board.Y4, pyb.Pin.board.Y3) @@ -128,16 +129,16 @@ For example:: .. method:: cc3k.connect(ssid, key=None, \*, security=WPA2, bssid=None) - Connect to a wifi access point using the given SSID, and other security + Connect to a WiFi access point using the given SSID, and other security parameters. .. method:: cc3k.disconnect() - Disconnect from the wifi access point. + Disconnect from the WiFi access point. .. method:: cc3k.isconnected() - Returns True if connected to a wifi access point and has a valid IP address, + Returns True if connected to a WiFi access point and has a valid IP address, False otherwise. .. method:: cc3k.ifconfig() @@ -323,7 +324,7 @@ For example:: .. method:: wlan.isconnected() - In case of STA mode, returns ``True`` if connected to a wifi access + In case of STA mode, returns ``True`` if connected to a WiFi access point and has a valid IP address. In AP mode returns ``True`` when a station is connected. Returns ``False`` otherwise. @@ -348,7 +349,7 @@ For example:: # Set WiFi access point name (formally known as ESSID) and WiFi channel ap.config(essid='My AP', channel=11) - # Queey params one by one + # Query params one by one print(ap.config('essid')) print(ap.config('channel')) @@ -433,7 +434,7 @@ For example:: .. method:: wlan.connect(ssid, \*, auth=None, bssid=None, timeout=None) - Connect to a wifi access point using the given SSID, and other security + 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``, @@ -451,16 +452,16 @@ For example:: .. method:: wlan.disconnect() - Disconnect from the wifi access point. + Disconnect from the WiFi access point. .. method:: wlan.isconnected() - In case of STA mode, returns ``True`` if connected to a wifi access point and has a valid IP address. + In case of STA mode, returns ``True`` if connected to a WiFi access point and has a valid IP address. In AP mode returns ``True`` when a station is connected, ``False`` otherwise. .. method:: wlan.ifconfig(if_id=0, config=['dhcp' or configtuple]) - With no parameters given eturns 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. @@ -498,10 +499,10 @@ For example:: 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. + - ``handler`` is the function that gets called when the IRQ is triggered. - ``wake`` must be ``machine.SLEEP``. - Returns an irq object. + Returns an IRQ object. Constants --------- diff --git a/docs/library/utime.rst b/docs/library/utime.rst index 8310673830..109c3560cc 100644 --- a/docs/library/utime.rst +++ b/docs/library/utime.rst @@ -82,37 +82,128 @@ Functions .. 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(). + 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 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 + 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. + + 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 + invalid results from the latter functions. .. 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 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 a CPU clock, some other timing source available in a + system (e.g. high-resolution timer) can be used instead. The exact timing unit + (resolution) of this function is not specified on ``utime`` module level, but + documentation for a specific port may provide more specific information. This + function is intended for very fine benchmarking or very tight real-time loops. + Avoid using it in portable code. + + Availability: Not every port implements this function. + + +.. 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`` + 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 ``tick_ms()``, ``ticks_us()``, ``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:: + + # Find out what ticks value there was 100ms ago + print(tick_add(time.ticks_ms(), -100)) + + # Calculate deadline for operation and test for it + deadline = tick_add(time.ticks_ms(), 200) + while ticks_diff(deadline, time.ticks_ms()) > 0: + do_a_little_of_something() + + # Find out TICKS_MAX used by this port + print(tick_add(0, -1)) + + +.. 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 operator, + ``tick_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. 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) 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 two's-complement signed binary integers). If the result is negative, + it means that `ticks1` occured earlier in time than `ticks2`. Otherwise, it means that + `ticks1` occured 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 2 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 to the negative range of possible values. + + Informal rationale of the constraints above: Suppose you are locked in a room with no + means to monitor passing of time except a standard 12-notch clock. Then if you look at + dial-plate now, and don't look again for another 13 hours (e.g., if you fall for a + long sleep), then once you finally look again, it may seem to you that only 1 hour + has passed. To avoid this mistake, just look at the clock regularly. Your application + should do the same. "Too long sleep" metaphor also maps directly to application + 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: + + 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() + while pin.value() == 0: + 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:: + + # This code snippet is not optimized + now = time.ticks_ms() + scheduled_time = task.scheduled_time() + if ticks_diff(now, scheduled_time) > 0: + print("Too early, let's nap") + sleep_ms(ticks_diff(now, scheduled_time)) + task.run() + elif ticks_diff(now, scheduled_time) == 0: + print("Right at time!") + task.run() + elif ticks_diff(now, scheduled_time) < 0: + print("Oops, running late, tell task to run faster!") + task.run(run_faster=true) + + Note: Do not pass ``time()`` values to ``ticks_diff()``, and 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 . - .. 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() |