.. currentmodule:: machine
.. _machine.Encoder:

class Encoder -- quadrature decoding
====================================

Encoder implements decoding of quadrature signals as commonly output from
rotary encoders, by counting either up or down depending on the order of two
input pulses.

Minimal ESP32 example usage::

    from machine import Pin, Encoder

    encoder = Encoder(0, Pin(0, Pin.IN), Pin(1, Pin.IN))   # create Encoder for pins 0, 1 and begin counting
    value = encoder.value()                                # retrieve current count

Availability: **ESP32, MIMXRT**

Constructors
------------

.. class:: Encoder(id, ...)

   Returns the singleton Encoder object for the the given *id*. Values of *id*
   depend on a particular port and its hardware. Values 0, 1, etc. are commonly
   used to select hardware block #0, #1, etc.

   Additional arguments are passed to the :meth:`init` method described below,
   and will cause the Encoder instance to be re-initialised and reset.

   On ESP32, the *id* corresponds to a :ref:`PCNT unit <esp32.PCNT>`.

Methods
-------

.. method:: Encoder.init(phase_a, phase_b, *, ...)

   Initialise and reset the Encoder with the given parameters:

   - *phase_a* specifies the first input pin as a
     :ref:`machine.Pin <machine.Pin>` object.

   - *phase_b* specifies the second input pin as a
     :ref:`machine.Pin <machine.Pin>` object.

   These pins may be omitted on ports that have predefined pins for a given
   hardware block.

   Additional keyword-only parameters that may be supported by a port are:

   - *filter_ns* specifies a minimum period of time in nanoseconds that the
     source signal needs to be stable for a pulse to be counted. Implementations
     should use the longest filter supported by the hardware that is less than
     or equal to this value. The default is 0 (no filter). *(Supported on ESP32 and MIMXRT)*

   - *phases* specifies the number of signal edges to count and thus the
     granularity of the decoding. e.g. 4 phases corresponds to "4x quadrature
     decoding", and will result in four counts per pulse. Ports may support
     either 1, 2, or 4 phases and the default is 1 phase. *(Supported on ESP32 and MIMXRT)*

   - *max* Specify the upper counting range. The position counter will count up
     from a *min* start value up to *max*, then roll over to the init value and
     increase the cycles counter by one. When counting down, the cycles counter
     decreases at the transition from *min* to *max*. The range is reset by defining
     both *max* and *min* to 0. The default value is the hardware's counter range.
     *(Supported by MIMXRT and the ESP32 PCNT module)*

   - *min*. Specify the lower counting range. The default value is 0.
     *(Supported by MIMXRT and the ESP32 PCNT module)*

   - *index* A Pin specifier telling to which pin the index pulse is connected.
     At a rising slope of the index pulse the encoder counter is set to the min value
     and the cycles counter is increased or decreased by one, depending on
     the input levels. A *value* of *None* disables the index input.
     *(Supported on MIMXRT)*

   - *reset* A Pin specifier telling to which pin the reset pulse is connected.
     At a rising slope of the reset pulse the position counter is set to the init
     value, but the cycles counter is not changed. A *value* of *None* disables the reset input.
     *(Supported on MIMXRT)*

   - *match* Set the counter value at which the interrupt IRQ_MATCH shall trigger.
     The value is not checked for being in the bounds of the counter range. This option
     if equivalent to the *threshold* options of the ESP32 PCNT module.
     A *value* of *None* resets the match value and disables the IRQ_MATCH interrupt.
     *(Supported on MIMXRT)*

   - *match_pin* A Pin specifier telling to which pin the match output is connected.
     This output will have a high level as long as the position counter matches the
     match value. The signal is generated by the encoder logic and requires no
     further software support. The pulse width is defined by the input signal frequency
     and can be very short, like 20ns, or stay, if the counter stops at the match position.
     A *value* of *None* disables the match output. *(Supported on MIMXRT)*

.. method:: Encoder.deinit()

   Stops the Encoder, disabling any interrupts and releasing hardware resources.
   A Soft Reset should deinitialize all Encoder objects.

.. method:: Encoder.value([value])

   Get, and optionally set, the encoder value as a signed integer.
   Implementations should aim to do the get and set atomically.

   See :meth:`machine.Counter.value` for details about overflow of this value.

.. method:: Encoder.cycles([value])

   Get or set the current cycles counter of the counter as signed 16 bit integer.
   The value represents the overflow or underflow events of the count range.
   With no arguments the actual cycles counter value is returned.
   With a single *value* argument the cycles counter is set to that value. The
   base counter is not changed. The method returns the previous value.
   *(Supported on MIMXRT)*

.. method:: Encoder.irq(handler=None, trigger=0, hard=False)

   Specifies, that the *handler* is called when the respective *event* happens.

   *event* may be:
    - Encoder.IRQ_RESET Triggered with a transition at the *reset* input.
    - Encoder.IRQ_INDEX Triggered with a transition at the *index* input.
    - Encoder.IRQ_MATCH Triggered when the position counter matches the *match* value. For fast signals,
      the actual position counter value when retrieved in the callback may be different from the trigger value.
    - Encoder.IRQ_ROLL_OVER Triggered when the position counter rolls over from the highest
      to the lowest value.
    - Encoder.IRQ_ROLL_UNDER Triggered when the position counter rolls under from the lowest
      to the highest value.

   The callback function *handler* receives a single argument, which is the Encoder object. All
   events share the same callback. The event which triggers the callback can be identified
   with the irq.flags() method. The argument *hard* specifies, whether the callback is called
   as a hard interrupt or as regular scheduled function. Hard interrupts have always a short latency,
   but are limited in that they must not allocate memory. Regular scheduled functions are not limited
   in what can be used, but depending on the load of the device execution may be delayed.
   Under low load, the difference in latency is minor.

   The default arguments values are trigger=0, handler=None, hard=False. The callback will be
   disabled, when called with handler=None.

   The position match event is triggered as long as the position and match value are identical.
   Therefore the position match callback is run in a one-shot fashion, and has to be enabled
   again when the position has changed. It will be enabled by re-defining the trigger with either
   :meth:`Encoder.irq()` or :meth:`irq().trigger()`. For ESP32, Encoder interrupts are handled
   by the :ref:`PCNT unit <esp32.PCNT>`.

   *(Supported on MIMXRT)*

Constants
---------

.. data:: Encoder.IRQ_RESET
          Encoder.IRQ_INDEX
          Encoder.IRQ_MATCH
          Encoder.IRQ_ROLL_OVER
          Encoder.IRQ_ROLL_UNDER

   Select the IRQ trigger event.  *(Supported on MIMXRT)*
