30 Days Lost in Space → Help Center

Coding Concepts

Arduino map() Function: How to Scale Values

map(value, fromLow, fromHigh, toLow, toHigh) rescales a number, like a 0 to 1023 reading into 0 to 255. The formula, integer math, constrain() and examples.

map() rescales a number from one range to another: map(value, fromLow, fromHigh, toLow, toHigh) returns where value would sit in the new range, so map(analogRead(A0), 0, 1023, 0, 255) turns a sensor reading into an LED brightness. It uses whole-number math and does not clamp, so it drops any fraction and can return a number outside the new range when the input is outside the old one.

You'll reach for it every time one part of a project speaks in one range and another part in a different one: sensor readings (0 to 1023) into brightness (0 to 255), percentages (0 to 100), angles (0 to 180) or musical pitches.

Syntax

long map(long value, long fromLow, long fromHigh, long toLow, long toHigh);

| Argument | What it is | |----------|------------| | value | The number to convert, usually a reading | | fromLow, fromHigh | The range it comes from, e.g. 0 and 1023 | | toLow, toHigh | The range you want, e.g. 0 and 255 |

It returns a long. Storing the result in an int is fine as long as it fits between -32,768 and 32,767, the range of an int on the HERO Board.

The Formula Behind It

map() is one line of math:

(value - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow

Worked through for map(512, 0, 1023, 0, 255): 512 × 255 ÷ 1023 = 127.6, and map() returns 127. The decimal is cut off, not rounded. That's integer division, and it's why map() never returns a fraction.

map() does this math in 32-bit long numbers, so the multiplication can't overflow. Write the same formula yourself with int and it breaks: 1023 × 255 is 260,865, far past the int limit, and in our test raw * 255 / 1023 with raw = 1023 printed -1 instead of 255.

Common Conversions

| You have | Code | You get | |----------|------|---------| | A reading for analogWrite() | map(x, 0, 1023, 0, 255) | 0 to 255 | | A reading as a percentage | map(x, 0, 1023, 0, 100) | 0 to 100 | | A reading as a servo angle | map(x, 0, 1023, 0, 180) | 0 to 180 | | A reading as a pitch for tone() | map(x, 0, 1023, 120, 1500) | 120 to 1500 Hz | | A reversed scale | map(x, 0, 1023, 255, 0) | 255 when x is 0 | | Your sensor's real range | constrain(map(x, 200, 800, 0, 100), 0, 100) | 0 to 100 |

Example 1: Light to LED Brightness, Reversed

A photoresistor divider on A0 (5V to the photoresistor, its other leg to A0 and to a 10 kΩ resistor, the resistor to GND) and an LED on PWM pin 9:

// Automatic night light: the darker the room, the brighter the LED on pin 9.
const int SENSOR_PIN = A0;   // the photoresistor and the 10k resistor meet here
const int LED_PIN = 9;       // a PWM pin (~)

void setup() {
  pinMode(LED_PIN, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int light = analogRead(SENSOR_PIN);             // 0 (dark) to 1023 (bright)
  int brightness = map(light, 0, 1023, 255, 0);   // flipped: dark room, bright LED
  analogWrite(LED_PIN, brightness);
  Serial.println(brightness);
  delay(50);
}

Listing the target range "backwards", 255 to 0, flips the scale: a dark room (a low reading) gives a high brightness. Either range may run high to low, and negative numbers work too: map(512, 0, 1023, -20, 20) returns 0, the middle.

Example 2: Calibrate to the Room

Fixed ranges like 0 to 1023 waste most of the scale, because a sensor in a real room never uses all of it. The 30 Days Lost in Space Day 6 lesson solves that by remembering the darkest and brightest readings it has seen and mapping into that range. Here is its sketch, shortened:

// Blink faster in brighter light, shortened from the 30 Days Day 6 lesson.
// The sketch learns the darkest and brightest readings it has seen, then
// maps the current reading into that range.
const byte PHOTORESISTOR_PIN = A0;
const unsigned int MIN_DELAY = 50;    // fastest blink, in ms
const unsigned int MAX_DELAY = 500;   // slowest blink, in ms

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);       // the LED on pin 13
  Serial.begin(9600);
}

void loop() {
  unsigned int light_value = analogRead(PHOTORESISTOR_PIN);

  static unsigned int darkest_light = light_value;     // remembered between loops
  static unsigned int brightest_light = light_value;
  if (light_value < darkest_light) darkest_light = light_value;
  if (light_value > brightest_light) brightest_light = light_value;

  // Dark maps to the slowest blink, bright to the fastest: a reversed range.
  unsigned int delay_value = map(light_value, darkest_light, brightest_light, MAX_DELAY, MIN_DELAY);

  Serial.print("Light: ");
  Serial.print(light_value);
  Serial.print("  Delay: ");
  Serial.println(delay_value);

  digitalWrite(LED_BUILTIN, HIGH);
  delay(delay_value);
  digitalWrite(LED_BUILTIN, LOW);
  delay(delay_value);
}

