Description

The encoder module uses to inputs to keep track of the quadrature outputted by the rotary encoder to keep track of position and direction of the steering wheel. The initialization sets up an input capture interrupt on rising edges of one of the two signals. In the interrupt response routine, the value of the other signal is checked to determine whether the encoder count should be incremented or decremented. Since there are only seven discrete values for steering command in each direction, the software saturates the encoder count at -7 and 7, so that the user overturning the wheel will not delay the response time of turning the wheel back in the other direction. Also, to provide a reasonably wide arc for each discrete value, a second counter is employed in order to update the encoder count only every four times the actual encoder ticks. A helper function converts the encoder count to the four-bit code required by the communications protocol.

Pseudo-Code

initEncoder:
    Set PT0 and PU6 to be inputs
    Use the fastest possible clock rate for increased resolution
    Enable the timer subsystem
    Set up TIM0_TC4 (PT0) as an input capture that interrupts on rising edges only
    Clear the interrupt flag to give us a clean start
ChanA_IC:
    Clear the interrupt flag
    If the other channel is high
        Increment the encoder spacing counter
        If the encoder spacing counter is now a multiple of 4, increment the encoder count
        If the encoder count is now greater than 7
            Set the encoder count to 7
            Decrement the encoder spacing counter to undo that increment as well
    Otherwise (the other channel is low)
        Decrement the encoder spacing counter
        If the encoder spacing counter is now a multiple of 4, decrement the encoder count
        If the encoder count is now less than -7
            Set the encoder count to -7
            Increment the encoder spacing counter to undo that decrement as well
getSteering:
    Return the four-bit code corresponding to the current encoder count