Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 37 ยท Analog and PWM

map(), constrain() and Scaling Values

Convert ranges with Arduino's map(), clamp values with constrain(), understand integer rounding traps, handle floats with a custom function and calibrate sensor min and max.

Sensors speak in their own units: 0 to 1023 from an ADC, 0 to 255 for PWM, 0 to 180 degrees for a servo, 20 to 80 degrees Celsius from a thermistor calculation. Most sketches spend part of their life translating between those ranges. Arduino provides two small helpers, map() and constrain(), and this lesson shows what they really do, where they surprise people, and how to write better versions when you need them.

map()

C++
long result = map(value, fromLow, fromHigh, toLow, toHigh);

map() rescales value linearly from the input range to the output range. A pot reading of 0 to 1023 becomes a PWM value 0 to 255:

C++
int pot = analogRead(A0);
int brightness = map(pot, 0, 1023, 0, 255);
analogWrite(9, brightness);

The documented implementation is just one line of integer arithmetic:

TEXT
(value - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow
C Stand-in: Arduino's map() reimplemented

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Swapping the output range reverses the direction, a handy way to invert a sensor.

What map() does not do

  1. It does not clamp. If value is outside the input range, the output is outside the output range too. map(1500, 0, 1023, 0, 255) gives 373, which would wrap if passed to analogWrite().
  2. It uses integers. The division truncates toward zero, so small values collapse and results are slightly biased.
  3. The top step is lopsided. Mapping 0 to 1023 into 0 to 255, each output value covers about four input values, but the maximum 255 only appears at exactly 1023.
C Stand-in: map() does not clamp, and truncates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The last output value 255 is produced by only one reading (1023). When that precision matters, map 0..1024 to 0..256 and clamp, or use floating point.

constrain()

C++
x = constrain(x, low, high);

constrain() returns low if x < low, high if x > high, and otherwise x. Use it before sending a value to a function that has a valid range, and after map() to repair out-of-range inputs:

C++
int brightness = constrain(map(pot, 0, 1023, 0, 255), 0, 255);

Beware one Arduino gotcha: constrain(), min(), max() and abs() are macros that evaluate their arguments more than once. constrain(analogRead(A0), 0, 255) reads the pin up to three times, and constrain(x++, 0, 9) increments more than once. Assign to a variable first.

C Stand-in: clamp, and the double-evaluation trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Floating point and your own helpers

When you need fractions (temperature, voltage), write a floating-point mapper. Floats on an 8-bit chip are slow but fine at sensor speeds:

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

For a sensor whose output is 0.5 V at 0 ยฐC and 10 mV per degree, temperature = (reading * 5.0 / 1024.0 - 0.5) * 100.0; is clearer than a map call.

Calibrating min and max

A real sensor rarely spans the full 0 to 1023. A light sensor in your room might read 180 in the dark and 820 in bright light. Hard-coding those values drifts when conditions change. Auto-calibration records the lowest and highest readings during the first few seconds and uses them as the input range:

C Stand-in: auto-calibrate then scale

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Notice how the last two readings fall outside the calibrated range and are clamped. In a real sketch, call constrain() or keep updating lo and hi continuously.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does map(512, 0, 1023, 0, 255) return?

    512 * 255 / 1023 = 127.6, truncated to 127 by integer division.
  2. 2. map() is given a value outside the input range. What happens?

    map() is pure arithmetic; use constrain() if you need clamping.
  3. 3. Why can constrain(analogRead(A0), 0, 255) misbehave?

    Macro arguments are expanded multiple times; store the reading in a variable first.
  4. 4. Which is a good reason to calibrate sensor min and max?

    Calibration makes use of the sensor's actual range for better resolution.

Summary

  • map() rescales linearly with integer arithmetic; reverse the output range to invert.
  • It does not clamp and it truncates; follow it with constrain() when the range must hold.
  • constrain, min, max and abs are macros: never pass expressions with side effects.
  • Use a float helper when you need fractions.
  • Calibrate to the sensor's real range for better resolution.

Next: Smoothing and Filtering Noisy Readings