0
0
Power-electronicsDebug / FixBeginner · 4 min read

How to Avoid Floating Point in Embedded C: Simple Fixes

To avoid floating point in embedded C, replace floating point variables and operations with integer or fixed-point arithmetic. This reduces code size and improves speed on microcontrollers without floating point units.
🔍

Why This Happens

Embedded systems often lack hardware support for floating point math, so using float or double causes slow software emulation. This leads to larger code size and slower execution, which is bad for resource-limited devices.

c
#include <stdio.h>

int main() {
    float voltage = 3.3f;
    float current = 0.02f;
    float power = voltage * current;
    printf("Power: %f W\n", power);
    return 0;
}
Output
Power: 0.066000 W
🔧

The Fix

Use integer math by scaling values to avoid decimals. For example, multiply values by 1000 and store as integers. Then do math with integers and scale back when displaying results.

c
#include <stdio.h>

int main() {
    int voltage_mV = 3300;  // 3.3 V scaled by 1000
    int current_mA = 20;    // 0.02 A scaled by 1000
    int power_uW = (voltage_mV * current_mA) / 1000;  // power in microwatts
    printf("Power: %d uW\n", power_uW);
    return 0;
}
Output
Power: 66000 uW
🛡️

Prevention

To avoid floating point issues in embedded C:

  • Use fixed-point arithmetic by scaling values to integers.
  • Define constants and variables as integers representing scaled values.
  • Use integer math operations instead of floating point.
  • Enable compiler warnings for floating point usage.
  • Use static analysis or linters to detect floating point usage early.
⚠️

Related Errors

Common related errors include:

  • Slow execution: Floating point math slows down microcontrollers without FPU.
  • Large binary size: Floating point libraries increase code size.
  • Precision loss: Improper scaling can cause rounding errors.

Fixes involve using integer math and careful scaling.

Key Takeaways

Replace floating point with scaled integer math to improve speed and reduce code size.
Scale values to fixed-point representation before calculations.
Use compiler warnings and static analysis to catch floating point usage early.
Test carefully to avoid precision loss when scaling integers.
Embedded systems often lack hardware floating point support, so avoid floats for efficiency.