Arduino project: the map() function
By Flavio Copes
Learn how the Arduino map() function converts a value from one range to another, like turning a 0 to 1023 analog reading into a smaller set of steps.
The Arduino map() function converts a value from one range to another. You give it a number, the range it comes from, and the range you want, and it returns the proportionally scaled value.
Why do we need it? When you acquire analog values from an analog input pin, by default they are acquired as values ranging from 0 to 1023.
This is because the analog read resolution is 10 bits, and 2^10 is 1024.
Tip: on ARM-based Arduino devices, like Arduino Zero, Arduino Due and the Arduino MKR family, you can map up to 12 bits, but the default is 0. On those devices you can call the
analogReadResolution(12)to set the resolution to 12 bits, so you can go from 0 to 4095 instead of 1023
That 0-1023 range rarely matches what the rest of your program needs. Maybe you want 10 steps for a menu, or 0-255 for a PWM output. map() handles the conversion.
How to use map()
Here’s the function signature:
int <newvalue> = map(<value>, <original_min>, <original_max>, <new_min>, <new_max>);
Note that the function returns an integer value, the decimal part is cut. Mapping 512 from 0-1023 to 0-9 gives 4, not 4.5.
For example you might want to map the original 1024 values we mentioned you can acquire through analog input to a set of only 10 values, because you might have some logic that only handles 10 steps.
You can do so like this:
int acquiredValue = analogRead(A1);
int value = map(acquiredValue, 0, 1023, 0, 9);
Here’s a full example:
void setup() {
Serial.begin(9600);
}
void loop() {
int acquiredValue = analogRead(A1);
int value = map(acquiredValue, 0, 1023, 0, 9);
Serial.println(value);
}
Now instead of the input having 1024 possible values, you have a restricted set of 10 possible values, going from 0 to 9.
A common use: PWM output
The most frequent use of map() is driving a PWM pin from an analog reading. analogRead() gives you 0-1023, but analogWrite() accepts 0-255.
Here’s a potentiometer controlling the brightness of a LED on pin 9:
int reading = analogRead(A1);
int brightness = map(reading, 0, 1023, 0, 255);
analogWrite(9, brightness);
Turn the knob, the LED dims and brightens.
map() does not limit values
Be careful with one thing: map() does not constrain the result to the target range. If the input goes outside the original range, the output goes outside the new range too. Pass 2000 to our 0-1023 mapping and you’ll get a value above 9.
That matters when your sensor can spike beyond the expected range. The fix is to clamp the result with constrain():
int value = map(acquiredValue, 0, 1023, 0, 9);
value = constrain(value, 0, 9);
Now the value is guaranteed to stay between 0 and 9.
Related posts about electronics: