[SOLVED] Get 0.00 when trying to print float

I can't understand why I keep getting 0.00 from this line:
"float val = sensorValue * (5/1023);"
The prints ok but the float is always 0.00

int sensorPin = A0;    // select the input pin for the potentiometer
    // select the pin for the LED
int sensorValue = 0;  // variable to store the value coming from the sensor
void setup() {
  Serial.begin(9600);
}

void loop() {
  // read the value from the sensor:
  sensorValue = analogRead(sensorPin);  
  Serial.println(sensorValue);  
sensorValue = sensorValue; 
   float val = sensorValue * (5/1023);
      delay(1000);
  Serial.print(val);       
    Serial.println(" volts");
    
 
}

Because 5 divided by 1023 is less than 0. Convert that to float and you get 0. O times sensorValue will always be zero.

5/1023 will be preformed with integer calculations, since both values are integers. And thus the result is 0.

Use instead:
float val = sensorValue * (5.0/1023);

Actually, I expect the compiler will replace that with a value to speed up the evaluation time. That value will be zero!

According to Arduino, line should be.................. float val = sensorValue *(5.0/1023.0);

https://docs.arduino.cc/built-in-examples/basics/ReadAnalogVoltage/

westfw,
Thanks, I found the answer in a sketch I found in my files. I ran a similar program and it worked
with this line:
"float voltage = sensorValue * (5.0 / 1023.0);"
Apparently only one of the two values need to be a float for the result to be a float.
Thanks for the reply.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.