The static variables keep their values from one pass of loop() to the next, so the range widens as you cover the sensor and shine a light on it. The output range is reversed (MAX_DELAY to MIN_DELAY), so more light means a shorter delay and faster blinking.

Watch the very first pass: darkest and brightest are the same number, so map() divides by zero. In our test that first delay came out as 499, a meaningless value that does no harm here because the next readings widen the range. In your own code, skip the map() until the range has some width.

Example 3: A Light Theremin

Map light to pitch and you have an instrument. Keep the photoresistor divider on A0 and add a passive buzzer from pin 8 to GND:

// Light theremin: more light, a higher note. Wave a hand over the sensor to play it.
const int SENSOR_PIN = A0;   // photoresistor and 10k resistor: more light, a higher reading
const int BUZZER_PIN = 8;    // passive buzzer, other leg to GND

void setup() {
  Serial.begin(9600);
}

void loop() {
  int light = analogRead(SENSOR_PIN);              // 0 to 1023
  int pitch = map(light, 0, 1023, 120, 1500);      // becomes 120 to 1500 Hz
  tone(BUZZER_PIN, pitch);
  Serial.println(pitch);
  delay(20);
}

Cover the sensor and the note drops; shine a light on it and it climbs. In our simulator a covered sensor (a reading of 14) played 138 Hz, and bright light (853) played about 1,275 Hz. The tone() guide covers the buzzer side.

Keep the Result in Range with constrain()

map() happily extrapolates. In our test map(1100, 0, 1023, 0, 255) returned 274, too big for analogWrite(). It happens most with calibrated ranges: if your sensor reads 200 to 800 in your room, map(x, 200, 800, 0, 100) gives -33 at a reading of 0 and 137 at 1023. Wrap it:

int percent = constrain(map(x, 200, 800, 0, 100), 0, 100);   // never below 0 or above 100

The constrain() guide has more.

Why map(x, 0, 1023, 0, 3) Almost Never Returns 3

Because the fraction is cut off, the top value only appears at the very top of the input. We ran every reading through it: 0 to 340 give 0, 341 to 681 give 1, 682 to 1022 give 2, and only 1023 exactly gives 3. If you want four equal zones, map one past each end:

int zone = map(x, 0, 1024, 0, 4);   // 0-255 gives 0, 256-511 gives 1, 512-767 gives 2, 768-1023 gives 3

The same effect makes map(x, 0, 1023, 0, 255) reach 255 only at 1023. For a straight 10-bit to 8-bit conversion, x / 4 gives perfectly even steps.

When You Need Decimals

map() can't return 2.5. Write a float version; it's the same formula with float everywhere:

float mapFloat(float x, float inMin, float inMax, float outMin, float outMax) {
  return (x - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
}

float volts = mapFloat(analogRead(A0), 0, 1023, 0.0, 5.0);   // 0.00 to 5.00

The full sketch is under Code Examples at the bottom of this page.

Common Mistakes

  1. Expecting decimals. map() returns whole numbers and cuts off the fraction. Use mapFloat() above when you need 2.47.
  2. Expecting it to clamp. Inputs outside the from-range give outputs outside the to-range. Add constrain().
  3. An empty input range. If fromLow equals fromHigh, map() divides by zero. There's no error message; you get a nonsense number (on the HERO Board, map(5, 5, 5, 0, 100) returned -1 in our test).
  4. Arguments in the wrong order. The value comes first, then the old range, then the new one. map(0, 1023, 0, 255, reading) compiles and returns garbage.
  5. Rewriting the formula with int. If you do the math yourself, cast to long first: (long)raw * 255 / 1023.

Frequently Asked Questions

Does map() return a float?

No. It returns a long and drops the fraction: map(512, 0, 1023, 0, 255) is 127, not 127.6. For decimals, write a mapFloat() function like the one above.

Does map() keep the result inside the new range?

No. A value outside the input range produces a value outside the output range, so map(1100, 0, 1023, 0, 255) returns 274. Wrap the call in constrain() when the input can stray.

Can map() reverse a range or use negative numbers?

Yes to both. map(x, 0, 1023, 255, 0) counts down as x goes up, and map(x, 0, 1023, -100, 100) gives negative results for the lower half of the readings.

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

map() converts a number from one scale to another; constrain() only clips a number to limits without changing its scale. They're often used together: map first, then constrain.

Is map(x, 0, 1023, 0, 255) the same as x / 4?

Nearly. x / 4 splits 0 to 1023 into 256 equal steps. map() gives very slightly uneven steps and only reaches 255 at a reading of exactly 1023. For an LED you won't see the difference.