Prevent overflow when averaging Arduino ADC samples
Seventy readings of 1,023 add up to 71,610.
0 of 3 complete · Progress saved on this device
Work out the example
Seventy readings of 1,023 add up to 71,610. A 16-bit unsigned accumulator holds at most 65,535. Its wrap occurs before dividing the sum by the count.
Decide what to check next
Use a 32-bit accumulator before adding. Divide only after all samples are included, and handle an empty window separately. Casting the already wrapped result to a larger type cannot restore the missing bits.
Compare with the serial result
The wide sum yields 1023.
Open the exact Uno example
The wide sum yields 1023.
void setup() {
Serial.begin(9600);
uint32_t sum = 0;
for (byte reading=0; reading<70; ++reading) sum += 1023;
Serial.println(sum / 70);
}
void loop() {}Verified with [email protected] on Uno R3 (2026-12-05 UTC). This check did not use physical hardware.