## need help with clamping function.

2 posts / 0 new
Author
Message

X and Y data is a 7 bit -80 0 80 with a sign on the 8th. but the data typically is -60 to 60.  I need to expand and move to 0-255 with clamping. Loss of data is ok.

uint8_t x=0,y=0;

x=getX();

y=getY();

int xx = x * 1.5;
int yy = y * 1.4;
yy += 6;//offset

yy = yy +127;// + 127 as the data rest is at 0
xx = xx +127;

//clamp
if (yy > 253) yy = 254; else if (yy< 1) yy = 1;//clip if needed.
if (xx > 253) xx = 254; else if (xx< 1) xx = 1;

reportBuffer[X_MAIN_STICK] = (int8_t)(xx);
reportBuffer[Y_MAIN_STICK] = (int8_t)(255 -yy);

I'm sure there is an easier way to do this then multiplication?

Last Edited: Sun. Oct 22, 2017 - 04:46 AM

Actually, doing the clamp up front got the multiplication out of the way.

uint8_tx=0,y=0;
x=getX();

y=getY();

if (y > 63)y = 63; else if (y < -63) y = -63;//clip to 128 max
if (x> 63) x = 63; else if (x < -63) x = -63;

reportBuffer[X_MAIN_STICK] = (x<<1)+128;
reportBuffer[Y_MAIN_STICK] = 255-((y<<1)+128);

Last Edited: Sun. Oct 22, 2017 - 04:53 AM