Math Function for Variable

Ok, Please put on your math hats.

I have a situation where I need to create a function that will work on an input variable to convert the outputs into the values needed to go to PWM.

So here is what I know:
With an input of 30 I need the output to be 0
With an input of 60 I need the output to be 62.5
With an input of 90 I need the output to be 125
With an input of 150 I need the output to be 250

So, what function can I pass a variable with each of those input variables through that will return the listed outputs?

Are those the only inputs or do you need to be able to interpolate between them?

I need it to interpolate float values

it needs to take any float between 30 and 150 and spit out a PWM value between 0 and 250.

Hi @ccole

Those points form a line, which can be described with a few forms of an equation. Here is the one that shows you how to figure this out:

  out = (in-30)*(62.5/(60-30));

Basically you have find the offset (aka bias) to get to zero (30 in this case) and then scale the result so that the next point will fit by correcting the input value (60-30) in the same way and then multiply by the values you to get. You can reduce the messy 62.5/(60-30) to 2.0833 if you want and multiply out if you want a*x+b type of equation.

1 Like

Fantastic!! Thank you SOO much!

Isn’t this just a map() function redux of floats?

double val[] = {30, 60, 90, 150};


void setup() 
{
  Serial.begin(9600);
  for(int i = 0; i < sizeof(val)/sizeof(val[0]); i++)
  {
    Serial.println(mapFloat(val[i], 30, 150, 0, 250));
  }
}

void loop() 
{
}

double mapFloat(double value, double in_min, double in_max, double out_min, double out_max)
{
  return (value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

outputs:

0.0
62.5
125.0
250.0
1 Like