RE. Using Arduino as a Volt Meter

I am still new and am experimenting with the arduino.
At the I'm trying to measure the voltage of a 1.5V AAA battery. I connected the +ve to pin A0 and the -ve to pin GND. I wrote the following code but can't get the correct voltage.

https://drive.google.com/file/d/1ouEsPdahkyhVXIvs25j9Ptegoj-ZSCK3/view?usp=sharing

If I workout the variable "v" : 306 * (5 / 1023) = 1.495V.
I can't figure out why the voltage is being printed as 0V.

Thanks in advance,
Daniel Camilleri.

x is zero...

5/1023 rounded/truncated to an integer is zero.

Try this

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  float x;
  float y;
  x = analogRead(A0);
  y = (x*5/1023);
  Serial.print("voltage = ");
  Serial.print(y);
  Serial.println();
  delay(500);
  
}

Use

 y = analogRead(A0)*(5.0/1024);

The 5.0 forces a floating point calculation (no integer truncation), and each ADC step is 1/1024 of the reference voltage.

Hi and thank you all for your quick reply.

To be80be, I have tried your code and it worked flawlessly, but I am unsure of what I did wrong in my first code.

What I think I understand from be80be and DrDiettrich is that to calculate analog readings the variable has to be set to float. Am I correct or is it something else?

Regards,
Daniel Camilleri.

Mine is using a float and doing the math before the cast y=( x*x/x )

Part of an expression can be evaluated using integer arithmetic, regardless of the type of the target variable. That's why in detail integer constants should be rewritten as floats (decimal point), if operations with these values should be made floating.

In fact it were better to use 1024.0, because the division by 1024 tends to be truncated when executed with integers.

I always used 1024 but it's really not right tho the adc is 0 to 1023 witch is 1024 steps
but like you say math works better at 1024 but you'll be a little off. probably no more then the adc is LOL

ADC 0 covers 0V to AREF/1024. Chose an offset within that range, just as you like.