So I am very confused at the results I am getting. It seems that floats aren't working properly, and I don't understand why.
I was trying to read a temp sensor and convert the reading to celsius. However, when I tried to divide the value (an int between 145-165) by 1024, and multiply by 5 I would get back a float value of 0.00 Here's the code I was using
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(A0, INPUT);
}
void loop() {
int sensorVal = analogRead(A0);
Serial.print("Sensor Value: ");
Serial.println(sensorVal);
float voltage = ((sensorVal/1024) * 5);
Serial.print("Voltage Value: ");
Serial.println(voltage);
}
This would only return values of 0.00 for voltage, even though the sensor itself is working fine, returning varying values between 146 and 165 based on how much heat I apply. This didn't make any sense, so I tried it with some other values, eg.
Serial.print(float (10 / 6));
and
Serial.print(float (5 / 2));
which should have returned 1.67 and 2.50 respectively, but instead returned 1.00 and 2.00
I think it might be a settings thing, where all floats round down to an int, but that seems really weird.
Any help would be great!
float voltage = ((sensorVal/1024.0) * 5.0);
0/11
will yield 1, since the answer is ≈1.81, and it simply strips away the decimal part. By comparison,round(20.0/11.0)
will give you a value of 2.0, since 1.8181 rounded rounds up to 2.)