當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Arduino constrain()用法及代碼示例

[數學]

說明

將數字限製在一個範圍內。

用法

constrain(x, a, b)

參數

x:限製數量允許的數據類型:所有數據類型。
a: 範圍的下限。允許的數據類型:所有數據類型。
b: 範圍的上限。允許的數據類型:所有數據類型。

返回

x:如果 x 在 a 和 b 之間。
a:如果 x 小於 a。
b:如果 x 大於 b。

示例代碼

該代碼將傳感器值限製在 10 到 150 之間。

sensVal = constrain(sensVal, 10, 150);  // limits range of sensor values to between 10 and 150

注意事項和警告

由於constrain()函數的實現方式,請避免使用括號內的其他函數,可能會導致結果不正確。

此代碼將產生不正確的結果:

int constrainedInput = constrain(Serial.parseInt(), minimumValue, maximumValue);   // avoid this

改用這個:

int input = Serial.parseInt();  // keep other operations outside the constrain function
int constrainedInput = constrain(input, minimumValue, maximumValue);

相關用法


注:本文由純淨天空篩選整理自arduino.cc大神的英文原創作品 constrain()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。