Arduino UNO calculations wrong

Hello,

I am trying to calculate a pressure value in Kpa from an automotive pressure sensor connected to an analog input via voltage divider.
Al is working very well, connected the sensor and started reading the analog value on every 100Kpa so I could create a decent calculation that converts my analog value to Kpa.
Strange thing is that my calculation works splendid in a spreadsheet or even in C on my i386 but is way off on the UNO
The C test code:

    int value[] = {66, 212, 323, 424, 515, 595, 666};

    int i = 0;
    for(i=0; i<7; i++)  {
        int result = 0.00067*(value[i]*value[i])+0.5*value[i]-33;
        printf("%d \n", result);
    }

In the arduino:

Value1=analogRead(inputVoltage1);
    press1=0.00067*(Value1*Value1)+0.5*Value1-33;

both Value1 and press1 are int.

Schermafbeelding 2012-08-21 om 18.56.24.PNG

        int result = 0.00067*(value[i]*value[i])+0.5*value[i]-33;

value[ i ] is an int. When you multiply that by value[ i ], the result is an int. For most of the values in the array, the result is not a valid int value.

japie:
Hello,

I am trying to calculate a pressure value in Kpa from an automotive pressure sensor connected to an analog input via voltage divider.
Al is working very well, connected the sensor and started reading the analog value on every 100Kpa so I could create a decent calculation that converts my analog value to Kpa.
Strange thing is that my calculation works splendid in a spreadsheet or even in C on my i386 but is way off on the UNO

Ints are 16-bits on the UNO (-32,768 to +32,767), while they are 32-bits on x86 systems (-2,147,483,648 to +2,147,483,647). If you multiply 666 by 666 you get 443,556 which does not fit in an int type, and the truncated value (17,572) is then converted to floating point.

So you want to convert the values to at least long for the multiply:

    for(i=0; i<7; i++)  {
        int result = 0.00067*(((long)value[i])*((long)value[i]))+0.5*value[i]-33;
        printf("%d \n", result);
    }

Or do the whole calculation in floating point (which will be slightly slower on the Arduino):

    for(i=0; i<7; i++)  {
        int result = (int)(0.00067*(((double)value[i])*((double)value[i]))+0.5*value[i]-33.0);
        printf("%d \n", result);
    }

32bit vs 16bit, thanks Paul!

Sorry, Michael for the 32 vs 16 bit explanation I meant.
changing the analog value to long instead of int was enough, I really never thought about 16 bits. (burden of using c++ and not thinking about the hardware I suppose)

Everybody thanks for your input!

MichaelMeissner:

        int result = (int)(0.00067*(((double)value[i])*((double)value[i]))+0.5*value[i]-33.0);

Just a nitpick, but I think it's misleading to use "double" here. Arduino doesn't implement double floats, only single floats -- a topic which seems to come up hourly some days -- and putting "double" in an example like this can give the wrong idea.