Loading...
Searching...
No Matches
AnalogAveraging.ino

Shows how averaging steadies a reading: for averaging 1, 4, 8, 16 and 32, takes 100 readings of A0 and A3 and prints the lowest, the highest and the spread, in 12-bit ADC steps.

analogReadAveraging() applies to every analog pin: A3-A5 average inside the external ADC, A0-A2 take the samples one after another.

Wiring
Optional: a steady voltage, e.g. a potentiometer wiper, on A0 (0-3.3 V) and A3 (0-2.048 V).
Output
Serial Monitor at 115200 baud, for example:
Averaging 1: A0 2041-2058 (spread 17) A3 1022-1025 (spread 3)
Averaging 32: A0 2048-2050 (spread 2) A3 1023-1023 (spread 0)
// Shows how averaging steadies a reading. For each setting, takes 100
// readings of A0 and A3 and prints the lowest, the highest and the spread
// between them (in ADC steps). Connect a steady voltage, e.g. a potentiometer
// wiper, to A0 (0-3.3 V) and A3 (0-2.048 V), or leave them as they are.
//
// analogReadAveraging() applies to every analog pin: A3-A5 average in the
// external ADC itself, A0-A2 take the samples one after another.
const int READINGS = 100;
const uint8_t SETTINGS[] = {1, 4, 8, 16, 32};
void printSpread(const char* name, pin_size_t pin) {
int lowest = 4095;
int highest = 0;
for (int i = 0; i < READINGS; i++) {
const int value = analogRead(pin);
if (value < lowest) lowest = value;
if (value > highest) highest = value;
}
Serial.print(name);
Serial.print(" ");
Serial.print(lowest);
Serial.print("-");
Serial.print(highest);
Serial.print(" (spread ");
Serial.print(highest - lowest);
Serial.print(") ");
}
void setup() {
Serial.begin(115200);
while (!Serial) {}
analogReadResolution(12); // 0-4095, to see the small changes
}
void loop() {
for (uint8_t samples : SETTINGS) {
Serial.print("Averaging ");
Serial.print(samples);
Serial.print(": ");
printSpread("A0", A0);
printSpread("A3", A3);
Serial.println();
}
Serial.println();
delay(3000);
}
SerialUSBClass Serial
USB serial port, the one the Serial Monitor uses.
void analogReadResolution(int bits)
Sets the number of bits analogRead() returns, for every analog pin.
void analogReadAveraging(uint8_t samples)
Sets how many samples are averaged for each analog result, on every analog pin.
int analogRead(pin_size_t pinNumber)
Reads the voltage on an analog pin.
void loop(void)
Written by the sketch: runs over and over after setup(), on core 0.
void setup(void)
Written by the sketch: runs once after reset, on core 0.
void delay(unsigned long)
Waits a number of milliseconds.
uint8_t pin_size_t
Type for Arduino pin numbers (uint8_t).
Definition Common.h:112