Electronic – Excessive AVR static RAM usage with mixed-type math operations

avravr-gccfloating pointmicrocontroller

I've narrowed down an issue in my code which creates an extra 260 bytes of static RAM usage:

BYTE Height = 150;

BYTE sampleLevel(BYTE ADCchan,BYTE averages)
{
    float samp;
    //int samp;
    BYTE level;

    samp = avgSampleADC(ADCchan,averages);
    level = 100-(samp*100/Height);

    return level;
}

BYTE here is a uint8_t type. If I comment out float samp and turn it into an int type, the static RAM usage goes back down to what I expect it to be. I suppose this has something to do with the math operation level = 100-(samp*100/Height); but I don't know what it is. What is happening to create such behavior?

Best Answer

For many mathematical functions there's a trade-off between RAM usage and speed. I guess the AVR floating-point library will be optimized for speed.
Bitrex is right: try to avoid floating-point in microcontrollers unless absolutely necessary. Do you really need floating-point, or will fixed-point do? You can emulate fixed-point by placing a virtual decimal point somewhere in an int.

In your example you multiply samp by \$\frac{2}{3}\$. The result, stored in a BYTE won't have a very high precision. In a case like that you can pick a scaling factor which is easier to calculate than the \$\frac{2}{3}\$. Find an approximation of the form \$\frac{A}{2^N}\$. In this case \$\frac{171}{256}\$ ~ 0.668 is a good choice, with an error of only 0.2%. And it's a lot easier to calculate: multiply by 171, and shift right 8 bits. No division needed.