Constrain() doesn't work

I used these code in my program:

       case btnUP:
         {
         cursorCoordinateY--;
         constrain(cursorCoordinateY, 0, 1);

while, I got "cursorCoordinateY = -1" in Serial Monitor, and the cursor location on LCD1602 is "-1", not "0", what maybe the reason?

https://www.arduino.cc/reference/en/language/functions/math/constrain/

It is only a snippet so how the variable is defined and how you printed it is not clear. However, constrain() is defined like this and it is difficult to see what goes wrong in your specific case:

#define constrain(amt,low,high) ((amt)<(low)?(low):((amt)>(high)?(high):(amt)))

Hi,
Look at this code and run it, the IDE monitor needs to be set to 115200.

int val1 = 0;
int val2 = 0;
void setup() {
  Serial.begin(115200);

}

void loop() {
  val1 = val1 + 1;
  val2 = constrain (val1, 5, 10);
  Serial.print(" val1 = ");
  Serial.print(val1);
  Serial.print(" constrained val2 = ");
  Serial.println(val2);
  if (val1 > 15)
  {
    val1 = 0;
  }

  delay (500);
}

Tom... :grinning: :+1: :coffee: :australia:

Constrain does not modify your variable, it just gives the result of constraining that variable.

Try with

cursorCoordinateY = constrain(cursorCoordinateY, 0, 1);