# Voltage reading returning 0 always

This is my sketch... whitch always returns 0.00 The problem is in Calc 2, since Calc 1 returns usable data.

So what is wrong here voltage = voltage / (r2 / (r1 + r2));???

Thank you.

void setup() {
Serial.begin(9600);
}

void loop() {
int vinPin = A1;
float voltage = batVolt(vinPin, 10000, 10000);
Serial.println(voltage);
delay(500);
}

float batVolt(int senzorPin, int r1, int r2) {
//Calc 1
float voltage = sensorValue * (5.0 / 1023.0);
//Calc 2
voltage = voltage / (r2 / (r1 + r2));
return voltage;
}

this is due to integer division in BatVoltage (integer division truncates,

Change it to float to solve it

float batVolt(int senzorPin, float r1, float r2) {
//Calc 1
float voltage = sensorValue * (5.0 / 1023.0);
//Calc 2
voltage = voltage / (r2 / (r1 + r2));
return voltage;
}

or If you want to do it with integer values for r1 and r2 you need to rewrite the formula

float batVolt(int senzorPin, int r1, int r2) {
//Calc 1
float voltage = sensorValue * (5.0 / 1023.0);  // to speed up you could replace this with a constant 0.00488 something float division take a lot of time
//Calc 2
voltage = voltage *  (r1 + r2) / r2;
return voltage;
}

Note this can be written into in short

float batVolt(int senzorPin, int r1, int r2)
{
return ((analogRead(senzorPin) * 0.004887586) *  (r1 + r2)) / r2;
}

The () are needed to force float math otherwise (r1+r2)/r2 might still cause a (small) truncating/rounding error

Thank you very much!

did it work?