Skip to main content

Subsection 12.5.8 Part 9: Floating Point

Recall yesterday’s conversion (Subsection 12.3.4): a = (ACC_FS * ACCEL_raw * MILLI) >> ACC_REGISTERWIDTH, the shift standing in for a divide by 2¹⁶. Because of the use of trigonometric functions such as atan2(), we’ll need to switch from exclusively using integers to temporarily working with real numbers. C’s type for them is float (single-precision floating point), 4 bytes, the same size as an int32_t. To use mathematical functions such as sin(), cos(), atan2(), round(), we’ll need to include the math library, and therefore #include <math.h> in our code. One more piece of C matters here: a cast applies only to the value written right after it, and it runs before * or /. So (float) 7 / 2 gives 3.5, while (float)(7 / 2) gives 3.0, because the division has already happened.

Activity 12.5.9. Place the cast.

(a)

When dividing integers in C, the division is performed in integer arithmetic: the remainder gets lost, and the result is just the integer part. The conversion ACCEL_raw * ACC_FS / 65536 divides that way unless something is done about it. Write the expression with a (float) cast placed so the result keeps its fraction.

(b)

As a review of how casting works in C: in your expression, what exactly does the (float) apply to, and when does it run relative to the * and the /?
Compute in float, but come back to integers to print. Recall from Day 5 that printf’s %f is not enabled in our projects (Subsection 3.2.2); the route is still convert-then-%d. The math library contains the function round(): double round(double x);. round() goes to the nearest integer value, whereas casting straight to an int truncates toward zero. round() returns a double, and you therefore need to cast its result for printing: (int)round(angle). This is how to display the calculated angles on your screen.
What does floating point cost? The 32 bits of a float consist of a sign bit, an 8-bit exponent, and a 23-bit fraction, so exactness is traded away for range; Section 12.6 lays the format out. The bigger cost is that computing with a float is fast on a processor that has an FPU (floating point unit), which is part of the processor hardware; the STM32C031C6 does not have a floating point unit, so every float operation is done in software. This is slower than integer arithmetic, and in addition, the library code takes up flash memory. In Lab 7 you are asked to measure exactly that, your program’s size with the math library in it.