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:

  • x
    : the number to constrain. Allowed data types: all data types.
  • a
    : the lower end of the range. Allowed data types: all data types.
  • b
    : the upper end of the range. Allowed data types: all data types.

Returns

The function returns the following:

  • x
    : if the input parameter (x) is between
    a
    and
    b
    .
  • a
    : if the input parameter (x) is less than
    a
    .
  • b
    : if the input parameter (x) is greater than
    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 functionality
2
3void setup() {
4 Serial.begin(9600);
5
6 sensVal = constrain(sensVal, 10, 150); // limits range of sensor values between 10 and 150
7
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 function
2int 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.