Analog Averaging example sketch 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)
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++) {
if (value < lowest) lowest = value;
if (value > highest) highest = value;
}
Serial.print(highest - lowest);
}
}
for (uint8_t samples : SETTINGS) {
printSpread("A0", A0);
printSpread("A3", A3);
}
}
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