Array manipulation

i think i heard my Arduino attempt to scream... :stuck_out_tongue:

i'm trying to use a moving average of a sensor data (Accelerometer) to smooth out the values from analogRead(A2);

here's the code i used;

/*
  AnalogReadSerial
 Reads an analog input pin, prints the result to the serial monitor.
 */

int oldAvg[10] = {512, 512, 512, 512, 512, 512, 512, 512, 512, 512};
int newAvg[10];
int movit;
int calcit;

void setup() {
  Serial.begin(9600);
}

void loop() {


    for (int i=0; i<9; i++)  {
      movit=oldAvg[i+1];
      newAvg[i]=movit;
    }
    newAvg[9]=(analogRead(A2))*5/3;  // expand the resolution, i think the sensor operates on 3.3 V ...
/*
Serial.print("analogRead(A2)= ");
Serial.print(analogRead(A2));
Serial.print("*5/3 = ");
Serial.println(newAvg[9]);
*/
    for (int i=0; i<10; i++)  {
      // calcit=+newAvg[i]; THIS DOESN'T WORK IN Arduino IDE ??
      calcit = calcit + newAvg[i];
    }
    int sensorValue=calcit/10;

    oldAvg[10] = newAvg[10];    // THIS IS THE CULPRIT

    calcit = 0;

    Serial.println(sensorValue);
    delay(100);        // delay in between reads for stability **using moving average, delay can be shortened

}

after a few loops, the reading just levelled (or maxed !) at 1023 and wouldn't budge - i spend a lot of time trying to find out where i might have made an error, and only after rebuilding the code bit by bit, i found the problem line.

after changing it to;

    for (int i=0; i<10; i++)  {
      oldAvg[i] = newAvg[i]; // assign the members one at a time
    }

all was fine.

the Verify process didn't have problems with assigning an array directly to another in one line, so what happened in the original code that pissed the Arduino off ?

also, is the code as efficient as possible already - are there faster functions to manipulate arrays like push or pop which i've seen used in some other high-level language but wasn't able to find it with a cursory browse though php.net or cplusplus.com

Sensible names will make coding so much easier.

int oldAvg[10] = {512, 512, 512, 512, 512, 512, 512, 512, 512, 512};

Is this supposed to be an array of averages? Or an array of values?

    for (int i=0; i<9; i++)  {
      movit=oldAvg[i+1];
      newAvg[i]=movit;
    }

You don't need an intermediate variable. You most certainly do not need that variable to have global scope.

      // calcit=+newAvg[i]; THIS DOESN'T WORK IN Arduino IDE ??

Sure it does. It may not do what you expect, but without knowing what you expect, it's hard to say what is wrong. I'd guess, though, that you wanted +=, not =+. Use some space between operators, so shit like this stick out like a sore thumb.

You don't need to arrays to compute a moving average. it is done with one array.

hello again, Paul - thanks for your help as always !

PaulS:
Sensible names will make coding so much easier.

int oldAvg[10] = {512, 512, 512, 512, 512, 512, 512, 512, 512, 512};

Is this supposed to be an array of averages? Or an array of values?

i was preloading the array with 10 "average" (half of 1024) values instead of then ignoring the first 10 loops of the code.
my assumption was the first readings (of an accelerometer just starting out, at rest) would be "in the middle".

PaulS:

    for (int i=0; i<9; i++)  {

movit=oldAvg[i+1];
      newAvg[i]=movit;
    }



You don't need an intermediate variable. You most certainly do not need that variable to have global scope.

so;newAvg[i]=oldAvg[i+1]; is valid ?
(i might have been thinking of some limitations of BASIC)

PaulS:

      // calcit=+newAvg[i]; THIS DOESN'T WORK IN Arduino IDE ??

Sure it does. It may not do what you expect, but without knowing what you expect, it's hard to say what is wrong. I'd guess, though, that you wanted +=, not =+. Use some space between operators, so shit like this stick out like a sore thumb.

okay - will have to try that again.

PaulS:
You don't need to arrays to compute a moving average. it is done with one array.

hmm... will go back to the drawing board and try...

oh, and what was the error(?)/problem with oldAvg[10] = newAvg[10];

so;newAvg=oldAvg[i+1]; is valid ?

Of course not. Using code tags ALL THE TIME is important.

oh, and what was the error(?)/problem with

Your arrays have ten elements, numbered 0 to 9. Assigning an out of bounds value outside the bounds of an array is not good.

PaulS:

so;newAvg=oldAvg[i+1]; is valid ?

Of course not. Using code tags ALL THE TIME is important.

ha, yeah - right you are, sir !
have now answered (the intended question) below.

PaulS:

oh, and what was the error(?)/problem with

Your arrays have ten elements, numbered 0 to 9. Assigning an out of bounds value outside the bounds of an array is not good.

