After a recent thread dealing with comparing values against a range, at least a once-a-week issue here, I decided to try my hand at writing a function to simplify the process. I decided on a template form so that different types of numeric values could be compared – like against like.
The end game is to put this in library form to cut the effort to an #include but Win7pro isn’t cooperating.
In the meantime I’d appreciate any comments or observations on this effort.
/*
ARDUINO LIMIT INSTRUCTION
A C++ template with two modes to compare a
numeric argument against two like values.
mode a. If low limit value is less than or
equal to high limit value, logic true is returned
if argument is equal to or between the limits.
False is returned otherwise.
given: a = 3, b = 6, c = 9:
example ( a <= b <= c ) returns true, returns false if b = 11
mode b. Low limit is greater than high limit - if argument is
between both limits a logic false is returned - true is
returned otherwise.
given: a = 8, b = 6, c = 4
example - ( b < a and b > c ) returns false,
*/
template <class T> bool limitTest (T lowLimit, T argument, T hiLimit) {
if (lowLimit <= hiLimit) {
if (lowLimit <= argument and argument <= hiLimit)
return true;
else return false;
}
else if ( argument < lowLimit and argument > hiLimit)
return false;
else return true;
}
void setup() {
Serial.begin(230400);
int lowlim = 3;
int hilim = 5;
Serial.println("LOW LIM LESS THAN OR EQUAL HILIM\n");
Serial.print("LOW ARG HI\n");
for (int i = 1 ; i < 7; i++) {
Serial.print(" ");
Serial.print(lowlim);
Serial.print(" <= ");
Serial.print(i);
Serial.print(" <= ");
Serial.print(hilim);
if (limitTest(lowlim, i, hilim)) Serial.println(" returns \ttrue");
else Serial.println(" returns false");
}
Serial.println();
lowlim = 5;
hilim = 3;
Serial.println("LOW LIM GREATER THAN HILIM\n");
Serial.print("LOW ARG HI\n");
for (int i = 1; i < 7; i++) {
Serial.print(" ");
Serial.print(lowlim);
Serial.print(" <= ");
Serial.print(i);
Serial.print(" <= ");
Serial.print(hilim);
if (limitTest(lowlim, i, hilim)) Serial.println(" returns \ttrue");
else Serial.println(" returns false");
}
Serial.println();
lowlim = 5;
hilim = 5;
Serial.println("LOW LIM EQUAL HILIM\n");
Serial.print("LOW ARG HI\n");
for (int i = 3; i < 8; i++) {
Serial.print(" ");
Serial.print(lowlim);
Serial.print(" <= ");
Serial.print(i);
Serial.print(" <= ");
Serial.print(hilim);
if (limitTest(lowlim, i, hilim)) Serial.println(" returns \ttrue");
else Serial.println(" returns false");
}
Serial.println();
}
void loop() {
// put your main code here, to run repeatedly:
}