Constrain() not working?

Hey i have some code to print some value from a accelerometer and i map the accel value to a value between 0 - 255 but when i serial.print the value it exceeds the range even after i used constrain fucntion.

here is the code

int speed1 = map( accelerationY, 145, 180, 0, 255);
    constrain(speed1, 0, 255);
    int speed2 = map( accelerationX, 80, 130, 0, 255);
     constrain(speed2, 0, 255);
    
    Serial.print (speed1);
    Serial.print (" ");
    Serial.print(speed2);
    Serial.println();

you need to use constrain()'s return value:

speed1 = constrain(speed1,0,255);

What's wrong, you don't trust map? maybe you need to feed it more realistic values?

What's wrong, you don't trust map?

If the input value is outside the from range, the output value will be outside the to range. If that is an issue, using constrain() (properly) is a good idea.

Oh ok thanks! And yes my input is not always within the right range so thats why im using constrain

My point is that you might have the wrong range.

if performance is an issue you can merge constrain and map quite easily.
I wrote this function some time ago.

long strictMap(long val, long inmin, long inmax, long outmin, long outmax)
{
  if (val <= inmin) return outmin;
  if (val >= inmax) return outmax;
  return (val - inmin)*(outmax - outmin)/(inmax - inmin) + outmin;
}

I only do not like the name, thought of constrainedMap() (too long) CMap() (too vague) ... :wink:

limitMap()?

whackMap()?

OR go the unix way:
cm()