Decode a quadrature encoder in software
The encoder rotates clockwise when Channel A leads Channel B. If Channel B leads Channel A, the encoder is rotating counter clockwise. By counting the pulses and the direction of rotation, you can find the position of the encoder. Although ICs can decode quadrature encoders, you can easily and less expensively have the processor decode the signal. The signals from Channel A and Channel B go through a Schmitt trigger if necessary, but many encoders and processors include this trigger internally. The signals are then applied to two I/O pins on the processor that support edge-triggered interrupts. The code in the interrupt handler implements a standard decoder algorithm, but all algorithms typically follow these steps:
- Set up a state table like the one in Table 1. The table wraps around from State 3 to State 0.
- Initialize a counter.
- Measure the current state of Channel A and Channel B. Find that state in the table and set a pointer to it.
- Enable the interrupts.
In the interrupt handler, use the following steps:
- Read the state of Channel A and Channel B.
- If the state is the one preceding the pointer, decrement the counter.
- If the state is the one following the pointer, increment the counter.
- Set the pointer to the new state. 5. Clear the interrupt.
| Read More|
The code in Listing 1 was tested on an MSP430F processor connected to an Encoder Products model 15T. The encoder monitored the position of a linear stage. The stage traveled 85 mm and could be tracked with resolution of 5 microns.
The define statements (highlighted in red) make the code more readable. The initPort() function (highlighted in blue) sets up the rising-edge interrupt on channels A and B. The final piece is the interrupt handler (highlighted in green). Note that it contains only six lines of code compared with the 20 or 30 lines it would take to implement the traditional method of decoding the channels.