Basics · 11 min read

Arduino map() Function: Usage, Examples and constrain()

How do you use the Arduino map() function? Syntax, the integer division trap, limiting with constrain(), potentiometer to servo and PWM examples, ESP32 and Pico.

The Arduino map() function is a built-in command that proportionally converts a value from one number range to another. When you want to turn a 0–1023 reading from a potentiometer into 0–180 degrees for a servo, a 0–255 PWM value for LED brightness, or 0–100 percent for a display, it does the job in one line. In short, map() is a ruler converter that fits the scale you have onto the scale you want.

But map() isn't as harmless as it looks: it works only with integers, throws away the decimal part and doesn't limit the result to the target range. In this post you'll see the function's formula, the surprises caused by integer division, safe use with constrain(), real examples from potentiometer to servo and from sensor to PWM, and how the same job is done on the ESP32's 12-bit ADC and on the Raspberry Pi Pico with MicroPython, step by step.

Potentiometer used with the Arduino map() function
The potentiometer is the input device most often used with map(): the 0–1023 reading is converted to a servo angle or a PWM value.

What is Arduino map() and how does it work?

map() sets up a linear proportion between two ranges. It finds what percentage of its own range the input value sits at, then calculates the number at the same position in the target range. The definition in the Arduino core is a single line: (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min. All parameters and the return value are of type long, which on the Uno is a 32-bit signed integer. The syntax is map(value, fromLow, fromHigh, toLow, toHigh), and you don't need to add any library to use it.

ParameterMeaningPot → servo example
value (x)The value to convertResult of analogRead(A0)
fromLow (in_min)Lower limit of the input range0
fromHigh (in_max)Upper limit of the input range1023
toLow (out_min)Lower limit of the output range0
toHigh (out_max)Upper limit of the output range180
Return valueThe equivalent in the target range (long)An angle between 0 and 180

Let's work through an example: with the potentiometer exactly in the middle, analogRead() returns about 512. For map(512, 0, 1023, 0, 180), first 512 - 0 = 512 is found, this is multiplied by 180 - 0 = 180, giving 92160. Then it's divided by 1023: 92160 / 1023 = 90.09. Because integer division drops the decimal, the result is 90 degrees; finally the output lower limit, 0, is added. If you swap the output limits, the direction reverses too: map(x, 0, 1023, 255, 0) produces a value that falls as the potentiometer rises. Negative ranges work fine as well; you can turn a joystick axis into forward-reverse motor speed with map(x, 0, 1023, -255, 255). The table below summarises the most common conversions.

GoalCodeNote
Potentiometer → servo anglemap(x, 0, 1023, 0, 180)For Servo.write()
Potentiometer → PWMmap(x, 0, 1023, 0, 255)For analogWrite(); x / 4 gives a more even spread
Analog reading → percentmap(x, 0, 1023, 0, 100)To show a percentage on a display
Joystick → motor speed and directionmap(x, 0, 1023, -255, 255)The sign gives direction, the magnitude gives speed
Reversed direction (dark → bright)map(x, 0, 1023, 255, 0)Swap the output limits
ESP32 12-bit ADC → PWMmap(x, 0, 4095, 0, 255)On the ESP32 analogRead() returns 0–4095

The integer division limit: why doesn't map() give decimals?

Because the division inside map() is done with integers, the result is always truncated towards zero; the decimal part isn't rounded, it's simply discarded. In a narrow target range this becomes very obvious. For example, if you write map(x, 0, 1023, 0, 10) to turn a potentiometer into a 0–10 level indicator, you get this table:

Input (x)Actual ratiomap() result
00.0000
1020.9970
1031.0071
5125.0055
10229.9909
102310.00010

Here's the real problem in the table: 103 different input values (0–102) produce the result 0, while the top value, 10, is produced by only a single input, 1023. If you don't turn the potentiometer all the way, your indicator never reaches 10. If you want an even distribution, you can raise both upper limits by one and write map(x, 0, 1024, 0, 11); each output value then corresponds to roughly 93 input values, and the result still stays between 0 and 10. The second limit is overflow: if the intermediate product (x - in_min) * (out_max - out_min) exceeds the 32-bit long limit of about 2.1 billion, the result breaks. Large ranges such as map(50000, 0, 100000, 0, 100000) produce a 5-billion intermediate product on the Uno and give a wrong result. The third limit is the need for decimals: if you write map(x, 0, 1023, 0, 5) to turn an analog reading into a 0–5 V voltage, you only get the results 0, 1, 2, 3, 4 and 5. In that case you should write your own floating-point map function using the same formula:

C++ (Arduino IDE)
1// Ondalikli map fonksiyonu / Floating-point map function
2float mapFloat(float x, float inMin, float inMax, float outMin, float outMax) {
3  return (x - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
4}
5
6void setup() {
7  Serial.begin(9600);
8}
9
10void loop() {
11  int raw = analogRead(A0);                          // 0-1023 ham deger / raw value
12  float volt = mapFloat(raw, 0, 1023, 0.0, 5.0);     // 0.00-5.00 V
13  long milliVolt = map(raw, 0, 1023, 0, 5000);       // tamsayi mV / integer mV
14  int percent = map(raw, 0, 1023, 0, 100);           // tamsayi yuzde / integer percent
15
16  Serial.print(F("Ham / Raw: "));
17  Serial.print(raw);
18  Serial.print(F("  V: "));
19  Serial.print(volt, 2);
20  Serial.print(F("  mV: "));
21  Serial.print(milliVolt);
22  Serial.print(F("  %: "));
23  Serial.println(percent);
24  delay(500);
25}
On the Uno, float operations are several times slower than integer ones and use more program memory. If decimals aren't essential, use integer map(); if you want precision, make the target unit smaller. For example, calculate voltage in millivolts instead of volts: map(raw, 0, 1023, 0, 5000) gives 0–5000 mV, and the largest intermediate product (5,115,000) stays far below the long limit.

Using it together with constrain

map() doesn't treat the target range as a limit; it only calculates a proportion. If the input goes outside the range you expect, the output goes outside too. Say you measured that an LDR actually gives values between 200 and 900 and you wrote map(x, 200, 900, 0, 255). When a powerful torch pushes the value up to 980, the result is (980 - 200) * 255 / 700 = 284; if the value drops to 150 when the room is very dark, you get -18. On the Uno, analogWrite() interprets a value above 255 differently depending on the pin; on pin 6, for example, 284 is cut to 8 bits and becomes 28, which is an almost dark LED. The fix is the constrain(value, low, high) function: it squeezes the value within the given limits. There are two correct orders: limit the input before map(), i.e. map(constrain(x, 200, 900), 200, 900, 0, 255), or limit the result after map(), i.e. constrain(map(x, 200, 900, 0, 255), 0, 255). Both stop you leaving 0–255; if you're calibrating a sensor, limiting the input is easier to read.

On the Arduino Uno (AVR) core, constrain() is a macro, not a function, and evaluates its parameters more than once. If you write constrain(analogRead(A0), 200, 900), analogRead() may run several times and the value compared may differ from the value returned. Take the reading into a variable first, then put that variable inside constrain().

Wiring table: Arduino Uno, ESP32 and Pico

ConnectionArduino UnoESP32Raspberry Pi Pico
Potentiometer outer pins5V and GND3V3 and GND3V3 and GND
Potentiometer middle pinA0GPIO 34GP26 (ADC0)
LDR + 10 kΩ divider midpointA1GPIO 35GP27 (ADC1)
LED (with 220 Ω resistor)D6 (PWM)GPIO 25GP15
Servo signal (orange wire)D9GPIO 13GP16
ADC reading range10-bit (0–1023)12-bit (0–4095)read_u16(): 0–65535
The analog inputs of the ESP32 and Pico accept 3.3 V at most. If you connect the potentiometer's ends to the 5V pin out of habit, the middle pin can reach 5 V and the ADC input can be permanently damaged. On these boards always power the potentiometer from the 3V3 pin; if you use a sensor with a 5 V output, first bring the level down with a voltage divider.

Step by step: setting a servo angle with a potentiometer

  1. Connect the two outer pins of the 10 kΩ potentiometer to the Arduino's 5V and GND pins, and the middle pin to A0.
  2. Connect the SG90 servo's brown wire to GND, its red wire to 5V and its orange signal wire to D9.
  3. Check that the Servo library is installed; it comes with the Arduino IDE, so you don't need to download anything.
  4. Upload the code below and open the Serial Monitor at 9600 baud.
  5. As you turn the potentiometer, watch the raw value and the angle change together on screen and the servo turn between 0 and 180 degrees.
  6. If the servo strains and buzzes at the end points, pull the map() output into a narrower range such as 10–170.
C++ (Arduino IDE)
1#include <Servo.h>
2
3const int POT_PIN = A0;     // potansiyometre orta ucu / potentiometer wiper
4const int SERVO_PIN = 9;    // servo sinyal pini / servo signal pin
5
6Servo servo;
7
8void setup() {
9  servo.attach(SERVO_PIN);
10  Serial.begin(9600);
11}
12
13void loop() {
14  int raw = analogRead(POT_PIN);           // 0-1023 ham deger / raw value
15  int angle = map(raw, 0, 1023, 0, 180);   // dereceye cevir / convert to degrees
16  angle = constrain(angle, 0, 180);        // guvenlik siniri / safety limit
17  servo.write(angle);
18
19  Serial.print(F("Ham / Raw: "));
20  Serial.print(raw);
21  Serial.print(F("  Aci / Angle: "));
22  Serial.println(angle);
23  delay(20);                               // servoya zaman tani / give the servo time
24}

In the code, analogRead() returns a 10-bit value, map() converts it to degrees, and constrain() guarantees that even if you change the range later, no angle outside 0–180 goes to the servo. Because the Uno's ADC is slightly noisy, the value can wander between 511, 512 and 513 even if you don't touch the potentiometer, which makes the servo jitter. Averaging a few readings, or calling servo.write() only when the angle changes by more than 2 degrees, largely solves the problem. For details, see the posts on servo jitter and filtering sensor data. If you're curious how a servo works, What Is a Servo Motor? is a good place to start.

From sensor to PWM: automatic LED brightness with an LDR

map() isn't only for potentiometers; it works with every analog sensor. In this example one end of the LDR is connected to 5V and the other to A1; a 10 kΩ resistor is also fitted between A1 and GND. With this wiring, as the light increases the LDR's resistance drops and the voltage at A1 rises. First note down the values read in a dark room and in bright light on the Serial Monitor; for example 150 and 850. These two numbers are your calibration limits. The code makes the LED brighter as the room gets darker, so the output range is written in reverse: from 255 to 0. For how an LDR works, see LDR Light Sensor, and for the background on PWM, see What Is PWM?.

C++ (Arduino IDE)
1const int LDR_PIN = A1;     // LDR + 10k bolucu / LDR + 10k divider
2const int LED_PIN = 6;      // PWM pini / PWM pin
3const int DARK = 150;       // karanlikta olculen / measured in the dark
4const int BRIGHT = 850;     // aydinlikta olculen / measured in bright light
5
6void setup() {
7  pinMode(LED_PIN, OUTPUT);
8  Serial.begin(9600);
9}
10
11void loop() {
12  int raw = analogRead(LDR_PIN);
13  int limited = constrain(raw, DARK, BRIGHT);       // once sinirla / limit first
14  int pwm = map(limited, DARK, BRIGHT, 255, 0);     // karanlik = parlak / dark = bright
15  analogWrite(LED_PIN, pwm);
16
17  Serial.print(raw);
18  Serial.print(F(" -> "));
19  Serial.println(pwm);
20  delay(100);
21}

map() on the ESP32: 12-bit ADC and LEDC PWM

On the ESP32, map() works the same way; what changes is the input range. The ESP32's ADC has a default resolution of 12 bits, so analogRead() returns 0–4095 instead of 0–1023. If you leave map(x, 0, 1023, ...) in code ported from the Uno, you use up the whole output range in the first quarter of the potentiometer's travel, and in the rest the values overflow up to four times the target range. So on the ESP32 write the input as 0–4095, or drop to 10 bits with analogReadResolution(10). On the PWM side the ESP32 uses the LEDC unit; Arduino core 3.x introduced ledcAttach(pin, frequency, resolution), while 2.x uses the channel-based ledcSetup() and ledcAttachPin(). The code below compiles on both versions. Because ADC2 pins can't be read while Wi-Fi is on, we connect the potentiometer to GPIO 34, which is on ADC1. If you want to drive a servo on the ESP32, you can use the same logic with the ESP32Servo library and the line map(x, 0, 4095, 0, 180).

C++ (Arduino IDE)
1const int POT_PIN = 34;      // ADC1 pini, yalniz giris / ADC1 pin, input only
2const int LED_PIN = 25;      // PWM cikisi / PWM output
3const int PWM_FREQ = 5000;   // 5 kHz
4const int PWM_RES = 8;       // 8 bit: 0-255
5
6#if ESP_ARDUINO_VERSION_MAJOR < 3
7const int PWM_CH = 0;        // 2.x icin LEDC kanali / LEDC channel for 2.x
8#endif
9
10void setup() {
11  Serial.begin(115200);
12  analogReadResolution(12);  // 0-4095
13#if ESP_ARDUINO_VERSION_MAJOR >= 3
14  ledcAttach(LED_PIN, PWM_FREQ, PWM_RES);
15#else
16  ledcSetup(PWM_CH, PWM_FREQ, PWM_RES);
17  ledcAttachPin(LED_PIN, PWM_CH);
18#endif
19}
20
21void loop() {
22  int raw = analogRead(POT_PIN);                // 0-4095
23  int duty = map(raw, 0, 4095, 0, 255);         // 12 bit -> 8 bit
24  duty = constrain(duty, 0, 255);
25#if ESP_ARDUINO_VERSION_MAJOR >= 3
26  ledcWrite(LED_PIN, duty);                     // 3.x: pin numarasi / pin number
27#else
28  ledcWrite(PWM_CH, duty);                      // 2.x: kanal numarasi / channel number
29#endif
30  Serial.printf("%d -> %d\n", raw, duty);
31  delay(20);
32}

The ESP32 ADC has a quirk you need to know about: it isn't linear at the ends. With the default attenuation setting, voltages below about 0.1 V read as 0, and above about 3.1 V the value saturates at 4095; in between, the measurement is slightly curved. So you may reach 4095 before turning the potentiometer all the way, or feel a dead zone at the start. The practical fix is to measure the real minimum and maximum readings and use those limits in map() and constrain(). If you need a voltage, the analogReadMilliVolts() function, which uses the factory calibration, gives more accurate results than map. For the board's general features, see What Is the ESP32?.

The equivalent of map() on Raspberry Pi Pico and MicroPython

MicroPython has no ready-made map() like Arduino's; Python's map() does something completely different and applies a function to a list. So you write the same formula yourself. On the Pico, ADC.read_u16() returns the physical 12-bit measurement scaled to 16 bits, in the range 0–65535; PWM.duty_u16() also expects a duty value between 0 and 65535. Because Python integers have unlimited size, you don't suffer the overflow problem of the Uno. The difference to watch is that the // operator always rounds towards negative infinity, whereas map() in C++ truncates towards zero, so with negative ranges you may see a 1-unit difference between the two languages. If you want a decimal result, just use / instead of //. In the code the potentiometer is read from GP26, the LED on GP15 follows the brightness, and the servo on GP16 follows the angle. For the LED we limit the input to 500–65000, because the Pico's ADC rarely reaches exactly 0 and 65535 at the ends. On the servo side, 0–180 degrees at 50 Hz PWM corresponds to a pulse of roughly 500–2500 microseconds for most SG90s. If you're new to the Pico, you can start with What Is the Raspberry Pi Pico? and MicroPython basics.

MicroPython
1from machine import ADC, Pin, PWM
2import time
3
4pot = ADC(26)                    # GP26 = ADC0
5led = PWM(Pin(15))               # LED GP15
6led.freq(1000)
7servo = PWM(Pin(16))             # servo sinyal GP16 / servo signal GP16
8servo.freq(50)                   # 50 Hz = 20 ms periyot / period
9
10def map_range(x, in_min, in_max, out_min, out_max):
11    # Arduino map() karsiligi (tamsayi) / Arduino map() equivalent (integer)
12    return (x - in_min) * (out_max - out_min) // (in_max - in_min) + out_min
13
14def constrain(x, low, high):
15    # degeri sinirla / clamp the value
16    return max(low, min(x, high))
17
18while True:
19    raw = pot.read_u16()                                           # 0-65535
20    percent = map_range(raw, 0, 65535, 0, 100)                     # yuzde / percent
21    duty = map_range(constrain(raw, 500, 65000), 500, 65000, 0, 65535)
22    led.duty_u16(duty)                                             # LED parlakligi / LED brightness
23    angle = map_range(raw, 0, 65535, 0, 180)                       # derece / degrees
24    pulse_us = map_range(angle, 0, 180, 500, 2500)                 # darbe suresi / pulse width
25    servo.duty_ns(pulse_us * 1000)                                 # mikrosaniye -> nanosaniye / us -> ns
26    print(raw, percent, angle, pulse_us)
27    time.sleep_ms(50)

Project ideas using map()

  • Level indicator: Convert a potentiometer or sound sensor value to 0–8 with map(x, 0, 1024, 0, 9) and show it on a bar of 8 LEDs.
  • Joystick-controlled car: Convert a joystick axis to between -255 and 255 and set the direction and speed of the motors with an L298N.
  • Digital voltmeter: Convert the analog reading to millivolts and show it on an LCD; details are in building an Arduino voltmeter.
  • Plant moisture percentage: Convert the dry and wet calibration values of a soil moisture sensor to a 0–100 percentage with constrain() and map().
  • Light-controlled instrument: Convert an LDR or distance value to a 200–2000 Hz range with map() and pass it to tone() as the frequency.
  • Speed-adjustable chasing LEDs: Convert a potentiometer to a delay time in milliseconds with map(x, 0, 1023, 50, 500).

Common mistakes and how to fix them

SymptomCauseFix
The result goes outside the target rangemap() doesn't limitLimit the input or output with constrain()
Decimal results always come out as whole numbersInteger division drops the decimalWrite mapFloat() or use a smaller unit (mV instead of V)
The top value is never reachedThe top value occurs for only a single inputSpread it evenly with map(x, 0, 1024, 0, max + 1)
Nonsense results with large numbersThe intermediate product exceeds the 32-bit long limitShrink the ranges or calculate with float or int64_t
On the ESP32 the value hits the ceiling too earlyThe code is written for 0–1023, but the ADC gives 0–4095Make the input range 0–4095
The direction works backwardsThe output limits or the sensor wiring are reversedSwap the output lower and upper limits
The result is constant and meaninglessin_min equals in_max, i.e. division by zeroCheck that the calibration limits are different
Instead of writing calibration as fixed numbers, measure it at run time: in setup(), read the sensor for a few seconds, record the smallest and largest value, then use those variables in map() and constrain(). If the two values stay equal, fall back to the default limits to avoid dividing by zero. That way the same code adjusts itself for different LDRs, potentiometers and environments. You can find the background on analog reading in What Is an ADC?.

The map() function is the translator between the sensor world and the output world: keep integer division in mind, protect the limits with constrain(), and if you write your board's ADC resolution correctly it works with the same logic on the Uno, ESP32 and Pico. You can revisit the basics of the potentiometer in What Is a Potentiometer?. In the BlueGrays app you can explore projects that use map(), such as speed-adjustable chasing LEDs, reading light intensity with an LDR, controlling a servo with a potentiometer and adjusting PWM brightness with the ESP32, step by step with circuit diagrams and code.

Frequently asked questions

What does the Arduino map() function do?

map() proportionally converts a number in one range to another range. Its most common use is turning a 0–1023 value read with analogRead() into 0–180 degrees for a servo or a 0–255 PWM value for analogWrite(). It needs no library and comes built into the Arduino core.

Does map() return decimal numbers?

No. map() works with the long type and drops the decimal part in division; for example, map(512, 0, 1023, 0, 5) gives 2, not 2.5. If you need decimals, write a mapFloat() function with float parameters using the same formula, or calculate the result in a smaller unit such as millivolts.

What is the difference between map() and constrain()?

map() converts a value from one scale to another but doesn't limit it; if the input is outside the range, the output goes outside too. constrain() doesn't change the scale, it only squeezes the value between the lower and upper limits you set. For safe use you write them together: map(constrain(x, 200, 900), 200, 900, 0, 255).

How do you set a servo angle with a potentiometer?

Connect the potentiometer's middle pin to A0 and the servo's signal wire to D9. In loop(), calculate the angle with int angle = map(analogRead(A0), 0, 1023, 0, 180); and send it to the servo with servo.write(angle). If the servo jitters, average a few readings or ignore small changes.

Does map() work differently on the ESP32?

The formula is the same, but because the ESP32's ADC is 12-bit, analogRead() returns 0–4095. So you should write the input range as map(x, 0, 4095, 0, 255). Because the ESP32's ADC isn't linear at the ends, measuring and using the real minimum and maximum readings gives better results.

Is there a MicroPython equivalent of Arduino's map() function?

There's no ready-made equivalent; Python's map() is a different construct that applies a function to lists. You write a short function using the formula (x - in_min) * (out_max - out_min) // (in_max - in_min) + out_min. Because read_u16() returns 0–65535 on the Pico, the input range is usually those values.

See all projects
LED Chaser with Adjustable Speed
AR-7Intermediate

LED Chaser with Adjustable Speed

Six LEDs light up one after another, so the light seems to run from one end to the other.

4.6(72)
148
Knight Rider LED Effect with Adjustable Speed
AR-8Intermediate

Knight Rider LED Effect with Adjustable Speed

A light runs from one end of six LEDs to the other, turns around and runs back again.

4.5(60)
124
Measuring Light Intensity with an LDR
AR-11Beginner

Measuring Light Intensity with an LDR

Want to see how bright your room is as a number? The LDR, a small part that reacts to light, measures the light around it, and the Arduino writes the value to your computer screen every half second.

4.6(84)
144
Servo Motor Operation with Potentiometer
AR-36Beginner
Premium

Servo Motor Operation with Potentiometer

As you turn the potentiometer knob, the servo motor's arm turns right along with it: one end of the knob means zero degrees, the other end means half a turn.

4.6(37)
53
ESP32 LED Brightness Control with a Potentiometer (Analog → PWM)
ES-13Intermediate
Premium

ESP32 LED Brightness Control with a Potentiometer (Analog → PWM)

In this project, we control the brightness of an LED analogically using a potentiometer. The ESP32's ADC pin reads the 0-3.3V voltage from the potentiometer, and this value is then converted into a PWM (Pulse Width Modulation) signal and sent to the LED. As a result, as you turn the potentiometer, the LED gradually brightens and dims. With Arduino Core 3.0+, analogWrite() can be used directly; on the ESP32-S2/S3, the ADC resolution is fixed at 12-bit.

4.5(19)
32
ESP32 Servo Motor (Potentiometer Control)
ES-16Intermediate
Premium

ESP32 Servo Motor (Potentiometer Control)

In this project, we control an SG90 servo motor using a potentiometer. We adjust the servo angle by mapping the analog value read from the potentiometer to the 0–180-degree range. The ESP32Servo library generates servo signals on suitable output-capable GPIO pins of the ESP32; this project uses GPIO 18. This is a fundamental control method for robotic arms, camera gimbals, and automatic door mechanisms.

4.3(29)
42
Servo Control with Joystick
AR-60Intermediate
Premium

Servo Control with Joystick

Steer two motors with a joystick, just like turning a security camera. Push the stick left or right and the bottom servo motor slowly turns, push it up or down and the top servo tilts up and down…

4.7(42)
58