EmbeddedRelated.com

Incremental Encoder Decode Trick

David January 16, 20131 comment Coded in C

This is a simple trick to detrmine the direction of rotation of a 2bit incremental encoder. This avoids the traditional tree of if-then statements that looks at both bits on each transition. An XOR statment is used on the lower bit of the new sample and the upper bit of last sample.

// Incremental encoder decoding.
uint new;
uint old;
bool direction; 
int count=0;

/* Get the latest 2bit sample. */
new = get_new_bits();  // Your function to get new samples.

/* XOR the lower bit from the new sample with the upper bit from the old.*/
direction = (new&1) ^ (old>>1)

/* The "direction" var holds the direction of rotation. */

/* Transfer the new sample to the old sample. */
old = new;

/* We can use this to inc or dec a counter to maintain position of rotation. */
if(direction) counter--; else counter++;