I've tried to create a thermometer using the Arduino together with a temperature sensor.
However, for some reason I can get the arduino to send me the value read from the analog port, using analogRead() to store it in a value, and then using Serial.println() to print it in the serial monitor.
However the moment I start trying to calculate a value, it just sends a 0.
Here's the code I used;
// thermometer: gets voltage from a sensor connected to analog pin 5, calculates a temperature from this, and sends it to serial port every second
#define sensor 5
int val = 0;
float voltage = 0;
int temperature = 0;
void setup()
{
Serial.begin(9600); //open the serial port
}
void loop ()
{
val = analogRead(sensor);
Serial.println(val);
voltage = ((val/1023)*5);
Serial.println(voltage);
temperature = ((voltage - 0.5) * 100);
Serial.println(temperature);
delay(1000);
}
The arduino returns; 142 (that's the analog read value)
0.00 (obviously I did something wrong with the calculation)
-50 ((0 - 0.5) *100 is -50 of course)
I suspect your calculations are running into problems because of the use of float and int variables together in the same statements. I'll let the stronger software people explain it better then I can, but it's a common mistake for beginners to make.
thanks for the answer, however, the first time I tried this I calculated the temperature directly from the analogue value (temp = ((val / 1023 ) * 5 - 0.5 ) * 100), not really caring that I'd lose precision because I don't think the sensor's that precise.
I only found out it was in the calculations because I measured the voltage output of the sensor with a multimeter
well, I don't really know what truncation is, I'll have to look it up.
But in the 2nd calculation I posted I calculate with a integer, and store into an integer, and it gave the same error, so I don't think the problem is in the float.
I thought that if you go from a float to an integer it cuts out all numbers right of the . ?
I thought it only truncated at the moment it had to store it in the integer.
C has two different sets of arithmetic operators: integer and floating-point.
By default, arithmetic is integer using the int datatype. "5 * 37" is performed using integer arithmetic with int as the datatype. Results less than -32768 or greater than +32767 are undefined.
char C = 15;
char X = 82;
Serial.print( C * X ); // C and X are promoted to int and then an integer multiply is performed.
If an operand is a larger datatype, the operation is performed in that datatype...
int F = 5;
long TS = 37;
Serial.print( F * TS ); // is performed using integer arithmetic with long as the datatype. Results less than -2147483648 or greater than +2147483647 are undefined.
If an operand is a floating-point datatype...
int F = 5;
float PI = 3.1415;
Serial.print( F * TS ); // is performed using floating-point arithmetic with float as the datatype
Adding ".0" forced to compiler to use floating-point arithmetic.