Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bad example for the map() function #975

Open
resnickj opened this issue Mar 6, 2024 · 0 comments
Open

bad example for the map() function #975

resnickj opened this issue Mar 6, 2024 · 0 comments

Comments

@resnickj
Copy link

resnickj commented Mar 6, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant