map(value, fromLow, fromHigh, toLow, toHigh)
描述
將某個範圍內的一個數值重新映射到另一個範圍,亦即數值 fromLow 被映射到數值 toLow 去,而數值 fromHigh 則被映射到數值 toHigh, value 則維持與 fromLow、fromHigh 的比例關係映射至新的範圍。
value 不一定是在範圍內的數值,因為有時候超出範圍的數值可能會有其他用處;如果希望數值限制在預期的範圍內,可在該函式的前後使用函式 constrain()。
任一範圍的下限是可以高於或低於範圍的上限的,所以 map() 函式也可以用來反轉一個範圍內的數值,例如:
y = map(x, 1, 50, 50, 1);
這個函式也可以處理負數,例如以下範例:
y = map(x, 1, 50, 50, -100);
函式一樣有效而且可以運作得很好。
map() 函式使用整數運算,所以不會有小數點,小數的部分會被捨去,而不是採用四捨五入做進位。
參數
value: 被映射的數字
fromLow: value 原本的範圍下限
fromHigh: value 原本的範圍上限
toLow: 要映射的目標範圍下限
toHigh: 要映射的目標範圍上限
回傳
映射後的值
範例
/* 將一個讀出的類比數值映射到 8bit 的大小 (0 到 255) */
void setup() {}
void loop()
{
int val = analogRead(0);
val = map(val, 0, 1023, 0, 255);
analogWrite(9, val);
}
延伸
關於數學上的計算運作,這裡有一個完整的方程式:
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()
本頁由熱血青年 LBU 譯自英文版。
The text of the 86Duino reference is a modification of the Arduino reference, and is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.