not sure i've got this yet - aren't they both arrays with ten elements ?

and here's the much improved code now !

/*
  AnalogReadSerial
 Reads an analog input pin, prints the result to the serial monitor.
 */

const int setcount = 10;
int movingAverage[setcount];
int accumulate;


void setup() {
  Serial.begin(9600);
}


void loop() {
    
    for (int i=0; i < (setcount-1); i++)  {
      accumulate += movingAverage[i];
      movingAverage[i] = movingAverage[i+1];
    }
    movingAverage[setcount-1]=(analogRead(A2))*5/3;  // stretch resolution from 3V to 5V
    accumulate += movingAverage[setcount-1];

    int sensorValue = accumulate/setcount;
    accumulate = 0;

    Serial.println(sensorValue);
    delay(100);        // delay in between reads for stability - no longer needed with mov.avg
}

but i have a feeling there might still be an even more efficient way ?
perhaps streamlining the operation on accumulate ?

not sure i've got this yet - aren't they both arrays with ten elements ?

They are. The 10 elements are numbered 0 to 9. The index value of 10 is invalid. The highest index value for each array is 9.

    movingAverage[setcount-1]=(analogRead(A2))*5/3;  // stretch resolution from 3V to 5V

5/3 == 1

5.0/3.0 == 1.66667

Frankly, the method you have for formulating an average is not all that good. Generally, if the idea is to average values read from a sensor, you simply add some ratio of the new value to the former average after scaling it:

   average = average * 0.9 + newvalue * 0.1;

By picking a suitable start value for average (512 is good, in your case), average moves only a little if an outlier arrives as the first value.

Just a thought so you don't have to remember setcount if you change it:

const int maxArrayIndex;
int movingAverage[10];
int accumulate;


void setup() {
  Serial.begin(9600);
  maxArrayIndex = (sizeof(movingAverage) / sizeof(int)) - 1;      // Max index is element count - 1
}
void loop() {
    
    for (int i=0; i < maxArrayIndex ; i++)  {
      accumulate += movingAverage[i];
      movingAverage[i] = movingAverage[i+1];
    }
    // And rest of code...
}

This way, if you change the array size, you only change it one place...at the point where the array is defined. However, the real benefit comes if you move the code to a processor that has 4-byte ints instead of 2-byte ints or you change the data type in some way. I would also move the parenthesis in the expression:

    movingAverage[setcount-1]=(analogRead(A2)*5)/3;  // stretch resolution from 3V to 5V

Since the precedence operators evaluate left to right, your code works fine. This minor change just documents that you don't want to multiply by 1 (i.e., for integers, 5 / 3 = 1).

PaulS:

not sure i've got this yet - aren't they both arrays with ten elements ?

They are. The 10 elements are numbered 0 to 9. The index value of 10 is invalid. The highest index value for each array is 9.

ARGH! the "mistake" i thought was happening was assigning the WHOLE array, as in:

oldAvg[] = newAvg[];

THAT is not on.
i'd mistaken the "10" from the array declaration, now i see what i actually did was.assigning members, which is valid - but not when the index is out of bounds.

PaulS:

    movingAverage[setcount-1]=(analogRead(A2))*5/3;  // stretch resolution from 3V to 5V

5/3 == 1

5.0/3.0 == 1.66667

but that "force type" (typecasting?) wouldn't have an effect if movingAverage[] has been declared as type int, right ?

PaulS:
Frankly, the method you have for formulating an average is not all that good. Generally, if the idea is to average values read from a sensor, you simply add some ratio of the new value to the former average after scaling it:

   average = average * 0.9 + newvalue * 0.1;

By picking a suitable start value for average (512 is good, in your case), average moves only a little if an outlier arrives as the first value.

ahh... even more basic math !!
yes, that's a lot "better".
i'd been replicating what a spreadsheet would do - looking at the cells, instead of looking at the numbers !

econjack:
Just a thought so you don't have to remember setcount if you change it:

const int maxArrayIndex;

int movingAverage[10];
int accumulate;

void setup() {
  Serial.begin(9600);
  maxArrayIndex = (sizeof(movingAverage) / sizeof(int)) - 1;      // Max index is element count - 1
}
void loop() {
   
    for (int i=0; i < maxArrayIndex ; i++)  {
      accumulate += movingAverage[i];
      movingAverage[i] = movingAverage[i+1];
    }
    // And rest of code...
}




This way, if you change the array size, you only change it one place...at the point where the array is defined. However, the real benefit comes if you move the code to a processor that has 4-byte *int*s instead of 2-byte *int*s or you change the data type in some way. I would also move the parenthesis in the expression:
...
Since the precedence operators evaluate left to right, your code works fine. This minor change just documents that you don't want to multiply by 1 (i.e., for integers, 5 / 3 = 1).

