I was recently using map() to map a pot input to the range 0,1. I noticed that I could only get a "1" as output when the pot was turned 100%. I had expected that the output value would change from 0 to 1 at about 50%.
I spent some time looking at the map() docs at http://www.arduino.cc/en/Reference/Map, both the explanation of integer math and truncated rather than averaged value, plus the actual implementation code, and I now completely understand why I have to have pot cranked to 100% to get a "1" output.
(quick aside in case it's not obvious. Here's the output from a couple of example maps:
map(x, 0, 1023, 0, 15);
0 69
1 68
2 68
3 68
4 68
5 69
6 68
7 68
8 68
9 68
10 69
11 68
12 68
13 68
14 68
15 1
map(x, 0, 1023, 0, 1);
0 1023
1 1
The output can be properly normalized by adding one to both in_max and out_max (and then wrapping in constrain(), which I should probably do anyway). Here's what the output distribution looks like for the same application, but with the maxes raised by one:
map(x, 0, 1024, 0, 16);
0 64
1 64
2 64
3 64
4 64
5 64
6 64
7 64
8 64
9 64
10 64
11 64
12 64
13 64
14 64
15 64
map(x, 0, 1024, 0, 2);
0 512
1 512
So, ok, great. I found an issue in my own code, it matches the textual documentation and implementation of the library function, and I know how to change my expectations and/or code to get what I want.
Here's my question though - should this issue be documented anywhere? I'm sure I'm not the first person to find this issue because I've found some example sketches where the author did it correctly (and did it in a way where I'm almost positive they did it on purpose), but the vast majority of code you come across on the internet uses the method which will result in an uneven distribution, and I haven't been abe to google up any discussion of the distribution issue. Even the map() documentation uses an example that will result in an uneven distribution without directly pointing out the issue.
Am I crazy? I know that for the most part, with analog in and out, this isn't a big deal, but it still seems really odd to me that I can't find any discussion of the issue. I don't have a ton of experience with arduino programming so I may be missing something obvious, would love some more experienced eyes on this.
Thanks!