14
May 09My favorite function
Ever since I started working with Arduinos I was in love with its map function. Map allows you to take a value range and convert it to another. So say you have a sensor giving you a range from 0 to 1024, but you need it from 100 to 255 you can do that. But you can also convert 0 to 1024 into 255 to 0, and it will calculate it correctly as well. So it goes down when the sensor reading goes up. Well I do a lot of sensor readings in flash as well, but actionscript does not have this much needed function. So I made one.
function map(val, min, max, minOut, maxOut){
var base = val - min;
var range = max - min;
var percent = base / range;
var rangeOut = maxOut - minOut;
return (percent * rangeOut) + minOut;
}
I also made a constrain function but it is very simple.
function constrain(val, min, max){
if(val < min){
return min;
}else if(val > max){
return max;
}else{
return val;
}
}