Re-maps a number from one range to another.
Contents
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.
Parameters
the value to map.
the beginning of the value’s current range.
the end of the value’s current range.
the beginning of the value’s mapped range.
the end of the value’s mapped range.
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.
/* 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);
}
License and Attribution
This documentation page was adapted from the Arduino Reference Documentation, which is released under a Creative Commons Attribution-ShareAlike 3.0 License.