How to introduce values into an Array

Hi!

I'm getting values from a sensor every second (I have the code to read the values), and I want to introduce that values in an Array to get the average value. Does anyone know how can it be done? or is there any other option without using Array?

Thanks a lot!

OK, say you want to average 10 values.

Make an array sized to hold 10 values, int i[10]={}

Make a cell pointer int ptrCell.

place a value into the array i[ptrCell]=1, average the 10 cell values, increment ptrCell++, repeat.

if( ptrCell>= 9 ) ptrCell=0;

Yup the very first 10 readings will be crap but after that, average away.

If you are looking to smooth data then a Kalman filter would work a bit better.GitHub - denyssene/SimpleKalmanFilter: A basic implementation of Kalman Filter for single variable models.

Is it a rolling average, or just an average of every N consecutive readings?

You don't actually need an array for an average of N readings...

total = 0;
for (int i = 0; i < 16; i++) total += readValue();
avg = total / 16;

Use a running total AND an array.
Subtract the oldest reading, add the newest.
Divide the total by ten.

TheMemberFormerlyKnownAsAWOL:
Use a running total AND an array.
Subtract the oldest reading, add the newest.
Divide the total by ten.

i realized the benefit of recording the accumulated sum of the values when looking at Covid data. but the variable type must be able to store the accumulated value.

for example, you probably need long if you're accumulating more than 64 10-bit values from an ADC

Thank you all, finally I used an Array and some if, to write the values on the Array at the time I wanted, and the just calculate the average value of the Array with a for loop.