aboutsummaryrefslogtreecommitdiffstats
path: root/source/arduino/map.rst
blob: 61aa6266a93a4be6c12216f0e4b8c0b74f84e537 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
.. _arduino-map:

map(value, fromLow, fromHigh, toLow, toHigh)
============================================

Description
-----------

Re-maps a number from one range to another. That is, a **value** of
**fromLow** would get mapped to **toLow**, a value of **fromHigh**
to **toHigh**, values in-between to values in-between, etc.



Does not constrain values to within the range, because out-of-range
values are sometimes intended and useful. The constrain() function
may be used either before or after this function, if limits to the
ranges are desired.



Note that the "lower bounds" of either range may be larger or
smaller than the "upper bounds" so the map() function may be used
to reverse a range of numbers, for example



``y = map(x, 1, 50, 50, 1);``



The function also handles negative numbers well, so that this
example



``y = map(x, 1, 50, 50, -100);``



is also valid and works well.



The map() function uses integer math so will not generate
fractions, when the math might indicate that it should do so.
Fractional remainders are truncated, and are not rounded or
averaged.



Parameters
----------

value: the number to map



fromLow: the lower bound of the value's current range



fromHigh: the upper bound of the value's current range



toLow: the lower bound of the value's target range



toHigh: the upper bound of the value's target range



Returns
-------

The mapped value.



Example
-------

::

    /* Map an analog value to 8 bits (0 to 255) */
    void setup() {}
    
    void loop()
    {
      int val = analogRead(0);
      val = map(val, 0, 1023, 0, 255);
      analogWrite(9, val);
    }



Appendix
~~~~~~~~

For the mathematically inclined, here's the whole function



::

    long map(long x, long in_min, long in_max, long out_min, long out_max)
    {
      return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
    }



See Also
--------


-  `constrain <http://arduino.cc/en/Reference/Constrain>`_\ ()


.. include:: cc-attribution.txt