Array shift and taking the averages

Hi,

I have a duty with arduino. ı have to create a row matrix with 100 entry by using read values from analog pin. for example:
array = [x1 x2 x3 ..... x100]. these x values are analog read values. then ı need to take average of these 100 values. after this step, ı need to shift this array to left, and add newly read value to the end of the array. then, again ı need to take the average of new array. this steps must continue until the user stop the code.
how can ı built such a code? please help. thanks in advance.

1 Like

Welcome to the forum

There is no need to move the array values which would be very clumsy. Instead use a variable to hold the value of the array index last written to and change that before saving the next value to the array. Once the array is full wrap the index value back to zero and keep going

What you will be implementing is a circular buffer which is a good term to search for to get more details

We don't do other people's homework, at least, I don't.

You could program it just as you described it, it would work.
More efficient and elegant would be to use a circular buffer,
which does not require any rearrangement of elements.

this is not a homework. this is a tiny part of my project, and ı am not software engineer. ı am hardware engineering student. so that ı decided to ask some help.
thanks for your help, at least.

It sounds like you can just use the moving average filter library.

You build this code one step at a time, just like you do hardware engineering. Both start at the beginning and do one small part and test it.

Begin your program by defining a 100 entry array of data sized to fit the return from an analog read.

Or a weighted moving average filter if the only purpose is to do some smoothing.

And if you have the freedom to select the pole location to be one minus a negative power of two, you can eliminate the divisions, resulting in much higher performance:

Arduino Helpers: EMA<K, input_t, state_t> Class Template Reference

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.