constrain()
Description
Constraints a number to be within a range. The input of this function could be, for example, a sensor value that controls a motor position, with the lower and upper ranges of the function being the physical limits of possible movement.
Syntax
Use the following function to constrain the range of a given variable:
constrain(x, a, b)
Parameters
The function admits the following parameters:
: the number to constrain. Allowed data types: all data types.x
: the lower end of the range. Allowed data types: all data types.a
: the upper end of the range. Allowed data types: all data types.b
Returns
The function returns the following:
: if the input parameter (x) is betweenx
anda
.b
: if the input parameter (x) is less thana
.a
: if the input parameter (x) is greater thanb
.b
Example Code
The code sets an emulated sensor value and prints its constrained result on the Serial Monitor.
1int sensVal = 50; // try with 170 and 5 to verify the functionality2
3void setup() {4 Serial.begin(9600);5
6 sensVal = constrain(sensVal, 10, 150); // limits range of sensor values between 10 and 1507
8 Serial.print("The sensor value is: ");9 Serial.println(sensVal);10}11
12void loop() {13}
Notes and Warnings
Because of the way the
constrain()
function is implemented, avoid using other functions inside the brackets, it may lead to incorrect results.This code will yield incorrect results:
1int constrainedInput = constrain(Serial.parseInt(), minimumValue, maximumValue); // avoid this
Use this instead:
1int input = Serial.parseInt(); // keep other operations outside the constrain function2int constrainedInput = constrain(input, minimumValue, maximumValue);
See also
Suggest changes
The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.
License
The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.