Code Snippets

Incremental Encoder Decode Trick

David January 16, 20131 comment Coded in C
// 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++;