Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 10

Mapping and

the map() function


Moving numbers from one range
to another in proportion
Spoiler Alert:
It’s just math.
It sets a proportion.
Proportion 3 x
A ratio.
-- = -- 3 (10) = 5x

A fraction.
5 10

x=6
The concept of mapping: connect two number lines
Input Range Output Range
1023 maps to 255
1023

512 maps to 128


255
0 maps to 0

512 128

0
A realistic example 145 x
An analogRead() function call gives
------- = ----
you a value in the range of 0-1023 - 1023 255
You want to convert that to the range
of 0-255

First, let’s use a concrete value such


as 145 x = 36
In code, you won’t
know the value …
it’s read in real
time

Read voltage input from A0


inputValue=analogRead(A0);
A numeric integer value (0-1023)
gets assigned to the inputValue
Variable outputValue=(inputValue+255)/1023;
Math occurs

The result of the math expression is assigned to


the outputValue variable
The same, BEFORE:
with the map()
inputValue=analogRead(A0);
function
Take the ORIGINAL VALUE outputValue=(inputValue+255)/1023;

Convert FROM this range AFTER:

Convert TO this range inputValue=analogRead(A0);

outputValue=map(inputValue,0,1023,0,255);
The map() function returns an integer value to be
assigned to the outputValue variable.
Especially useful when you don’t always start at 0
Analog input is in the 0-1023 range

Our Servos operate from about 16


degrees to 180 degrees. servoAngle=map( inputValue, ???, ???, ???, ??? );

(0-15 are “slow motion” angles and


don’t work like the rest - trust me on
this one)

servoAngle=map( inputValue, 0, 1023, 16, 180 );


The same graphic for a more complex mapping:
16 to 180 Input Range Output Range
1023 maps to 180
1023

512 maps to 98
180
0 maps to 16

512 98

16

0
In conclusion: the map() function
Syntax:

map( original_value, orig_low, orig_high, new_low, new_high );

Example (return value assigned to int variable):

x = map( value, 0, 1023, 0, 255 );

You might also like