Just to as a complement to Majenko's answer (which I second), there are a couple of flaws in your program that may be related to your problem:
lowest
is always zero, as it is initialized to 0 and cannot increase- your computation of the mean is incorrect: the mean is the sum of the readings divided by their number
- you fail to reset
lowest
andhighest
between consecutive runs of 8000 samples - there is no point in putting all of
loop()
inside an infinite loop.
Assuming you really intend to print summary statistics on runs of 8000 samples, as your code suggests, I would write it like this:
const int SENSOR_PIN = A0;
const int SAMPLE_COUNT = 8000;
void loop()
{
long sum = 0;
int lowest = INT_MAX, highest = 0;
for (int i = 0; i < SAMPLE_COUNT; i++) {
int sensorValue = analogRead(SENSOR_PIN);
sum += sensorValue;
highest = max(highest, sensorValue);
lowest = min(lowest, sensorValue);
}
float mean = (float) sum / SAMPLE_COUNT;
Serial.print("mean: "); Serial.print(mean);
Serial.print(", minimum: "); Serial.print(lowest);
Serial.print(", maximum: "); Serial.println(highest);
}
Edgar Bonet
- 45.1k
- 4
- 42
- 81