You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This example is given for the map() function (here):
/* Map an analog value to 8 bits (0 to 255) */
void setup() {}
void loop() {
int val = analogRead(0);
val = map(val, 0, 1023, 0, 255);
analogWrite(9, val);
}
However, use of 1023 and 255 (as opposed to 1024 and 256) produces results that, from the perspective of integer math, aren't correct. Converting a 10 bit number to an 8 bit number is effectively a division by 4, and should produce the same result as a right shift by 2 bits. i.e. the number 4 should output 1 - not 0, as is the case when 1023 and 255 are used.
The root of the issue is perhaps the naming of the parameters - using the words "low" and "high" - and the lack of any guidance in the documentation itself as to whether the high value is meant to be inclusive or exclusive. Other codebases I have worked with typically use the convention that the upper end of an integer range is exclusive of the actual maximum value - i.e. 1024 instead of 1023 - because this makes the math work properly. I'm fairly new to Arduino, so if using inclusive upper values is the convention in this codebase, forgive me; but either way, it would be helpful if it were documented. (I suppose it is implicitly documented, given that the implementation of map is provided further down on the page, but that requires the reader to do a fair bit of work.)
The text was updated successfully, but these errors were encountered:
This example is given for the
map()
function (here):However, use of 1023 and 255 (as opposed to 1024 and 256) produces results that, from the perspective of integer math, aren't correct. Converting a 10 bit number to an 8 bit number is effectively a division by 4, and should produce the same result as a right shift by 2 bits. i.e. the number
4
should output1
- not0
, as is the case when 1023 and 255 are used.The root of the issue is perhaps the naming of the parameters - using the words "low" and "high" - and the lack of any guidance in the documentation itself as to whether the high value is meant to be inclusive or exclusive. Other codebases I have worked with typically use the convention that the upper end of an integer range is exclusive of the actual maximum value - i.e. 1024 instead of 1023 - because this makes the math work properly. I'm fairly new to Arduino, so if using inclusive upper values is the convention in this codebase, forgive me; but either way, it would be helpful if it were documented. (I suppose it is implicitly documented, given that the implementation of
map
is provided further down on the page, but that requires the reader to do a fair bit of work.)The text was updated successfully, but these errors were encountered: