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.
不會把值強制限制在范圍之內,因為超范圍的值經常也是有用的。如果需要的范圍做一限制。可以在這個函數之前或之后使用constrain() 函數。
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
注意,兩個范圍中的“下界”要比“上界”大或下,這樣map()可以用來反轉一個范圍,例如
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.
map()函數使用整型,所以不會產生分數,分數將會被截去,並不是全面的或平均值(?)
Parameters 參數
value: the number to map
給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
void setup() {}
void loop()
{
int val = analogRead(0); //讀取0口的值
val = map(val, 0, 1023, 0, 255);//從0-1023映射到0-255
analogWrite(9, val);//把映射后的值寫給9口
}
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;
}