Hello everybody,
I'm not an expert so maybe I'm doing some sacrilegious mistakes.
I am trying average the values of a CO2 sensor but the results are inconsistent.
Here you have a test code. After running for a while, it starts giving nonsense values.
float co2 = 3;
float sum = 0;
int i = 0;
float co2Arr[200];
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
if(i<200){
co2Arr[i] = co2;
i++;
}
else{
for(int j = 0; j<=200; j++){
sum += co2Arr[j];
}
float average = suma/200;
Serial.println("the average");
Serial.println(average);
memset(co2Arr, 0, 200);
average = 0;
sum = 0;
i=0;
}
}
If it loops for 0, 200, and each number in between, that would 201 different numbers. Depending on whether the next 4 bytes in memory are zero or not, you'd get 3 or not.
( edit: Oops. I didn't read the comments -- What they said)
It seems at least probable that "the worst" that could go wrong is picking up a random number, but I think the act of reading at j == 200 means anything can happen.
No one has pointed out yet that the array is not needed at all, in @gbg_4 's current code. It uses 800B of ram memory for no reason.
It waits until 200 values have been accumulated in the array, then calculates the total and then the average, prints the average, then clears all values and starts over (or at least it will do when the errors pointed out have been corrected)
So the array is not needed. The total could be updated as the values arrive, without storing them in an array. Once 200 values have been received, the average can be calculated and printed as they are now.
float co2 = 3;
float sum = 0;
int n = 0;
#define N 200
void loop()
{
if (++n < N)
sum += co2;
else {
float average = sum / N;
Serial.print ("the average ");
Serial.println (average);
sum = n = 0;
}
}
void setup() {
Serial.begin(9600);
}