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.

int sensVal = 50;  // try with 170 and 5 to verify the functionality

void setup() {
  Serial.begin(9600);

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

  Serial.print("The sensor value is: ");
  Serial.println(sensVal);
}

void loop() {
}

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:

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

Use this instead:

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

See also