Currently, I have a code that relies on the concept of having to use either an increment or decrement for the for loop depending on a certain condition. Example would be two tact switches for Arduino. One would trigger the positive increment and the other for the negative increment.
int inc; //Increment that is +1 or -1
int limit; //Minimum value for decrement and maximum value for increment
void loop() {
if(CONDITION) { //Condition for positive increment
i = 1;
limit = 15;
for(int i = 0; i <= limit; i = i + inc) {
//Statements
}
} else { //Condition for negative increment
i = -1;
limit = 0;
for(int i = 0; i >= limit; i = i + inc) {
//Statements
}
}
}
I want to make a uniform code for both situations where you just change a parameter, such as the variable. Now I have no problem with changing the increment. Just set a variable that becomes positive or negative 1. The same goes for the minimum and maximum values. My problem is the comparison operator.
Now I've done some searching myself but can't quite understand how to apply what I've read for this situation I've mentioned here. I will reference the links here.
Is there a way to make a comparison operator a variable?
Are Variable Operators Possible?
My big issue is none of the content in those links as far as from what I can recall have applied a comparison operator inside a loop such as for. Is there a way to create a variable operator of sorts for the situation I have stated? My goal is to be able to remove the for statements inside the if else conditions I have created and move it outside. I would instead put inside the if else conditions the code that would allow me to set the comparison operators <= and >=. Here is an idea of what I would want it to look like.
int inc; //Increment that is +1 or -1
int limit; //Minimum value for decrement and maximum value for increment
void loop() {
if(CONDITION) { //Condition for positive increment
i = 1;
limit = 15;
/*
(Code to make the operator <=)
Wrong code technically but the concept would be
VariableOperator = <=
*/
} else { //Condition for negative increment
i = -1;
limit = 0;
/*
(Code to make the operator >=)
Wrong code technically but the concept would be
VariableOperator = >=
*/
}
for(int i = 0; /* i VariableOperator limit */; i = i + inc) {
//Statements
}
}
Though this is just a concept because I have no idea on how it would work. The code would probably be different. I really don't have an idea.