Sub topic 9
Scaling readings with map()
This chapter assumes you can write a basic sketch with setup() and loop(). It also assumes you have wired a potentiometer to A0 and can read it with analogRead() on an Uno-class board (10-bit ADC, 0 to 1023). You should know how to open the Serial Monitor.
Why raw readings need scaling
analogRead() returns a number from 0 to 1023. Most things you want to control do not use that range. Some examples:
analogWrite()accepts 0 to 255.Servo.write()accepts 0 to 180 degrees.- A volume display might use 0 to 100 percent.
- A temperature setpoint might use 15 to 30 degrees Celsius.
Scaling means converting a value from one range to another so that the ends line up and the points in between keep their proportions. Arduino provides map() for this.
The map() function
The signature is:
map(value, fromLow, fromHigh, toLow, toHigh)It returns a long. Internally it computes a linear interpolation using integer arithmetic:
(value - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLowTake map(512, 0, 1023, 0, 255):
512 - 0 = 512512 * 255 = 130560130560 / 1023 = 127(integer division drops the fraction)127 + 0 = 127
The result is 127, not 127.6. This matters in the edge cases below.
Dimming an LED with a potentiometer
This sketch maps the reading onto the 0 to 255 range of analogWrite(). It assumes an LED with a series resistor on pin 9, which is a PWM pin on an Uno.
const int POT_PIN = A0;
const int LED_PIN = 9;
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
int raw = analogRead(POT_PIN);
int brightness = map(raw, 0, 1023, 0, 255);
analogWrite(LED_PIN, brightness);
}Turning the knob from one end to the other moves the brightness from fully off to fully on. analogWrite() produces a PWM signal, a fast on-off pattern whose average level sets the perceived brightness. The next chapter covers PWM in more detail.
The diagram shows the data flow.
Mapping to ranges that are not zero-based
The target range can start anywhere. To turn the knob into a servo angle from 0 to 180 degrees:
int angle = map(analogRead(A0), 0, 1023, 0, 180);To get a setpoint between 15 and 30:
int setpoint = map(analogRead(A0), 0, 1023, 15, 30);Reversing a range
map() does not require toLow to be smaller than toHigh. Swap them to invert the direction:
int inverted = map(raw, 0, 1023, 255, 0);Now a reading of 0 gives 255 and a reading of 1023 gives 0. This is useful when the pot is wired so that turning clockwise lowers the reading and you want the opposite behavior. Swapping the outer pot terminals does the same job in hardware.
Edge cases and gotchas
map() does not constrain its output
If value falls outside fromLow to fromHigh, the output falls outside toLow to toHigh. Values from analogRead() stay within 0 to 1023, so this is safe there. It becomes a problem when you narrow the input range, for example to cut off dead zones at the ends of a worn pot:
int level = map(raw, 50, 970, 0, 255);A raw reading of 20 now gives a negative result, and analogWrite() receives a bad value. Wrap the result in constrain():
int level = constrain(map(raw, 50, 970, 0, 255), 0, 255);Integer division loses fractions
map() only works with integers. If you map to a small range, many input values collapse onto the same output. Mapping 0 to 1023 onto 0 to 10 gives 11 possible outputs, so about 93 input values share each output. Also, the top output value is reached only when the input is exactly fromHigh, so the last step is much narrower than the others. With map(raw, 0, 1023, 0, 10), only a reading of 1023 gives 10. The output 9 covers roughly 93 readings, and the output 10 covers one.
If you need an even split into buckets, scale to one more than the count and constrain. This gives 10 equal buckets numbered 0 to 9:
int bucket = constrain(raw / 103, 0, 9);Here 1024 divided by 10 is about 102.4, and 103 is rounded up so the last bucket is not larger than the rest.
Mapping to fractional values
To get a result such as 0.0 to 5.0 volts, do not use map(). Use floating-point arithmetic:
float volts = raw * (5.0 / 1023.0);A common trick is to map to a larger integer range, such as 0 to 500, and divide by 100.0. Direct floating-point math is clearer and more accurate.
Overflow with large ranges
On AVR boards such as the Uno, int is 16 bits and holds values up to 32767. map() uses long (32 bits) internally, so the intermediate product is safe for typical ranges. The risk appears when you store the result in an int and the target range exceeds 32767. Use long for the result variable in that case.
The output is a long
Assigning the result to int is fine for small ranges. Passing it to Serial.print() also works. Be aware of the type when you do arithmetic with other variables.
Printing raw and mapped values together
Print both values to see how they relate:
const int POT_PIN = A0;
void setup() {
Serial.begin(9600);
}
void loop() {
int raw = analogRead(POT_PIN);
int mapped = map(raw, 0, 1023, 0, 255);
Serial.print("raw=");
Serial.print(raw);
Serial.print(" mapped=");
Serial.println(mapped);
delay(100);
}Turn the knob slowly. You will see mapped increase by one roughly every four steps of raw, because 1023 divided by 255 is about 4. That is the resolution lost when you scale down. Scaling up does the opposite: mapping 0 to 1023 onto 0 to 10000 skips values, and the output moves in jumps of about 10.
Choosing between map() and other approaches
| Need | Approach |
|---|---|
| Integer range to integer range | `map()` |
| Result must stay inside the target range | `constrain(map(...), low, high)` |
| Fractional output such as volts | Floating-point multiplication |
| Equal-sized buckets | Integer division with `constrain()` |
| Power-of-two scale such as 0 to 1023 to 0 to 255 | `raw >> 2`, which is fast but fixed |
For the LED example, raw / 4 and map(raw, 0, 1023, 0, 255) give nearly the same result. map() is easier to read and adapts when you change the ranges, so it is usually the better choice unless speed matters.
Boards with a different resolution
The fromHigh value of 1023 assumes a 10-bit ADC. Some boards default to a different resolution or let you change it, and a hard-coded 1023 gives wrong results there. The last chapter covers board differences. For now, keep the maximum in a constant so you can change it in one place:
const int ADC_MAX = 1023;
int brightness = map(analogRead(A0), 0, ADC_MAX, 0, 255);Summary of rules
map()scales linearly using integer math and truncates toward zero.- It does not clamp its output, so use
constrain()when the input can leave the stated range. - Reverse the output range by swapping
toLowandtoHigh. - Use floating-point math when you need fractions.
- Scaling down loses resolution, and scaling up creates gaps.
Exercise
A potentiometer reads between 0 and 1023. You call map(raw, 0, 1023, 0, 100) and raw is 700. What does it return, and why? Then write the call that makes a servo angle go from 180 down to 0 as raw goes from 0 to 1023.
Show answer
It returns 68. The computation is 700 * 100 / 1023 = 70000 / 1023 = 68.4, and integer division drops the fraction, so the result is 68. For the reversed servo angle, swap the output limits: map(raw, 0, 1023, 180, 0).
Exercise
A worn potentiometer only reports raw values from 40 to 980. You use map(raw, 40, 980, 0, 255) and pass the result to analogWrite(). What goes wrong when raw is 10, and how do you fix it?
Show answer
map() does not clamp, so raw = 10 gives a negative result of about -8, which is outside the valid 0 to 255 range for analogWrite(). Wrap the call: constrain(map(raw, 40, 980, 0, 255), 0, 255).