Quadrature decoding in software
Optical and magnetic rotation encoders usually generate quadrature signals called A and B. Read about quadrature, which allows clockwise and counterclockwise motion to be distinguished. There are special chips that can count up and down according to quadrature A and B inputs. There are even some PICs with quadrature inputs, but the 4520 isn't one of them.
QuadratureSoft.c uses software to decode and count A and B signals. It can handle any number of encoders, but it is limited in the number of counts per second it can handle. As written it runs at a 1KHz interrupt rate, and it is required that the A and B signals for one encoder change no more than once in 1mS. If both A and B change in 1mS, the algorithm cannot determine if an up-count or a down-count has occurred.
In understanding the algorithm, consider that for instance a high-to-low transition of A implies an up-count if B is high, but a down-count if B is low. The algorithm works by assembling a 4-bit number consisting of the previous state of A and B (1mS ago), and the present state. The four bits form a number in the range 0 to 15. For instance if A was previously high and B was low, and they are both unchanged now, the code is 1010 (binary), which is 10 (decimal). The codes are translated to up-counts or down-counts (or neither) by being used as an index of the array DecoderLookup.
If both A and B changed since 1mS ago (code 1001 for instance), then the encoder is moving too fast for the interrupt interval. This is an error condition ("overrun"). It is detected by the second part of the ISR, and a light is turned on to indicate the error. Once it is determined that this does not happen in normal operating conditions, the error-checking part of the ISR can be removed.