Chapter 9 - Rotary Encoder

These rotary encoders are available for about 1 pound for either the panel mount version or the breakout version (buzz out the misleading labels).
They look similar to a 'volume control', but they function in a completely different way, able to continuously rotate without end stops, and giving 2 out-of-phase streams of pulses which can be interpreted for rotational direction, speed, and position.

If the 'common' (centre pin) is taken to ground, and the 2 encoder outputs taken to pulled-up gpio inputs, they will generate pulses when the shaft is rotated (think engine camshaft).

The internal 'camshaft lobes' are arranged so that when one changes state the other will be On when rotated in one direction but will be Off when rotated in the other direction.

So it is possible to monitor one pin for change of state, then branch on interrupt to compare its level with the other pin, which would indicate the direction of rotation.

Each pulse, in any direction, causes an interrupt - so knowing the direction allows controlling something one step in the appropriate direction.
Mine are 20-step devices, so a full rotation generates 20 pulse steps, therefore dividing the pulses in any direction by 20 will give revolutions.
Some commonly have 12 steps. Rotational speed can be worked out from how many pulses are received during the  period ofrotation.

Typically, another pair of pins on the rotary encoder offer a momentary push button switch which is operated by pressing down on the shaft.
So if the two functions are combined it offers a way to move up or down through a list then press to select a chosen item - ie: navigate a menu.

If the 2 outputs are 'polled' for position change in a loop, some pulses could be missed, but as rotary position is relative it probably won't matter.
If using 'interrupts' to catch every pulse, the interrupt code must be fast enough to complete execution before being interrupted by the next pulse.
So better to carry out time-consuming operations, such as writing to the browser, outside of the interrupt routine, perhaps by using a timer routine.