|
| 1 | +/* |
| 2 | + * FixMath Library - Example demonstrating that FixMath internally keeps track of |
| 3 | + * the range used by a number to avoid promoting too easily |
| 4 | + * |
| 5 | + * This example code is in the public domain CONTRARY TO THE LIBRARY itself, |
| 6 | + * which is licensed the GNU Lesser General Public Licence |
| 7 | + * |
| 8 | + */ |
| 9 | + |
| 10 | +#include <FixMath.h> |
| 11 | + |
| 12 | +const uint8_t a = 200, b = 150, c = 205, d = 130; |
| 13 | +auto aF = toUInt(a); // This automatically makes a UFix<8,0> because a is an 8bits type |
| 14 | +auto bF = toUInt(b), cF = toUInt(c), dF = toUInt(d); |
| 15 | + |
| 16 | + |
| 17 | +void setup() { |
| 18 | + Serial.begin(9600); |
| 19 | +} |
| 20 | + |
| 21 | +void loop() { |
| 22 | + Serial.print("aF is of type: UFix<"); |
| 23 | + Serial.print(aF.getNI()); |
| 24 | + Serial.print(","); |
| 25 | + Serial.print(aF.getNF()); |
| 26 | + Serial.println(">"); |
| 27 | + |
| 28 | + |
| 29 | + /* |
| 30 | +Promotion is needed to be sure that the result |
| 31 | +does not overflow. The sum has the potential |
| 32 | +to fill completely a UFix<9,0> |
| 33 | +*/ |
| 34 | + Serial.print("aF+bF is of type: UFix<"); |
| 35 | + Serial.print((aF + bF).getNI()); |
| 36 | + Serial.print(","); |
| 37 | + Serial.print((aF + bF).getNF()); |
| 38 | + Serial.println(">"); |
| 39 | + |
| 40 | + /* |
| 41 | +Promotion is needed to be sure that the result |
| 42 | +does not overflow. The sum does not fill completely |
| 43 | +a UFix<10,0>. There is still room for a UFix<8,0> |
| 44 | +because 256*3=768 and the maximum a UFix<10,0> can |
| 45 | +hold is 1023. |
| 46 | +*/ |
| 47 | + Serial.print("aF+bF+cF is of type: UFix<"); |
| 48 | + Serial.print((aF + bF + cF).getNI()); |
| 49 | + Serial.print(","); |
| 50 | + Serial.print((aF + bF + cF).getNF()); |
| 51 | + Serial.println(">"); |
| 52 | + |
| 53 | + |
| 54 | + /* |
| 55 | +As the sum can hold another UFix<8,0>, |
| 56 | +FixMath does not promote here and |
| 57 | +aF+bF+cF has the same type than |
| 58 | +aF+bF+cF+dF. |
| 59 | +*/ |
| 60 | + Serial.print("aF+bF+cF+dF is of type: UFix<"); |
| 61 | + Serial.print((aF + bF + cF + dF).getNI()); |
| 62 | + Serial.print(","); |
| 63 | + Serial.print((aF + bF + cF + dF).getNF()); |
| 64 | + Serial.println(">"); |
| 65 | + |
| 66 | + Serial.println(); |
| 67 | + |
| 68 | + |
| 69 | + |
| 70 | + |
| 71 | + delay(1000); |
| 72 | +} |
0 commit comments