Today I pushed my Troolean = tristate class to
github: Arduino/libraries/Troolean at master · RobTillaart/Arduino · GitHub
I needed this tri-state functionality in an experiment and extended it a bit to be “complete” and possibly usable for the community.
Booleans can have the value true or false. Booleans support operators like AND OR XOR == != to make larger expressions. However sometimes a boolean cannot hold the state you want.
Imagine that you read a sensor and you have a boolean to show it is working.
reading ==> working = true;
no reading ==> working = false;
But suppose the reading is done, and the value returned seems to be way off
(e.g. drop in temperature of 30° in < minute ).
Although you have a reading, you are quite sure it is not a good on.
So it is in a sort of twilight, it is not true but it is also not false.
This is where Trooleans come in. A Troolean can have three states, true, false and unknown. This third state allows you to keep sort of state if it is not known.
The Troolean class has the same operators as boolean have, AND OR XOR == !=
If all Trooleans in an expression have boolean values (true or false), the expression behaves boolean. If one of the Trooleans are unknown the following rules apply.
true && unknown ==> unknown false && unknown ==> false true || unknown ==> true false || unknown ==> unknown !unknown ==> unknown
The Troolean class also has == and != which behave as one expect. For completeness there are overloads to compare Trooleans with booleans and with ints. As Troolean class implements unknown with -1, the comparison with ints should be used with care as it differs from thebehavior of boolean comparisons.
The class implements isTrue(), isFalse() and isUnknown() to check the state. The Troolean class also implements Printable, so one can use a Troolean in e.g. Serial.println( trool );
Finally there are two example sketches that do (1) check the behavior of all operators of the class and (2) show how to use the Trooleans in an array.
As always remarks, improvements, comments and usecases are welcome