map()¶
Re-maps a number from one range to another.
Contents
Library Documentation¶
-
static long
map
(long value, long fromStart, long fromEnd, long toStart, long toEnd)¶ Remap a number from one range to another.
That is, a value equal to fromStart gets mapped to toStart, a value of fromEnd to toEnd, and other values are mapped proportionately.
Does not constrain value to lie within [fromStart, fromEnd].
If a “start” value is larger than its corresponding “end”, the ranges are reversed, so map(n, 1, 10, 10, 1) would reverse the range [1,10].
Negative numbers may appear as any argument.
- Return
- the mapped value.
- Parameters
value
-the value to map.
fromStart
-the beginning of the value’s current range.
fromEnd
-the end of the value’s current range.
toStart
-the beginning of the value’s mapped range.
toEnd
-the end of the value’s mapped range.
Discussion¶
map()
does not constrain values to within the range, because
out-of-range values are sometimes intended and useful. The
constrain() macro may be used either before or
after this function, if limits to the ranges are desired.
Note that the “lower bounds” of either range may be larger or smaller
than the “upper bounds” so that map()
may be used to reverse a
range of numbers; for example:
y = map(x, 1, 50, 50, 1);
The function also handles negative numbers well, so that this example
y = map(x, 1, 50, 50, -100);
is also valid.
The map()
function uses integer math (its arguments and return
values all have type long), so it will not generate
fractions, when the math might indicate that it should do so.
Fractional remainders are truncated, and are not rounded or averaged.
Example¶
/* Map an ADC reading (12 bits) to 16-bit PWM (0 to 65,535) */
void setup() {
pinMode(0, INPUT_ANALOG);
pinMode(9, PWM);
}
void loop() {
int val = analogRead(0);
val = map(val, 0, 4095, 0, 65535);
analogWrite(9, val);
}
See Also¶
License and Attribution
Portions of this page were adapted from the Arduino Reference Documentation, which is released under a Creative Commons Attribution-ShareAlike 3.0 License.