I want to keep a running/rolling (I have heard both terms used in forum posts?) average of a constant stream of measurements from a ph sensor that outputs a reading every ~.265 seconds. I have tried to use the smoothing example but it the first ten or so "averages" are too low because there are (possibly?) no previous readings to compare it to. How can I change code up so that I get the full ten readings before it averages it. Or what would be a better way to do this?
#include <SoftwareSerial.h>
#define rxpin 12
#define txpin 11
SoftwareSerial mySerial(rxpin, txpin);
const int numReadings = 10;
const unsigned int MAX_INPUT = 50;
float readings[numReadings]; // the readings from the analog input
int index = 0; // the index of the current reading
float total = 0; // the running total
float average = 0; // the average
int inputPin = A0;
void setup()
{
// initialize serial communication with computer:
Serial.begin(38400);
mySerial.begin(38400);
// initialize all the readings to 0:
for (int thisReading = 0; thisReading < numReadings; thisReading++)
readings[thisReading] = 0;
mySerial.print("c");
mySerial.print('\r');
}
void loop() {
// subtract the last reading:
total= total - readings[index];
// read from the sensor:
readings[index] = getPH ();
delay(500);
// add the reading to the total:
total= total + readings[index];
// advance to the next position in the array:
index = index + 1;
// if we're at the end of the array...
if (index >= numReadings)
// ...wrap around to the beginning:
index = 0;
// calculate the average:
average = total / numReadings;
// send it to the computer as ASCII digits
Serial.println(average);
}
float getPH (){
static char input_line [MAX_INPUT];
static unsigned int input_pos = 0;
while (mySerial.available () > 0)
{
char inByte = mySerial.read ();
switch (inByte)
{
case '\r': // end of text
{
input_line [input_pos] = 0; // terminating null byte
char * data (input_line);
float pHmeasurement = atof(data);
input_pos = 0;// reset buffer for next time
return pHmeasurement;
break;
}
break;
case '\n': // discard carriage return
break;
default:
// keep adding if not full ... allow for terminating null byte
if (input_pos < (MAX_INPUT - 1))
input_line [input_pos++] = inByte;
break;
} // end of switch
} // end of incoming data
} // end of function
Here is the serial output if it helps:
0.00
0.70
1.40
2.10
2.80
3.51
4.21
4.91
5.61
6.31
7.01
7.01
7.01
Thanks