Go Down

Topic: Arduino map function for float values (Read 16915 times) previous topic - next topic

Uptown

Jul 21, 2012, 11:13 pm Last Edit: Jul 21, 2012, 11:16 pm by Uptown Reason: 1
Hello everyone.

My problem is I need something like a map function, but it should return float.

I had an idea about it.

a regular map - function is map(x,a,b,c,d)  -->an example  ...= map(val,0,1024,0,100);

Quote
x is a value that you read by using analogRead() -function

a lower border of the values that analogRead can provide
b upper border of the values that analogRead can provide

c lower border of your value range
d upper border of your value range



my solution is

float z= x/(b-a)*(d-c)+c  Note: x,a,b,c and d should be float

Finally the whole function

float map_to_float(float x, float a, float b, float c, float d)
{
      float f=x/(b-a)*(d-c)+c;
      return f;
}



Is it correct? if it do, so i can write a small library if you want

thanks for attention

tmd3

That formula works only if a is zero.  For a general solution, the numerator of the fraction should be (x-a).

Uptown


Riva

From the map() reference page here http://arduino.cc/en/Reference/Map the map function is just this
Code: [Select]
long map(long x, long in_min, long in_max, long out_min, long out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

I would assume changing all longs to floats and renaming the mapping function to something like mapf() would work.
Don't PM me for help as I will ignore it.

nickgammon

Make a template function to be more general?
Please post technical questions on the forum, not by personal message. Thanks!

More info: http://www.gammon.com.au/electronics

nitrof

#5
Aug 27, 2016, 06:46 pm Last Edit: Aug 27, 2016, 06:48 pm by nitrof
Old topic but.. like this:

Code: [Select]

template <class X, class M, class N, class O, class Q>
X map_Generic(X x, M in_min, N in_max, O out_min, Q out_max){
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}


will return x type.

Edit:       It have to be put on a header file and #inlcude to compile !

Go Up