Electronic – arduino – How to obtain Input voltage from ADC value

adcanalogarduinoatmega328psampling

I am using atmega328p for my project. I have to read my battery voltage and display it in my cloud. For that, i am using ADC. Now I am getting the ADC value for input voltage applied. But i need to convert the ADC to voltage.

When I go to datasheet, I observed the following equation here

So to convert ADC, Vin=(ADC/1024)*Vref.

But When i searched the google I found another equation and it is

Vin=(ADC/1023)*Vref

Now I doubt that which equation is to use?

If we use 1024, ADC value will be 0001 when the input voltage is equal to 1LSB voltage(Vref/1024).

If we use 1023(second equation), ADC value will be 0000 when the input voltage is equal to 1LSB voltage (Vref/1024)

Best Answer

First let me quote the picture which already has the answer : "0x000 represents analog ground, and 0x3FF represents the selected reference voltage minus one LSB". That would mean to represent the reference voltage Vref, one LSB count more would be needed so the result would be 0x400 or 1024. So a voltage equaling Vref just cannot be represented as a result, it is a special case. For all other voltages that are at least 0.5 step below Vref (between 1022.5 and 1023.5) the result is valid.

Atmel has an ADC application note for AVRs that explains how the successive ADC works, and it is not obvious but helps to understand which one is correct. There are also a lot of threads on AVRFreaks about which one is correct. And armed with that information, 1024 is correct and there is no error in the datasheet.

In reality, ADCs are not perfect as results can have more than 1 count of error and it really does not matter much if 1023 or 1024 is used, as you rarely need accuracy of 1 count out of 1024 at the Vin=Vref extreme case anyway.