Trackball encoder 2

February 6, 2014 5:45 PM Published by

If you are not watching direction, a wiggle of the shaft can count just as easy as rotation in a single direction.

That being said, A and B are usually coded as square waves 90 degrees out of phase, so you have 4 states

1) Both A and B low
2) A high and B low
3) Both A and B high
4) A low and B high.

So to count both up and down, you could look for a rising edge on A.

This happens on either going from state 1 to state 2, or rotating backwards, from state 4 to state 3.

The way to tell which way is to determine if you are in state 2 or state 3 after the rising edge. The easy way to do that is to look at B. B is low in State 2; it is high on state 3.

So say you tied A to INT0, and set it to interrupt on a rising edge. Your interrupt service routine would start on A rising. It could the look at B to see whether it is a count up or down. Up for B low. Down for B high.

You may of course merely poll for rising edges.

Another way to do it is to decode A and B into states. Probably easier to enumerate them as state 0 through state 3 instead of 1 through 4 as above. The just look for state transitions. If you go from 0 -> 1 or 1 -> 2 or 2 -> 3 to 3 -> 0 then you should count up. If you go from 0->3 or 3->2 or 2->1 or 1->0, then you should be counting down. Basically thats either counting up or down modulo 4.

// determine current state
state=0;
if (A) state |= 1;
if (b) state |= 2;
//count up or down on state change
if ( state != laststate )
{
//check for state incrementing modulo 4
if ( ((laststate+1) & 0x3) == state )
count++;
else
count--;
}
//current state is next time's laststate
laststate= state;  

 

Categorised in:


Tag Cloud