/*
autoscale V1.1
Scales a variable from one range of numbers to another range using linear interpolation
Paul Badger 2007
Modified from code by Greg Shakar
autoscale takes five parameters all integers, negative numbers will work with all parameters
originaMin - the minimum value of the original range - this MUST be less than origninalMax
originalMax - the maximum value of the original range - this MUST be greater than orginalMin
newBegin - the end of the new range which maps to orginalMin - it can be smaller, or larger, than newEnd, to facilitate inverting the ranges
newEnd - the end of the new range which maps to originalMax - it can be larger, or smaller, than newBegin, to facilitate inverting the ranges
inputValue - the variable for input that will mapped to the given ranges, this variable will be constrained to originaMin <= inputValue <= originalMax
*/
int j;
long scaledResult;
void setup() {
Serial.begin(9600);
}
void loop(){ // all this does is tests the function
for ( j=-60; j < 100; j++){
scaledResult = autoScale( -50, 75, 50, -50, j);
Serial.print(j, DEC);
Serial.print(" ");
Serial.println(scaledResult , DEC);
}
}
int autoScale( int originalMin, int originalMax, int newBegin, int
newEnd, int inputValue){
long zeroRefOriginalMax = 0;
long zeroRefnewEnd = 0;
long zeroRefCurVal = 0;
long rangedValue = 0;
boolean invFlag = 0;
// Check for out of range inputValues
if (inputValue < originalMin) {
inputValue = originalMin;
}
if (inputValue > originalMax) {
inputValue = originalMax;
}
// Zero Refference the values
zeroRefOriginalMax = originalMax - originalMin;
if (newEnd > newBegin){
zeroRefnewEnd = newEnd - newBegin;
}
else
{
zeroRefnewEnd = newBegin - newEnd;
invFlag = 1;
}
zeroRefCurVal = inputValue - originalMin;
// Check for originalMin > originalMax - the math for all other cases i.e. negative numbers seems to work out fine
if (originalMin > originalMax ) {
return 0;
}
if (invFlag == 0){
rangedValue = ((zeroRefCurVal * zeroRefnewEnd) /
zeroRefOriginalMax) + newBegin ;
}
else // invert the ranges
{
rangedValue = newBegin - ((zeroRefCurVal * zeroRefnewEnd) /
zeroRefOriginalMax) ;
}
return rangedValue;
}