22 Improving your Analog Input Code
The combination of analogReadResolution()
and analogRead()
will let you get pretty good values for analog input voltages on the Analog to Digital Conversion (ADC) pins A0 to A5 of a 32 bit microcontroller like the SAMD M0. Older processors like the UNO don’t support analogReadResolution()
and only provide 10 bit return values between 0 and 1023 to represent the full input scale.
Throw Away an Initial Reading
The first reading you take from an analog input will probably be a little off due to accumulated residual charge on the circuitry. Calling analogread() once before actually getting the value(s) you will use can make your results more consistent. (video 1:12)
Average Multiple Readings
Taking the mean of multiple readings after throwing away the first one will reduce noise proportionally to the root of the number of samples (half for four samples, a quarter for 16, an eight for 64) based on the statistics of normal distributions. As this video (3:22) shows, averaging over 16 samples is a good compromise between speed and noise reduction.
Check the Noise Histogram
The previous examples make it clear that there’s noise in the values returned by analogRead(A1)
. This video (13:29) provides a coding example to keep track of how frequently different values are returned for a nominally constant voltage input on A1. There’s not enough storage space on the Itsy Bitsy to track all 65535 possible 16 bit values, so the code uses a mapping relationship to keep the values of interest in a much smaller array and uses the native 12 bit resolution to make things simpler.
The end result suggests that analog voltage measurements have Gaussian noise on them with an RMS (same as standard deviation at large sample sizes) of about 2 measurement steps, or about 1.5 mV for the 3.3 volt measurement range.
Thus the uncertainty due to noise on a voltage measurement would be about 3 mV, while the bias uncertainty due to the variability in the supply might be as large as 20 or 30 mV. (Check your microcontroller’s power supply voltage with a high quality multimeter to find the actual supply and reference voltage.)