/* * adc_statistics.ino * ARGYNIX Skills (worldskills.blog), lesson "From reading to result: an uncertainty budget". * Arduino Uno. Save it in a folder named adc_statistics. * * Takes 100 readings of A0, then prints the mean, the standard deviation s and the * standard uncertainty of the mean, s / sqrt(n): a Type A evaluation, done by the board. * Every 3 seconds, on Serial at 115200 baud. * * VREF_MV: measure the Uno's 5V pin with your meter and put the real value here. The ADC * compares against it, so every millivolt figure is only as good as this number. */ const uint8_t N = 100; const float VREF_MV = 5000.0; void setup() { Serial.begin(115200); analogRead(A0); // the first reading after a change of channel can be off: throw it away } void loop() { // Welford's method: the mean and the spread in one pass, without huge sums float mean = 0.0; float m2 = 0.0; uint16_t lo = 1023, hi = 0; for (uint8_t i = 1; i <= N; i++) { uint16_t x = analogRead(A0); if (x < lo) lo = x; if (x > hi) hi = x; float d = x - mean; mean += d / i; m2 += d * (x - mean); delay(2); } float s = sqrt(m2 / (N - 1)); // n - 1: the sample standard deviation float u = s / sqrt((float)N); // standard uncertainty of the mean float lsb = VREF_MV / 1024.0; // one count, in mV Serial.print(F("n=100 mean=")); Serial.print(mean, 2); Serial.print(F(" counts (")); Serial.print(mean * lsb, 1); Serial.print(F(" mV) s=")); Serial.print(s, 2); Serial.print(F(" counts u(mean)=")); Serial.print(u, 3); Serial.print(F(" counts min=")); Serial.print(lo); Serial.print(F(" max=")); Serial.println(hi); delay(3000); }