arduino / arduino/reference-en
bad example for the `map()` function
- Dominant language
- No language data
- Stars
- 173
- Forks
- 704
- PR merge metrics
- No merged PRs in 30d
Description
This example is given for the `map()` function ([here](https://www.arduino.cc/reference/en/language/functions/math/map/)):
```
/* 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.)
Contributor guide
No contributing guide indexed for this repository
Research direction
Start at the linked map() reference page and inspect the example and implementation shown there. Resolve whether the range endpoints are inclusive or exclusive, then update the example and add explicit guidance so the documented behavior and expected integer results are clear.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- arduino
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100