Hey there,
I am having troubles understanding how the Arduino has two different answers for what I think is the same calculation when changing the output of the TMP 36 thermometer into celsius.
The attached screenshot shows the code with those two calculations that give a different value to the serial monitor on the right side.
Can someone explain to me why the first calculation's result is 22.27 but the second's is -48?
Thanks in advance
Serial.println((((analogRead(0)*5000)/1024)-500)/10);
You are overflowing the maximum integer value with analogRead()5000. 1505000>32,767.
If you specify the constant as 5000L it will force the calulation to a long.
Seehttp://arduino.cc/en/Reference/IntegerConstants
Delta_G:
The second one uses integer math. The first one is done floating point.
Does this mean that a float variable can calculate higher numbers?
If so, could I somehow change this
Serial.println((((analogRead(0)*5000)/1024)-500)/10);
into a float?
Also, if I it would not be (((analogRead(0)5000)/1024)-500)/10
but ((analogRead(0)(5000/1024))-500)/10
I think it should be the same result without getting over 32,767 because 5000/1024 is calculated first.
But this does not work either.
Adsunt:
Also, if I it would not be (((analogRead(0)5000)/1024)-500)/10
but ((analogRead(0)(5000/1024))-500)/10
I think it should be the same result without getting over 32,767 because 5000/1024 is calculated first.
But this does not work either.
This is because 5000/1024 = 4.88 which is truncated to 4 which is a large difference (18% inaccurate)...
Use this (((analogRead(0)*5000L)>>10)-500)/10
Side Note : Shouldn't 1024 actually be 1023 because the max is 1023 on the analog ports?
Thank you! That was helpful. Also I guess you are right about the 1023. I got it from a book which said 1024. But there where a few mistakes in the book before. I think the author's thought was that there where 1024 including the 0.
Ps991:
Side Note : Shouldn't 1024 actually be 1023 because the max is 1023 on the analog ports?
Actually, no.
With a 5V Aref the value 1023 actually represents 4.995V (1023/1024ths of Aref). You divide by 1024 and multiply by Aref to convert to voltage. The difference is less than 0.1% so it is usually not an issue.
johnwasser:
The difference is less than 0.1% so it is usually not an issue.
Im a perfectionist, I demand that 0.1%