Documentation for map() misleading

The map(value, fromLow, fromHigh, toLow, toHigh) call is useful to map one range to another, but I find the documentation misleading. Is says that given value == fromHigh it will return toHigh. That is technically correct, but implies that fromHigh and toHigh should be the highest valid input and output-values. However, to map correctly the function should be given the first non-valid number for fromHigh and toHigh.

Example: We read an analog input, valid range 0-1023 inclusive. We want to display the value by lighting up a LED, and we have 16 LEDs to choose from. Valid range = 0-15 inclusive. One might be tempted to use

led = map(value, 0,1023, 0,15);

to find out which LED to light up, but

led = map(value, 0,1024, 0,16);

will give much better results (i.e. the input range will be divided into 16 equal-sized parts).


map(1023, 0,1023, 0,15);  // returns 15
map(1022, 0,1023, 0,15);  // returns 14 !


map(value, 0,1024, 0,16);

will return 15 for all values in the range 960-1023. Can someone with proper access rights please update the documentation?

But 0 to 1024 are 1025 numbers, and the adc return a value between 0 and 1023 and not between 0 and 1024.

Does anything here help...

Does anything here help…

Well, I personally don’t need any help - I’ll tailor my code for how map() actually works as opposed to how it’s documented.

In the linked thread, IDoSoLikeGreenEggsAndHam has pointed out the same problem as I did and suggested that the map() function ought to be fixed. I realize that changing the map-function is no good because that might break preexisting code.
Therefore I suggested to update the documentation so that it agrees with how map() works, i.e. that one should supply the first value outside the ranges for fromHigh and toHigh rather than the highest value within the ranges.

Did you read my last post in that thread?

Did you read my last post in that thread?

Yes - you are pointing out that when given the lowest and highest values within the ranges, map will truncate rather than round, which agrees with what the documentation says.

That makes the documentation correct, but it can still be misleading. I believe most users would want and expect a mapping function to round properly. Reading the current docs they might say “so it truncates. Ah well, that’s not quite what I wanted but I suppose I’ll have to live with that”.

Now, there is an easy way to make the function round properly - just supply the first value inside and the first value outside each range. I just wish the documentation would mention that.