Averaging + Slowing results

Hey there,

I'm looking to collect data from the A0 pin, average it, and send the average to processing approximately every 1 second.

I'm also looking to implement a feature where if the average result is the same as the previous result, no signal is sent (not sure if it's best to do this within processing).

Help with either of these problems would be super apprecaited - Thanks in advance!!

Ross

const int numReadings = 100;

int readings[numReadings];
int readIndex = 0;
int total = 0;
int average = 0;

int inputPin = A0;

void setup() {
  Serial.begin(9600);
  for (int thisReading = 0; thisReading < numReadings; thisReading++) {
  readings[thisReading] = 0;
    }
  }

void loop() {
  
  total = total - readings[readIndex];
  readings[readIndex] = analogRead(inputPin);
  total = total + readings[readIndex];
  readIndex = readIndex + 1;
  
  if (readIndex >= numReadings) {
  readIndex = 0;
  }

average = total / numReadings;
Serial.println(average);
delay(1);
}

I'm looking to collect data from the A0 pin

How many times?

average it,

There are several way that could be done.

and send the average to processing approximately every 1 second.

The blink without delay example shows how.

I'm also looking to implement a feature where if the average result is the same as the previous result, no signal is sent

This does not make sense if you are trying to send data on a regular basis. Dropping a send because the value is the same as last time will skew the results in the receiving end.

I think this is as simple as including a counter, perhaps to 10. This allows you to accumulate the data on ten trips round the loop. You then divide it by the count, display the result, reset the counter to zero, and go on.

There are many ways to skin a cat

With a microprocessor it is better to collect say 8, 16 or 32 samples (powers of 2) for averaging because dividing by powers of 2 is very much faster.

...R

Use a running average algorithm.

say you want to average N samples.

initialize variable SUM by reading once then multiply by N (or read N times)

average AVG is always SUM/N.

every 1 second get a new reading R, then update SUM = SUM - AVG + R
update AVG = SUM/N.

So it does not matter what your N is, the amount of work to update every second (or whatever interval) is exactly the same.

Robin2:
With a microprocessor it is better to collect say 8, 16 or 32 samples (powers of 2) for averaging because dividing by powers of 2 is very much faster.

...R

Yes, although with a whole second to play with in this case, the programmer has a huge safety margin.