How To Cap A Variable?

So I’m using a counting integer to set the position of a servo. The problem is once the variable gets to big the servo shoots back to the 0 position. Does anyone know how to set a range for a variable or set a min/max for it?

Use an if/else, if you want a min of say 20 and a max of 100, do something like if 20<value && value<100 then variable = whatever the value is, then else if 20>value then variable =20 and else variable =100. I’m not an expert on servos but I am a coder and that general setup works for mins and maxes

The way my program is set up wouldn’t work like that. I just need to know if there is like a command that restricts the integer from passing a certain value. Appreciate the suggestion though!

Make a “command” by making a function called “min” that accepts 2 ints as parameters, and returns the smaller one. Every time you want to update the variable, call the min function with the new value and the cap as parameters.

Below is a function that my teams use. It works well with motors because the value can be either positive or negative.


int Max(int value, int maxValue){
	return (abs(value) <= abs(maxValue)) ? value :
	    (value > 0) ? maxValue : -maxValue;
}

//Example usage
		int x = Max(100,50);  //Returns  50
		int y = Max(-100,50); //Returns -50 (because the first value is negative)
		int z = Max(40,50);   //Returns  40
		int k = Max(-40,50);  //Returns -40
                int motor1 = Max(controlVal, 127);  //limits the top speed to 127 regardless of direction

Edit: Typo

So long as you are looping through the code, a simple if statement should do the trick. Maybe post the relevant code here?

if(abs(var) > max)
{
var = max * sgn(var)
}

Ideally you’d encapsulate a variable and never allow directly setting it so you can maintain the constraint.

Nice use of the


sgn

function. Time to refactor.


int Max(int value, int maxValue){
	return (abs(value) <= maxValue) ? value : maxValue * sgn(value);
}