My (genuine) Arduino DUE board gives inconsistent analog input readings.
An analog voltage equal to exactly 1/2 of the 3.3V reference is connected to A1, read 500 times in a loop, and then averaged to improve accuracy. The voltage is obtained by resistively dividing the reference with two precision 2K000 resistors, and is filtered with a 1uF capacitor mounted directly on the input pin.
As 500 readings are taken, with a delay between readings of 1 mS, average readings are displayed every 0.5 seconds. The consistency of successive averaged readings is less than 0.1 count, as it should be given there are 500 readings in each average.
However, is observed that the averaged value varies by up to 2LSB, depending on the presence or absence of program code that has nothing whatsoever to do with reading the voltage or calculating the average.
For example, when the second-last line of code is "Serial.print(a)", the average voltage reads 2047.4, which is pretty much exactly what you would expect, being almost exactly half of the full scale ADC count of 4095.
However, when that line of code is changed to "Serial.print(a/4.0)", the average voltage changes to 2049.5, an inexplicable and unacceptable change of ~2LSB.
There is nothing 'special' about this line particular of code that changes the analog reading. In general, it is found that adding, removing or altering ANY line of code slightly changes the voltage reading. If you use the serial monitor to look at the individual readings rather than the average, then you observe the same thing. The voltage returned by analogRead() varies according code in the program that has absolutely nothing to do with reading the voltage.
Something is not right here, and this strange effect is a real PITA, making it impossible to obtain meaningful, accurate voltage readings.
I also have a UNO board, and it behaves perfectly. The simple program code is given below.
What is going on here????
/*
This program illustrates a problem with reading analog inputs on the Arduino DUE
*/
int sum; // DUE has 32 bit integers, so don't need 'long'
int a,b;
int n=500;
float Vave;
void setup() // the setup routine runs once when you press reset:
{
analogReadResolution(12);
Serial.begin(9600); // initialize serial communication at 9600 bits per second:
}
void loop()
{
sum=0;
b=0;
for (int i=1; i <= n; i++) {
delayMicroseconds(1000); // 1 kHz read rate, analog read needs this delay
sum = sum + analogRead(A1); // read the voltage on analog pin 1
} // Next i
Vave=sum/float(n); // Vaverage in units of ADC counts
a=b/float(n); // Arbitrary, typical line of code
Serial.print( Vave );
Serial.print(" ");
Serial.print( a/4.0 ); // Changing ( a ) to ( a/4.0 ) significantly changes the average voltage reading!!??!!
Serial.println(" ");
}