Uptown
July 21, 2012, 9:13pm
#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);

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;_

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

thanks for attention

tmd3
July 21, 2012, 10:34pm
#2
That formula works only if a is zero. For a general solution, the numerator of the fraction should be (x-a ).

Riva
July 22, 2012, 6:44am
#4
From the map() reference page here http://arduino.cc/en/Reference/Map the map function is just this

```
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.

1 Like

Make a template function to be more general?

nitrof
August 27, 2016, 4:46pm
#6
Old topic but.. like this:

```
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 !

1 Like