Ever wondered why the Leonardo ( 32u4, ATmega32U4 ) has an internal reference of 2.56 volts? Not 2V, not 3V?
The 10bit sampling of analogRead() gives you 1024 levels: 0 to 1023
Incidentally, 2560mV / 1024 = 2.5, exactly. This means that if you multiply the analogRead() sample value by 2.5 you get your analog voltage in millivolts.
But wait! There is more…
v = alalogRead(pin)
mV = 2.5 * v
mV = 2v + 0.5v
mV = 2v + v/2
Maybe you didn’t know of the neat low level trick, arithmetic shift, where:
shift left 1 on a number << multiplies it by 2
shift right 1 on a number >> divides it by 2
So, instead of multiplications you can do this to convert your sample to millivolts:
v = alalogRead(pin)
mV = v << 1 + v >> 1
No multiplication, no floating point arithmetic.
PS. The cool thing is, the compiler knows about arithmetic shifts so you can optimise the conversion simply by writing:
mV = 2*v + v/2
and it will all be taken care of so long as no one involved is a float. Easier to read than shifts.
You are not clear if you mention a floating point calculation or an integer calculation.
If optimized code is needed that is very fast, some arithmetic optimizations can be useful. But I would not recommend it.
For normal readable code, a floating point calculation using 2.56 is best.
And the internal voltage reference is never exactly 2.56, it might be 2.52 or 2.63. That would be easy to correct in the code if a normal floating point calculation is used.
Hey all, I just thought this was an interesting conclusion. Does it actually help anyone? No idea. Helps me crystalise things in my head anyway XD
@caltoa you are right! Idid not mention that the variables "v" and "mV" need to be integer/long to benefit from this. Also, how can you measure the absolute internal voltage reference so you can correct for it in code?
@robtillaart That's a handy experimental result. Will note that. Thanks!
While we are talking timing and analog inputs, it is worth mentioning what I read elsewhere in the forum: Switching analogReference() takes about 5.5ms : "this delay is because of the 100nF cap on the AREF pin" says @wayneft