 calculation error

Hi all,

I have a strange issue with a simple calculation.
I’m using the analog input A0 to read a potentiometer, this part is working well. The potentiometer is simulating a pressure transducer I’ll use in my final work.

The code below show the variable and the calculation I’m using to transform the analog input into physical measure.

int sensor_min = 102; //sensor minimum scale, 102 = 0.5V
int sensor_max = 920; //sensor maximum scale, 920 = 4.5V
int sensor_range = 150; //sensor range: 150 PSI

pressure = (sensor_range*(sensorinput-sensor_min))/(sensor_max-sensor_min); //full scale conversion

Serial.print(sensorinput);
Serial.print("   ");
Serial.println(pressure);

the expected result is a pressure between 0 and 150 for 102 to 920 input reading.
And here is the result for some input values, first column is analogread and second one is calculation result.

262 29
282 33
303 36
317 39
334 -37
352 -34
366 -31
383 -28

493 -8
502 -6
513 -4
521 -3
529 -1
543 0
552 2
562 4
575 6

725 34
735 35
743 37
749 38
755 39
764 -38
772 -37
779 -36
793 -33
802 -31
814 -29

When I’m doing the calculation by myself the result is good, but as you can see the arduino is doing something I don’t understand.

My only idea is a limit when the arduino is doing the calculation, maybe because of int ? Do I need to use double or long somewhere?

A 16 bit int stores integer values in the range -32768 to 32767.

Ok, I understand. So I need to use long instead of int.

For all of the var or only sensor_range (only the left part of the division is going over 32767).

For anywhere the result of an addition or multiplication will result in a partial result > 32767

It's ok.

Thank you for you help :)