i was thinking that setcount would infact be a main parameter of the above code which could become a function for plotting raw data, but yes, i've seen sizeof() being used in such a manner and it's probably best practice to do it like that - minimise 'hard code' wherever possible !

good to know that someone know's what i should be doing ! :smiley:

but that "force type" (typecasting?) wouldn't have an effect if movingAverage[] has been declared as type int, right ?

The comment says:

// stretch resolution from 3V to 5V

That's a stretch factor of 1.6667, isn't it? 5/3 is 1, which is a bit less than 1.6667.

PaulS:

but that "force type" (typecasting?) wouldn't have an effect if movingAverage[] has been declared as type int, right ?

The comment says:

// stretch resolution from 3V to 5V

That's a stretch factor of 1.6667, isn't it? 5/3 is 1, which is a bit less than 1.6667.

ahh, i see - bad commenting then.
the "stretch" is really more for the Y-axis graph plot (make the curve more pronounced), the analogRead(A2) is 10-bit resolution in any case.

PaulS:
...
Frankly, the method you have for formulating an average is not all that good. Generally, if the idea is to average values read from a sensor, you simply add some ratio of the new value to the former average after scaling it:

   average = average * 0.9 + newvalue * 0.1;

By picking a suitable start value for average (512 is good, in your case), average moves only a little if an outlier arrives as the first value.

okay, i've simplified the code even further to this method - looks even more streamlined... code wise.

/*
  AnalogReadSerial
 Reads an analog input pin, prints the result to the serial monitor.
 */

float average = 512;      // for analogRead()= 0 to 1023 , no need to be float - YES if using "math method" of averaging
float setcount = 10;    // even this has to be declared float !

void setup() {
  Serial.begin(9600);
}

void loop() {
    
    average = ( average * ( (setcount-1) / setcount ) )  +  ( ( analogRead(A2)*5/3) * ( 1/setcount ) );

    int sensorValue = average;      // NOW typecast to int for plot

    Serial.println(sensorValue);
    delay(100);        // delay in between reads for stability
}

but it actually compiles to a bigger file (3,882 Bytes) compared to the one using array (2,780 Bytes) - does this make sense ?

it's because of the two float variables, isn't it ?

float setcount = 10;    // even this has to be declared float !

Is setcount going to change? Use const if not.

retronet_RIMBA1ZO:

PaulS:
Frankly, the method you have for formulating an average is not all that good. Generally, if the idea is to average values read from a sensor, you simply add some ratio of the new value to the former average after scaling it:

   average = average * 0.9 + newvalue * 0.1;

By picking a suitable start value for average (512 is good, in your case), average moves only a little if an outlier arrives as the first value.

ahh... even more basic math !!
yes, that's a lot "better".
i'd been replicating what a spreadsheet would do - looking at the cells, instead of looking at the numbers !

That's a very simple IIR lowpass filter. You should be able to get a better result with a simpler filters. Depending on how you define 'better', but you should be able to get more precise smoothing from a better filter.

In the example above, we could rewrite it like this:

average = average * b + newvalue * (1-b);

As a take different values, the data is more or less smoothed. b=0 means no smoothing, b=1 means so much smoothing that all data is smoothed to the DC component of your signal, and in between means different amounts of smoothing. But it should always be better to get better performance with a better filter. Designing filters is pretty heavy duty Digital Signal Processing work, but there are tools around to help. E.g. the following is a filter that Tony Fisher's online digital filter design website made for me.

http://www-users.cs.york.ac.uk/~fisher/mkfilter/trad.html

/* Digital filter designed by mkfilter/mkshape/gencode   A.J. Fisher

Command line: /www/usr/fisher/helpers/mkfilter -Bu -Lp -o 2 -a 2.5000000000e-01 0.0000000000e+00 -l */

#define NZEROS 2
#define NPOLES 2
#define GAIN  3.414213562e+00

static float xv[NZEROS+1], yv[NPOLES+1];

static void filterloop()
  { for (;:wink:
      { xv[0] = xv[1]; xv[1] = xv[2];
        xv[2] = next input value / GAIN;
        yv[0] = yv[1]; yv[1] = yv[2];
        yv[2] =  (xv[0] + xv[2]) + 2 * xv[1]
                    + ( -0.1715728753 * yv[0]) + ( -0.0000000000 * yv[1]);
        next output value = yv[2];
      }
  }




Better smoothing might mean a better following of the average. But, you'd need to choose a frequency cutoff between 0 and half the sampling rate which smooths correctly. (For the previous example, I put in 44100Khz, but the only important thing is the proportion of that maximum frequency we choose as the cutoff, I chose 11050Hz, but it only really means that the cutoff is 1/4 of the sampling rate, whatever that rate. Higher and lower cutoffs means more or less smoothing.