map to floating point

I would like to print a value read on the analog input(0-1023) as 0-10.00

I can map it to 0-1000:

Serial.print(map(value,0,1023,0,1000),DEC)

but how can i add "." in the string?

Serial.print(map(value,0,1023,0.0,10.00),DEC)
would be perfect

2 Likes

In other words you want the map-function to return a float and not a long? It's not possible with the map-function, but you can write your own.

Here's map() modified to return a float (if I'm lucky - I haven't tried it):

float mapfloat(long x, long in_min, long in_max, long out_min, long out_max)
{
  return (float)(x - in_min) * (out_max - out_min) / (float)(in_max - in_min) + out_min;
}
3 Likes

This won't work if he wants to parse in decimal values in the function, i.e. wants to make the range 5.3 to 10.6. I'd just make everything a float.

float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

I'm pretty sure floats take up more memory however, so I'd be careful... Can someone confirm this?

6 Likes

Using either gives the same size on ATMega328P

It would not return the fraction only the whole number without any decimal places

1 Like

try this:

int value = analogRead(pin);
Serial.print( map(value, 0,1023,0,1000) / 100.0);

1 Like