encoder count wrapping

S

Thread Starter

satyan

Can any one help for coding encoder counts wrapping my counts are between -32767 to 32767
 
R

Robert Scott

How you handle wrap-around of encoder counts depends on what you are doing with it. If you are only looking for relative changes of less than 32767 counts then merely subtracting two counts always works, even if the two counts are on opposite sites of a wrap boundary, provided the subtraction takes place using 16-bit numbers. That is,

-32768 minus 32767 in hexadecimal is
0x8000 minus 0x7fff which is 0x0001
or just 1, which is what you want.

But if you perform the subtraction using 32-bit numbers you can get a very wrong answer, as in:

-32768 in 32-bit numbers is 0xffff8000
32767 in 32-bit numbers is 0x00007fff
Subtracting gives 0xffff0001 which is wrong.

This can be fixed by masking with 0x0000ffff after subtraction.

Things get more complicated when you need to compare positions that are more than 32767 counts apart. In that case merely subtracting the starting position from the ending position will not work. You need to count overflows during the move. That means you must monitor the encoder count as it gradually changes from the start position to the end position and count the number of times there is a wrap-around. To do that reliably you need to guarantee that the position will be sampled after no more than 32767 counts.

The count of overflows obtained this way can be used to synthesize a higher-order word for the encoder count so that you end up dealing with 24 or 32 bits instead of just 16.

Robert Scott
Real-Time Specialties
Hopkins, MN
 
Top