Fpasquer
Fpasquer

Reputation: 413

ATMEGA328p convert analog value to voltage

This is an extract of the official ATMEGA328p data sheet page 261:

enter image description here

As the documentation say

      Vin * 1024
ADC = ----------
         Vref

What I don't understand is an analog pin can provide us 10bits. That's mean a value between 0x0 and 0x3ff (1023)

So I don't understand why the documentation say Vin * 1024 and not 1023. Because for me 0v = 0 and 5v = 1023?

Upvotes: 6

Views: 1137

Answers (3)

AterLux
AterLux

Reputation: 4654

5v = 1024, yes, but you cannot measure 5V with 5V reference, the maximum value you can measure is 1023/1024 of Vref, i.e. if Vref=5V, then max value is 4.995V. This and all voltages above this will read as 1023 (0x3FF).

So, you're right, the Vref voltage requires value 1024 which requires 11 bits to store, but you never can measure that voltage using ADC.

But according to the datasheet (28.9 ADC Characteristics at page 265) Absolute accuracy of the ADC in ATmega328P is typically at 2.2 LSB, so you can be not worried about 1LSB error which appears if use 1023 instead of 1024 as the divisor.

But still, using of 1024 not only more correct in meaning of measurement, but also can be optimized in integer math, thus not requiring complex operations such as the division:

   // convert ADC value into millivolts (assuming Vref is 5000 mV)
   uint16_t result_in_mv = ((uint32_t)adc_result * 5000UL) >> 10;

Upvotes: 4

Lundin
Lundin

Reputation: 213892

Yeah this is a common mistake. One thinks 10 bits = 2^10 = 1024 and so there will be 1024 steps, right? Nope, 10 bit ADCs only give output up to 1023 (3FFh), because that is the largest number you can fit into 10 bits.

So if you do arithmetic on 1024 instead of 1023, you introduce a very slight inaccuracy in the calculation. I've done this bug myself and it sat in production code for over 10 years without anyone noticing, and when I fixed the bug nobody noticed a difference either :) But naturally we should always strive for program correctness.

Upvotes: 2

Lakshitha
Lakshitha

Reputation: 1542

0 counts as a valid reading. 1..1023 is 1023 steps and plus 0 that makes 1024. 0x000 represents analog ground, and 0x3FF represents the selected reference voltage minus one LSB. 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. In theory using 1024 is more accurate.

Upvotes: 7

Related Questions